diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..c59730f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,14 @@ +# Exclude model/data dirs from build context (reduce context size, avoid permission issues) +ollama/ +comfyui/models/ +comfyui/output/ +comfyui/input/ +swarmui/data/ +swarmui/output/ +swarmui/dlbackend/ +swarmui/models/ +swarmui/extensions/ +swarmui/bin/ +.git/ +.env +.env.* diff --git a/.env.example b/.env.example index 74a4193..8614e42 100644 --- a/.env.example +++ b/.env.example @@ -1,11 +1,9 @@ -# Environment Variables -# Copy this file to .env and update with your actual values - -# Civitai API Configuration -CIVITAI_API_KEY=your_civitai_api_key_here - -# Hugging Face (model downloads, HF Hub; optional for private/gated models) -HUGGINGFACE_HUB_TOKEN=your_huggingface_token_here - -# Optional: Model download settings -CIVITAI_API_URL=https://civitai.com/api/v1 +OPENROUTER_API_KEY= +CIVITAI_API_KEY= +HF_TOKEN= +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 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 40f02b3..63178d7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,11 +21,11 @@ jobs: - name: Validate Docker Compose run: | - # Create a minimal .env file if it doesn't exist (for CI validation) - if [ ! -f .env ]; then - touch .env + # Compose stack lives under legacy/ after the OpenRouter operator cutover + if [ ! -f legacy/.env ]; then + touch legacy/.env fi - docker compose config > /dev/null + docker compose -f legacy/docker-compose.yml --project-directory legacy config > /dev/null echo "✅ Docker Compose configuration is valid" - name: Install kube-score @@ -104,18 +104,28 @@ jobs: wget -O /usr/local/bin/hadolint https://github.com/hadolint/hadolint/releases/latest/download/hadolint-Linux-x86_64 chmod +x /usr/local/bin/hadolint - - name: Validate ComfyUI Dockerfile + - name: Validate legacy ComfyUI Dockerfile run: | - echo "Validating Dockerfile.comfyui..." - hadolint Dockerfile.comfyui || echo "⚠️ ComfyUI Dockerfile had linting warnings (non-blocking)" + echo "Validating legacy/Dockerfile.comfyui..." + hadolint legacy/Dockerfile.comfyui || echo "⚠️ ComfyUI Dockerfile had linting warnings (non-blocking)" echo "✅ ComfyUI Dockerfile validation complete" - - name: Validate SwarmUI Dockerfile + - name: Validate legacy SwarmUI Dockerfile run: | - echo "Validating Dockerfile.swarmui..." - hadolint Dockerfile.swarmui || echo "⚠️ SwarmUI Dockerfile had linting warnings (non-blocking)" + echo "Validating legacy/Dockerfile.swarmui..." + hadolint legacy/Dockerfile.swarmui || echo "⚠️ SwarmUI Dockerfile had linting warnings (non-blocking)" echo "✅ SwarmUI Dockerfile validation complete" + - name: Validate Freya Dockerfiles + run: | + for f in Dockerfile Dockerfile.web; do + if [ -f "$f" ]; then + echo "Validating $f..." + hadolint "$f" || echo "⚠️ $f had linting warnings (non-blocking)" + fi + done + echo "✅ Freya Dockerfile validation complete" + test-scripts: name: Test Scripts runs-on: ubuntu-latest diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..7eea32b --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,17 @@ +name: Lint + +on: + push: + pull_request: + +jobs: + lint: + name: fmt + clippy + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - run: make vet diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..627f2fa --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,17 @@ +name: Tests + +on: + push: + pull_request: + +jobs: + test: + name: cargo test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - run: make test diff --git a/.gitignore b/.gitignore index 1d8a470..1777c1a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,13 @@ -# Python +# Rust +/target +/data +**/*.rs.bk + +# Web +web/node_modules +web/dist + +# Python (legacy) __pycache__/ *.py[cod] *$py.class @@ -8,10 +17,8 @@ env/ venv/ ENV/ .venv -pip-log.txt -pip-delete-this-directory.txt -# Models and outputs +# Models and outputs (legacy Compose volumes) comfyui/models/ comfyui/output/ comfyui/input/ @@ -28,34 +35,27 @@ openwebui/ *.pt *.pth -# IDE +# IDE / OS .vscode/ .idea/ *.swp *.swo *~ - -# OS .DS_Store Thumbs.db -# Docker -.dockerignore - # Logs *.log logs/ -# Environment +# Environment / secrets .env -.env.local +.env.* +!.env.example +*.pem -# .NET +# .NET (legacy SwarmUI) bin/ obj/ *.dll *.exe - -# Jupyter -.ipynb_checkpoints/ -*.ipynb diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..9db3728 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2987 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "multer", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "backoff" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b62ddb9cb1ec0a098ad4bbf9344d0713fa193ae1a80af55febcff2627b6a00c1" +dependencies = [ + "getrandom 0.2.17", + "instant", + "rand 0.8.8", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "clap" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "educe" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7bc049e1bd8cdeb31b68bbd586a9464ecf9f3944af3958a7a9d0f8b9799417" +dependencies = [ + "enum-ordinalize", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "enum-ordinalize" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89dd01549b09589510cf0647475075d12071456586d70f5c75c98ae2a5537677" +dependencies = [ + "enum-ordinalize-derive", +] + +[[package]] +name = "enum-ordinalize-derive" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a65863d15a4ce2888bd2f0f543cc963d3879c3a022c8ee43f6141d479a3ac815" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "freya-api" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "base64 0.22.1", + "chrono", + "clap", + "reqwest", + "serde", + "serde_json", + "serde_yaml", + "thiserror 2.0.21", + "tokio", + "tower-http", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "freya-crd" +version = "0.1.0" +dependencies = [ + "k8s-openapi", + "kube", + "schemars", + "serde", + "serde_json", +] + +[[package]] +name = "freya-operator" +version = "0.1.0" +dependencies = [ + "anyhow", + "freya-crd", + "futures", + "k8s-openapi", + "kube", + "reqwest", + "serde", + "serde_json", + "serde_yaml", + "thiserror 2.0.21", + "tokio", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "freya-worker" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "base64 0.22.1", + "clap", + "reqwest", + "serde", + "serde_json", + "tokio", + "tower-http", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "headers" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc2700e3fe555c3310aa7286cac6167449f2c87e0eb58769c9208a1c58a1d106" +dependencies = [ + "base64 0.22.1", + "bytes", + "headers-core", + "http", + "httpdate", + "mime", + "sha1", +] + +[[package]] +name = "headers-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" +dependencies = [ + "http", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "hostname" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" +dependencies = [ + "cfg-if", + "libc", + "windows-link", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "http-range-header" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c" + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-http-proxy" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd1d471ea2f65ba45eddb1d6ab7d58ac2671d2d4ac14da5c6516ae1d97e1327a" +dependencies = [ + "bytes", + "futures-util", + "headers", + "http", + "hyper", + "hyper-rustls", + "hyper-util", + "pin-project-lite", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "log", + "rustls", + "rustls-native-certs", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-timeout" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" +dependencies = [ + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "json-patch" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08" +dependencies = [ + "jsonptr", + "serde", + "serde_json", + "thiserror 1.0.69", +] + +[[package]] +name = "jsonpath-rust" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c00ae348f9f8fd2d09f82a98ca381c60df9e0820d8d79fce43e649b4dc3128b" +dependencies = [ + "pest", + "pest_derive", + "regex", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "jsonptr" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "k8s-openapi" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c75b990324f09bef15e791606b7b7a296d02fc88a344f6eba9390970a870ad5" +dependencies = [ + "base64 0.22.1", + "chrono", + "serde", + "serde-value", + "serde_json", +] + +[[package]] +name = "kube" +version = "0.98.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32053dc495efad4d188c7b33cc7c02ef4a6e43038115348348876efd39a53cba" +dependencies = [ + "k8s-openapi", + "kube-client", + "kube-core", + "kube-derive", + "kube-runtime", +] + +[[package]] +name = "kube-client" +version = "0.98.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d34ad38cdfbd1fa87195d42569f57bb1dda6ba5f260ee32fef9570b7937a0c9" +dependencies = [ + "base64 0.22.1", + "bytes", + "chrono", + "either", + "futures", + "home", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-http-proxy", + "hyper-rustls", + "hyper-timeout", + "hyper-util", + "jsonpath-rust", + "k8s-openapi", + "kube-core", + "pem", + "rustls", + "rustls-pemfile", + "secrecy", + "serde", + "serde_json", + "serde_yaml", + "thiserror 2.0.21", + "tokio", + "tokio-util", + "tower", + "tower-http", + "tracing", +] + +[[package]] +name = "kube-core" +version = "0.98.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97aa830b288a178a90e784d1b0f1539f2d200d2188c7b4a3146d9dc983d596f3" +dependencies = [ + "chrono", + "form_urlencoded", + "http", + "json-patch", + "k8s-openapi", + "schemars", + "serde", + "serde-value", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "kube-derive" +version = "0.98.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37745d8a4076b77e0b1952e94e358726866c8e14ec94baaca677d47dcdb98658" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "serde_json", + "syn 2.0.119", +] + +[[package]] +name = "kube-runtime" +version = "0.98.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a41af186a0fe80c71a13a13994abdc3ebff80859ca6a4b8a6079948328c135b" +dependencies = [ + "ahash", + "async-broadcast", + "async-stream", + "async-trait", + "backoff", + "educe", + "futures", + "hashbrown 0.15.5", + "hostname", + "json-patch", + "jsonptr", + "k8s-openapi", + "kube-client", + "parking_lot", + "pin-project", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pest" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ec53fd1d256900a9a771bf2720d42cef6f8bc91b4e25065fbd291e3e7222576" +dependencies = [ + "memchr", + "pest_stack_guard", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adcf794fd301ddc20818a6b4de85ed507f4b45300245cec948982e69e12e3bd7" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3073afae5db334c25dea9fc3e230a4f191e920c1df080cb9c0b37c9ce1dbb41" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "pest_meta" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bc7f614b3742541642af1685faaa910bf6333e3cd3729c2cccd118146a57327" +dependencies = [ + "pest", +] + +[[package]] +name = "pest_stack_guard" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ac6154fd4418b8f0b82532c59c26f303f9ca59a64c883e8ce3971fd82733439" +dependencies = [ + "psm", + "stacker", +] + +[[package]] +name = "pin-project" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.4", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "secrecy" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a" +dependencies = [ + "zeroize", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float", + "serde", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "slab", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "base64 0.22.1", + "bitflags", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "http-range-header", + "httpdate", + "mime", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "tokio", + "tokio-util", + "tower", + "tower-layer", + "tower-service", + "tracing", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "ucd-trie" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f20bdbfc9915686faa18fb5bbe8b4552778505defbf9f12289beefbc44092a6" + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..7b0c9be --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,43 @@ +[workspace] +resolver = "2" +members = [ + "crates/freya-crd", + "crates/freya-operator", + "crates/freya-api", + "crates/freya-worker", +] +default-members = [ + "crates/freya-crd", + "crates/freya-operator", + "crates/freya-api", + "crates/freya-worker", +] + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +repository = "https://github.com/DataKnifeAI/freya" +authors = ["DataKnifeAI"] + +[workspace.dependencies] +freya-crd = { path = "crates/freya-crd" } +anyhow = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +serde_yaml = "0.9" +schemars = "0.8" +thiserror = "2" +tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal", "fs", "io-util"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +kube = { version = "0.98", default-features = true, features = ["runtime", "derive", "client"] } +k8s-openapi = { version = "0.24", features = ["v1_32"] } +axum = { version = "0.8", features = ["multipart"] } +tower-http = { version = "0.6", features = ["cors", "fs", "trace"] } +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +chrono = { version = "0.4", features = ["serde"] } +uuid = { version = "1", features = ["v4", "serde"] } +base64 = "0.22" +futures = "0.3" +clap = { version = "4", features = ["derive", "env"] } diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..05a9f74 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,23 @@ +FROM rust:1.87-bookworm AS builder +WORKDIR /src +COPY Cargo.toml rust-toolchain.toml ./ +COPY crates ./crates +COPY packs ./packs +RUN cargo build --release -p freya-operator -p freya-api -p freya-worker + +FROM gcr.io/distroless/cc-debian12:nonroot AS operator +COPY --from=builder /src/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 --from=builder /src/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 worker +COPY --from=builder /src/target/release/freya-worker /usr/local/bin/freya-worker +USER nonroot:nonroot +ENTRYPOINT ["/usr/local/bin/freya-worker"] diff --git a/Dockerfile.web b/Dockerfile.web new file mode 100644 index 0000000..5c5918e --- /dev/null +++ b/Dockerfile.web @@ -0,0 +1,14 @@ +FROM node:22-bookworm AS build +WORKDIR /web +COPY web/package.json web/package-lock.json* ./ +RUN npm install +COPY web/ ./ +RUN npm run build + +FROM nginx:1.27-alpine +# Official image runs envsubst on /etc/nginx/templates/*.template → conf.d/ +ENV FREYA_API_UPSTREAM=http://freya-api:8080 +ENV FREYA_API_TOKEN= +COPY web/nginx.conf /etc/nginx/templates/default.conf.template +COPY --from=build /web/dist /usr/share/nginx/html +EXPOSE 80 diff --git a/Makefile b/Makefile index fd62803..437a8ea 100644 --- a/Makefile +++ b/Makefile @@ -1,217 +1,76 @@ -.PHONY: help check-deps fix-docker-group build build-comfyui build-swarmui up down sui sui-rebuild swarmui-update cui llm llm-pull llm-import-hf llm-list llm-rm llm-logs swarmui-rebuild swarmui-extensions-check restart logs clean - -help: ## Show this help message - @echo 'Usage: make [target]' - @echo '' - @echo 'Available targets:' - @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf " %-15s %s\n", $$1, $$2}' $(MAKEFILE_LIST) - -check-deps: ## Check Docker, Docker Compose, Git; install Git on Linux if missing; warn on NVIDIA - chmod +x scripts/linux/check-deps.sh && ./scripts/linux/check-deps.sh - -fix-docker-group: ## Create docker group if missing, add current user (fixes permission denied) - chmod +x scripts/linux/add-docker-group.sh && ./scripts/linux/add-docker-group.sh - -setup: ## Run initial directory setup (runs check-deps first, then creates dirs) - chmod +x scripts/linux/setup.sh && ./scripts/linux/setup.sh - -quick-setup: ## Non-interactive setup: directories + ComfyUI starter models (SDXL + VAE) - chmod +x scripts/linux/quick-setup.sh && ./scripts/linux/quick-setup.sh - -download-starter-models: ## Download ComfyUI starter models (SDXL base + VAE, ~7.3 GB) - chmod +x scripts/linux/download-model.sh && ./scripts/linux/download-model.sh starter - -download-model: ## Download one ComfyUI model (make download-model TYPE=checkpoint URL=... [FILE=...]) - @if [ -z "$(TYPE)" ] || [ -z "$(URL)" ]; then \ - echo "Usage: make download-model TYPE= URL= [FILE=]"; \ - echo "Types: checkpoint, lora, vae, controlnet, upscale, embedding"; \ - echo "See docs/model-downloads.md for Hugging Face / Civitai (account + API key required)."; \ - exit 1; \ - fi - chmod +x scripts/linux/download-model.sh - ./scripts/linux/download-model.sh "$(TYPE)" "$(URL)" "$(FILE)" - -build: ## Build all Docker images - docker compose build - -build-comfyui: ## Build ComfyUI image only - docker compose build comfyui - -build-swarmui: ## Build SwarmUI image only - docker compose build swarmui - -build-no-cache: ## Build all images without cache - docker compose build --no-cache - -up: ## Start all services - docker compose up -d - -sui: ## SwarmUI + Ollama (stops ComfyUI first; updates SwarmUI; preserves running containers) - -docker compose stop comfyui 2>/dev/null || true - docker compose up -d swarmui ollama - @$(MAKE) swarmui-update - -swarmui-update: ## Pull latest SwarmUI, rebuild if needed, and restart (requires swarmui container) - @docker ps >/dev/null 2>&1 || (echo "Error: Docker not accessible. Run: make fix-docker-group, then newgrp docker" && exit 1) - @docker compose up -d swarmui 2>/dev/null || true - @i=0; while [ $$i -lt 90 ]; do \ - status=$$(docker compose ps swarmui --format '{{.Health}}' 2>/dev/null); \ - echo "$$status" | grep -q healthy && break; \ - docker compose ps swarmui --status running -q 2>/dev/null | grep -q . || { sleep 1; i=$$((i+1)); continue; }; \ - [ -z "$$status" ] && break; \ - i=$$((i+1)); sleep 1; \ - done - @docker compose ps swarmui --status running -q 2>/dev/null | grep -q . \ - || (echo "Error: SwarmUI not running. Start with: docker compose up -d swarmui" && exit 1) - @echo "Updating SwarmUI (git pull + dotnet build if needed)..." - @docker compose exec -T swarmui bash -c 'set -e; cd /app/SwarmUI; \ - prior=$$(git rev-parse HEAD); \ - for attempt in 1 2 3 4 5; do \ - if git fetch origin master && git reset --hard origin/master; then break; fi; \ - [ "$$attempt" -eq 5 ] && exit 1; \ - echo "Git fetch failed (attempt $$attempt), retrying..."; sleep 2; \ - done; \ - new=$$(git rev-parse HEAD); \ - rm -f src/bin/must_rebuild; \ - if [ "$$prior" != "$$new" ] || [ ! -f src/bin/live_release/SwarmUI.dll ]; then \ - echo "Building SwarmUI ($$prior -> $$new)..."; \ - dotnet build src/SwarmUI.csproj -c Release -o src/bin/live_release; \ - touch src/bin/.swarmui_restarted; \ - else \ - echo "SwarmUI source already up to date; skipping build."; \ - fi' - @if docker compose exec -T swarmui test -f /app/SwarmUI/src/bin/.swarmui_restarted 2>/dev/null; then \ - docker compose exec -T swarmui rm -f /app/SwarmUI/src/bin/.swarmui_restarted; \ - docker compose restart swarmui; \ - fi - -sui-rebuild: ## Restart SwarmUI + Ollama (SwarmUI builds extensions at startup; use after adding extension via UI) - @docker ps >/dev/null 2>&1 || (echo "Error: Docker not accessible. Run: make fix-docker-group, then newgrp docker" && exit 1) - docker compose down && docker compose up -d swarmui ollama - -cui: ## ComfyUI only (stops other compose services first) - docker compose down && docker compose up -d comfyui - -llm: ## Ollama only (for SwarmUI MagicPrompt / LLM API; stops other compose services first) - docker compose down && docker compose up -d ollama - -down: ## Stop all services - docker compose down - -restart: ## Restart all services - docker compose restart - -logs: ## Show logs from all services - docker compose logs -f - -logs-comfyui: ## Show logs from ComfyUI service - docker compose logs -f comfyui - -logs-swarmui: ## Show logs from SwarmUI service - docker compose logs -f swarmui - -llm-logs: ## Show logs from Ollama service - docker compose logs -f ollama - -clean: ## Remove containers, volumes, and images - docker compose down -v - -ps: ## Show running containers - docker compose ps - -shell-comfyui: ## Open shell in ComfyUI container - docker compose exec comfyui /bin/bash - -shell-swarmui: ## Open shell in SwarmUI container - docker compose exec swarmui /bin/bash - -swarmui-rebuild: ## [Debug] Force rebuild inside container without git pull. Prefer: make swarmui-update - @docker ps >/dev/null 2>&1 || (echo "Error: Docker not accessible. Run: make fix-docker-group, then newgrp docker" && exit 1) - @docker compose ps swarmui 2>/dev/null | grep -q Up || (echo "Error: SwarmUI not running. Start with: make sui" && exit 1) - docker compose exec swarmui bash -c "set -e; cd /app/SwarmUI && dotnet build src/SwarmUI.csproj -c Release -o src/bin/live_release" - docker compose restart swarmui - -swarmui-extensions-check: ## [Debug] List extensions dir and run build; use if extension not showing after restart - @docker ps >/dev/null 2>&1 || (echo "Error: Docker not accessible. Run: make fix-docker-group, then newgrp docker" && exit 1) - @docker compose ps swarmui 2>/dev/null | grep -q Up || (echo "Error: SwarmUI not running. Start with: make sui" && exit 1) - @echo "=== Extension dir (host: swarmui/extensions) ===" - @docker compose exec swarmui ls -la /app/SwarmUI/src/Extensions/ 2>/dev/null || true - @echo "=== Extension subdirs (.cs) ===" - @docker compose exec swarmui find /app/SwarmUI/src/Extensions -maxdepth 2 -type f -name "*.cs" 2>/dev/null || true - @echo "=== Manual build (SwarmUI usually builds at startup) ===" - docker compose exec swarmui bash -c "set -e; cd /app/SwarmUI && dotnet build src/SwarmUI.csproj -c Release -o src/bin/live_release -v minimal" - -llm-pull: ## Download Ollama model (usage: make llm-pull MODEL=dolphin3) - @if [ -z "$(MODEL)" ]; then \ - echo "Usage: make llm-pull MODEL="; \ - echo "Example: make llm-pull MODEL=dolphin3 (default for MagicPrompt: https://ollama.com/library/dolphin3)"; \ - echo "Browse available models: https://ollama.com/library"; \ - echo "Popular: dolphin3, llama3.2:1b, llama3.2:3b, mistral, gemma2:7b"; \ - exit 1; \ - fi - @echo "Pulling Ollama model: $(MODEL)" - @docker compose exec ollama ollama pull $(MODEL) || \ - docker compose run --rm ollama ollama pull $(MODEL) - -llm-import-hf: ## Import GGUF model from Hugging Face into Ollama (usage: make llm-import-hf REPO=user/repo [QUANT=Q4_K_M]) - @if [ -z "$(REPO)" ]; then \ - echo "Usage: make llm-import-hf REPO= [QUANT=]"; \ - echo "Example: make llm-import-hf REPO=bartowski/Llama-3.2-1B-Instruct-GGUF"; \ - echo "Example: make llm-import-hf REPO=bartowski/Llama-3.2-3B-Instruct-GGUF QUANT=IQ3_M"; \ - echo "Browse GGUF models: https://huggingface.co/models?library=gguf"; \ - echo "Ollama uses hf.co/REPO; default quant is Q4_K_M when present."; \ - echo ""; \ - echo "Note: Only GGUF repos work. Transformers/Safetensors models (e.g. dphn/dolphin-vision-72b)"; \ - echo "cannot be imported unless a GGUF version exists on Hugging Face."; \ - exit 1; \ - fi - @HF_MODEL="hf.co/$(REPO)"; \ - if [ -n "$(QUANT)" ]; then HF_MODEL="$$HF_MODEL:$(QUANT)"; fi; \ - echo "Importing from Hugging Face: $$HF_MODEL"; \ - docker compose exec ollama ollama pull "$$HF_MODEL" || \ - docker compose run --rm ollama ollama pull "$$HF_MODEL" - -llm-list: ## List installed Ollama models and show available models link - @echo "=== Available models ===" - @echo "Browse: https://ollama.com/library" - @echo "" - @echo "Default for MagicPrompt (control + compatibility): dolphin3 — https://ollama.com/library/dolphin3" - @echo "Other options: Light (1-3B) llama3.2:1b, phi3:mini | Balanced (7-8B) mistral, gemma2:7b" - @echo "" - @echo "=== Installed models ===" - @docker compose exec ollama ollama list 2>/dev/null || \ - docker compose run --rm ollama ollama list || \ - (echo "Ollama not running. Start with: make llm" && exit 1) - @echo "" - @echo "Pull a model: make llm-pull MODEL=" - @echo "Import from Hugging Face (GGUF): make llm-import-hf REPO=user/repo [QUANT=...]" - @echo "Remove a model: make llm-rm MODEL=" - -llm-rm: ## Remove an Ollama model (usage: make llm-rm MODEL=dolphin3) - @if [ -z "$(MODEL)" ]; then \ - echo "Usage: make llm-rm MODEL="; \ - echo "Example: make llm-rm MODEL=dolphin3"; \ - echo "List installed models: make llm-list"; \ - exit 1; \ - fi - @echo "Removing Ollama model: $(MODEL)" - @docker compose exec ollama ollama rm $(MODEL) || \ - docker compose run --rm ollama ollama rm $(MODEL) - -check-gpu: ## Run GPU diagnostic check - chmod +x scripts/linux/check-gpu.sh && ./scripts/linux/check-gpu.sh - -check-gpu-comfyui: ## Check GPU availability in ComfyUI container - docker compose exec comfyui python3 -c "import torch; print(f'CUDA available: {torch.cuda.is_available()}'); print(f'GPU count: {torch.cuda.device_count()}'); [torch.cuda.is_available()] and print(f'GPU name: {torch.cuda.get_device_name(0)}')" - -check-gpu-swarmui: ## Check GPU availability in SwarmUI container - docker compose exec swarmui nvidia-smi || echo "nvidia-smi not available, checking CUDA..." - @docker compose exec swarmui dotnet --version || echo "DotNET check failed" - -status: ## Show service status and URLs - @echo "=== Service Status ===" - @docker compose ps - @echo "\n=== Access URLs ===" - @echo "ComfyUI: http://localhost:8188" - @echo "SwarmUI: http://localhost:7801" - @echo "Ollama API: http://localhost:11434" +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 + +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 + +all: build + +help: ## Show this help + @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf " %-18s %s\n", $$1, $$2}' $(MAKEFILE_LIST) + +build: ## Build workspace + $(CARGO) build --workspace + +release: ## Build release binaries + $(CARGO) build --workspace --release + +test: ## Run tests + $(CARGO) test --workspace + +fmt: ## Format Rust sources + $(CARGO) fmt --all + +fmt-check: ## Check formatting (CI) + $(CARGO) fmt --all -- --check + +lint: ## Clippy with warnings denied + $(CARGO) clippy --workspace --all-targets -- -D warnings + +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 + +install: manifests ## Apply CRDs + kubectl apply -f config/crd/freya.dataknife.ai_crds.yaml + kubectl apply -f config/rbac/ + +deploy: ## Deploy operator + sample studio (edit secrets first) + kubectl apply -k config/default + +run-api: ## Run Freya API locally + $(CARGO) run -p freya-api -- --bind 127.0.0.1:8080 + +run-worker: ## Run diffusion worker stub locally + $(CARGO) run -p freya-worker -- --port 8091 + +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) + @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" + +.PHONY: mock-ui +mock-ui: ## Interactive Freya UI mock (no API / keys required) + cd web && npm install && npm run dev:mock + +clean: + $(CARGO) clean + +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.web -t $(WEB_IMG) . diff --git a/README.md b/README.md index 2c0444f..2301ded 100644 --- a/README.md +++ b/README.md @@ -1,133 +1,93 @@ -# Freya - Stable Diffusion with UI on Kubernetes +# Freya ![Freya](freya.png) -A Kubernetes-ready platform for running ComfyUI and SwarmUI Stable Diffusion interfaces with discrete GPU support. Both UIs are built from source using custom Docker images. +Kubernetes operator and approachable NL image studio for [DataKnifeAI](https://dataknife.ai). -## Features +Freya removes the old “download GB → open Comfy/Swarm → click forever” loop: -- 🎨 **ComfyUI**: Advanced node-based workflow interface for Stable Diffusion (built from source) -- 🐝 **SwarmUI**: Modular AI image and video generation web interface (built from source) -- 💬 **Ollama**: Local LLM API; use inside SwarmUI via the [MagicPrompt extension](https://github.com/HartsyAI/SwarmUI-MagicPromptExtension) for prompt generation and enhancement -- 🐳 **Docker Support**: Custom-built containers with GPU support for local development -- ☸️ **Kubernetes Ready**: Designed to run in Kubernetes clusters -- 🚀 **GPU Accelerated**: Full CUDA support for discrete GPUs -- 🔧 **Custom Builds**: All images built from source, not using public images +1. **Describe** in natural language (no comma-tag recipes) +2. Optionally **ask for suggestions**; Freya **plans** and writes the model brief for you +3. **Generate** via OpenRouter image models **or** a local/remote diffusion worker with LoRAs +4. Browse the **gallery** and remix -## Quick Start +The previous Compose/ComfyUI/SwarmUI/Ollama stack is preserved under [`legacy/`](legacy/) for reference — it is not required for the new path. -### Prerequisites +## Quick start (local) -- **Platform**: Linux (primary) or Windows only (NVIDIA support; macOS not supported). See [Installation Guide](docs/installation.md). -- **Linux / WSL2**: Docker Engine 20.10+ and Docker Compose v2 — [check and install](docs/installation.md#checking-and-installing-docker) per your OS. -- **Windows**: From repo root run **PowerShell** `.\make.ps1` (same name as Linux `make`); or use WSL2 and `make`. Docker Desktop (WSL2 backend) recommended. -- **GPU**: NVIDIA GPU with 8GB+ VRAM (16GB+ recommended); NVIDIA Container Toolkit required on Linux. - -See [Installation Guide](docs/installation.md) for dependency check/install and [Windows / PowerShell](docs/installation.md#windows) setup. - -### Getting Started +**UI mock only** (no keys/API — for layout and flow tweaks): ```bash -# Setup directories -make setup - -# Optional: Quick setup = dirs + ComfyUI starter models (SDXL + VAE); add more via make download-model -make quick-setup - -# Build images -make build - -# Start services -make up +make mock-ui # or: cd web && npm i && npm run dev:mock ``` -### Access the Interfaces - -- **ComfyUI**: http://localhost:8188 -- **SwarmUI**: http://localhost:7801 -- **Ollama API**: http://localhost:11434 (use from SwarmUI via MagicPrompt extension) - -### Example: SwarmUI with a sample prompt and model - -![Freya UI](freya-ui.png) +**Full stack:** -Try this in **SwarmUI** (http://localhost:7801) after downloading the model: - -**Model:** [SDXL Yamer's Anime Unstable Illustrator](https://civitai.com/models/76489/sdxl-yamers-anime-unstable-illustrator?modelVersionId=377674) (Civitai — checkpoint, ~6.46 GB SafeTensors). Place the file in `swarmui/data/Models/` or use SwarmUI’s built-in downloader. +```bash +export OPENROUTER_API_KEY=sk-or-... +# optional — search/install Civitai LoRAs onto a worker +export CIVITAI_API_KEY=... -**Positive prompt:** -``` -45 megapixel, the ethereal beauty of a mystical landscape under the red moonlight, The scene should be illuminated by a large, radiant moon, casting its glow upon a twisted, yet majestic tree with blossoms that seem to sparkle in the night, The tree's roots should be deeply embedded into rocky terrain, symbolizing its ancient existence, In the background, towering mountains loom, their peaks veiled in mist, A serene lake at the foot of the mountains reflects the moon's luminescence, Incorporate elements that evoke a sense of magic and mystery -``` +make run-api # :8080 +cd web && npm install && npm run dev # :5173 -**Negative prompt:** -``` -bad quality, bad anatomy, worst quality, low quality, low resolution, extra fingers, blur, blurry, ugly, wrong proportions, watermark, image artifacts, lowres, ugly, jpeg artifacts, deformed, noisy image +# optional GPU / remote worker stub +make run-worker # :8091 +# then Settings → Diffusion worker URL → http://127.0.0.1:8091 ``` -**Suggested settings (from model page):** Resolution 1024×1024 (or 576×1024, 768×1024), Steps 20–50, CFG 5–20. +In the UI **Settings** tab you can paste: -## Makefile Commands +- **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 -On **Linux** or **WSL2** run `make` from the repo root. On **Windows** run `.\make.ps1` from the repo root (e.g. `.\make.ps1 help`, `.\make.ps1 up`). See [Installation Guide](docs/installation.md#windows). +## Cluster ```bash -make help # Show all available commands -make build # Build all Docker images -make up # Start all services -make down # Stop all services -make sui # SwarmUI + Ollama (stops others first; updates SwarmUI) -make cui # ComfyUI only (stops others first) -make llm # Ollama only (stops others first) -make swarmui-update # Pull latest SwarmUI, rebuild, and restart -make swarmui-rebuild # Rebuild SwarmUI from current source (no git pull) -make logs # View logs from all services -make restart # Restart services -make status # Show service status and URLs -make check-gpu-comfyui # Verify GPU access in ComfyUI -make check-gpu-swarmui # Verify GPU access in SwarmUI -make llm-pull MODEL=dolphin3 # Pull default Ollama model (MagicPrompt); see https://ollama.com/library/dolphin3 -make llm-list # List installed models + browse link -make llm-rm MODEL=dolphin3 # Remove an Ollama model -make llm-logs # View Ollama logs -``` +make manifests install +kubectl apply -k config/default -See [Architecture Guide](docs/architecture.md) for complete command reference. +kubectl create ns freya +kubectl -n freya create secret generic freya-openrouter --from-literal=apiKey="$OPENROUTER_API_KEY" +kubectl -n freya create secret generic freya-civitai --from-literal=apiKey="$CIVITAI_API_KEY" +kubectl -n freya create secret generic freya-api-token --from-literal=token="$(openssl rand -hex 32)" +kubectl -n freya create secret generic freya-worker-token --from-literal=apiKey="$(openssl rand -hex 32)" -## Documentation +# remote GPU box +kubectl apply -f config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml +# or in-cluster GPU +# kubectl apply -f config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml + +kubectl apply -f config/samples/freya_v1alpha1_freyastudio.yaml +``` -- [Installation Guide](docs/installation.md) - System requirements and setup -- [GPU Compatibility](docs/gpu-compatibility.md) - Compatible GPU cards -- [Kubernetes Deployment](docs/kubernetes.md) - Deploy to Kubernetes -- [Model Management](docs/MODELS.md) - Download and manage models -- [SwarmUI Video Guide](docs/swarmui-video-guide.md) - Beginner’s guide to T2V/I2V with SwarmUI (links to [HF guide](https://huggingface.co/blog/MonsterMMORPG/beginners-guide-generate-videos-with-swarmui)) -- [Architecture](docs/architecture.md) - Project structure and services -- [SwarmUI MagicPrompt](docs/swarmui-magicprompt.md) - Use Ollama inside SwarmUI for prompt generation (MagicPrompt extension) -- [MagicPrompt Default Prompts](docs/magicprompt-default-prompts.md) - Optimized Freya system prompts for Ollama/dolphin3 -- [MagicPrompt Custom Instructions](docs/magicprompt-custom-instructions.md) - Create custom instructions for specific styles and workflows -- [Troubleshooting](docs/troubleshooting.md) - Common issues and solutions +### Workers: in-cluster or remote physical -## Requirements +| Placement | Spec | Use when | +|-----------|------|----------| +| `incluster` | GPU Deployment + models PVC | Cluster has `nvidia.com/gpu` | +| `external` | `externalEndpoint: http://host:8091` | Physical box / bare-metal GPU | -- **OS**: Linux (Ubuntu, Debian, Fedora, RHEL, openSUSE, Arch) or Windows via WSL2 — see [installation](docs/installation.md) -- **GPU**: NVIDIA GPU with CUDA 12.4+ or 13.x (images use 13.1.1) -- **VRAM**: Minimum 8GB (16GB+ recommended for both services) -- **RAM**: Minimum 16GB system RAM -- **Storage**: Minimum 50GB free space +`FreyaModelAsset` (or UI **Civitai → Install to worker**) pushes LoRAs onto that worker so they show up for local generation. -See [Installation Guide](docs/installation.md) for detailed requirements. +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. -## Notes +## CRDs -- Models are downloaded on first use and cached in mounted volumes -- Generated images are saved to respective `output/` directories -- First build may take 15-30 minutes -- Both services can run simultaneously with 16GB+ GPU memory +- `FreyaStudio` — API + UI + gallery; OpenRouter + **Civitai** + HF secret refs +- `FreyaGeneration` — declarative generate job +- `FreyaStyle` — curated style packs +- `FreyaDiffusionWorker` — in-cluster or external engine +- `FreyaModelAsset` — install weights onto a worker -## Acknowledgments +## Docs -This project was built with [Cursor](https://cursor.sh) using the Composer model. +- [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 ## License -MIT +Apache-2.0 — see [LICENSE](LICENSE). diff --git a/config/crd/freya.dataknife.ai_crds.yaml b/config/crd/freya.dataknife.ai_crds.yaml new file mode 100644 index 0000000..b18c42a --- /dev/null +++ b/config/crd/freya.dataknife.ai_crds.yaml @@ -0,0 +1,615 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: freyastudios.freya.dataknife.ai +spec: + group: freya.dataknife.ai + names: + categories: [] + kind: FreyaStudio + plural: freyastudios + shortNames: + - fstudio + singular: freyastudio + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: Auto-generated derived type for FreyaStudioSpec via `CustomResource` + properties: + spec: + description: 'Namespaced Freya studio: API + UI + gallery.' + properties: + apiImage: + description: Image reference for Freya components. + nullable: true + properties: + pullPolicy: + nullable: true + type: string + repository: + nullable: true + type: string + tag: + nullable: true + type: string + type: object + apiTokenSecretRef: + description: Secret holding `FREYA_API_TOKEN` for the API (and UI nginx proxy). Set for non-dev / Ingress. + nullable: true + properties: + key: + default: apiKey + type: string + name: + type: string + required: + - name + type: object + chatBackend: + default: + kind: openrouter + properties: + baseUrl: + description: When kind=vllm, OpenAI-compatible base URL. + nullable: true + type: string + kind: + default: openrouter + enum: + - openrouter + - vllm + type: string + type: object + civitai: + default: {} + description: Civitai API key for browsing/installing LoRAs & checkpoints onto workers. + properties: + secretRef: + description: Secret holding the Civitai API token (create from UI or `kubectl create secret`). + nullable: true + properties: + key: + default: apiKey + type: string + name: + type: string + required: + - name + type: object + type: object + diffusionWorkerRef: + description: Optional FreyaDiffusionWorker name in the same namespace. + nullable: true + type: string + huggingFace: + default: {} + description: Optional Hugging Face token for gated checkpoints. + properties: + secretRef: + description: Reference to a Secret key holding credentials. + nullable: true + properties: + key: + default: apiKey + type: string + name: + type: string + required: + - name + type: object + type: object + ingress: + default: + enabled: false + properties: + className: + nullable: true + type: string + enabled: + default: false + type: boolean + host: + 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 + secretRef: + key: apiKey + name: freya-openrouter + properties: + baseUrl: + default: https://openrouter.ai/api/v1 + type: string + chatModel: + default: openrouter/auto + description: Default chat / plan model id (OpenRouter). + type: string + imageModel: + default: black-forest-labs/flux.2-klein-4b + description: Default cloud image model id (OpenRouter). + type: string + secretRef: + description: Reference to a Secret key holding credentials. + properties: + key: + default: apiKey + type: string + name: + type: string + required: + - name + type: object + required: + - secretRef + type: object + replicas: + default: 1 + format: int32 + type: integer + storage: + default: + gallerySize: 20Gi + properties: + gallerySize: + default: 20Gi + type: string + storageClassName: + nullable: true + type: string + type: object + uiImage: + description: Image reference for Freya components. + nullable: true + properties: + pullPolicy: + nullable: true + type: string + repository: + nullable: true + type: string + tag: + nullable: true + type: string + type: object + type: object + status: + nullable: true + properties: + apiEndpoint: + nullable: true + type: string + observedGeneration: + format: int64 + nullable: true + type: integer + phase: + nullable: true + type: string + uiEndpoint: + nullable: true + type: string + type: object + required: + - spec + title: FreyaStudio + type: object + served: true + storage: true + subresources: + status: {} + +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: freyagenerations.freya.dataknife.ai +spec: + group: freya.dataknife.ai + names: + categories: [] + kind: FreyaGeneration + plural: freyagenerations + shortNames: + - fgen + singular: freyageneration + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .status.backend + name: Backend + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: Auto-generated derived type for FreyaGenerationSpec via `CustomResource` + properties: + spec: + description: Declarative image generation request. + properties: + backend: + default: auto + description: Generation backend selection. + enum: + - auto + - openrouter + - local + type: string + enhance: + default: auto + description: '`off` | `on` | `auto`' + type: string + loras: + items: + properties: + name: + type: string + scale: + default: 1.0 + format: float + type: number + required: + - name + type: object + type: array + model: + nullable: true + type: string + negativePrompt: + nullable: true + type: string + prompt: + type: string + seed: + format: int64 + nullable: true + type: integer + size: + nullable: true + type: string + studioRef: + description: FreyaStudio that owns API routing (same namespace). + nullable: true + type: string + styleRef: + nullable: true + type: string + required: + - prompt + type: object + status: + nullable: true + properties: + artifactPath: + nullable: true + type: string + backend: + nullable: true + type: string + enhancedPrompt: + nullable: true + type: string + message: + nullable: true + type: string + phase: + nullable: true + type: string + type: object + required: + - spec + title: FreyaGeneration + type: object + served: true + storage: true + subresources: + status: {} + +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: freyastyles.freya.dataknife.ai +spec: + group: freya.dataknife.ai + names: + categories: [] + kind: FreyaStyle + plural: freyastyles + shortNames: + - fstyle + singular: freyastyle + scope: Namespaced + versions: + - additionalPrinterColumns: [] + name: v1alpha1 + schema: + openAPIV3Schema: + description: Auto-generated derived type for FreyaStyleSpec via `CustomResource` + properties: + spec: + description: Curated style pack (Civitai-inspired metadata, not weight hosting by itself). + properties: + backend: + default: auto + description: Generation backend selection. + enum: + - auto + - openrouter + - local + type: string + displayName: + type: string + examplePrompt: + type: string + localCheckpoint: + nullable: true + type: string + loras: + items: + properties: + name: + type: string + scale: + default: 1.0 + format: float + type: number + required: + - name + type: object + type: array + openRouterModel: + nullable: true + type: string + recommendedSize: + nullable: true + type: string + tags: + items: + type: string + type: array + thumbnailUrl: + nullable: true + type: string + triggerWords: + nullable: true + type: string + required: + - displayName + - examplePrompt + type: object + status: + nullable: true + properties: + phase: + nullable: true + type: string + type: object + required: + - spec + title: FreyaStyle + type: object + served: true + storage: true + subresources: + status: {} + +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: freyadiffusionworkers.freya.dataknife.ai +spec: + group: freya.dataknife.ai + names: + categories: [] + kind: FreyaDiffusionWorker + plural: freyadiffusionworkers + shortNames: + - fdiff + singular: freyadiffusionworker + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .spec.engine + name: Engine + type: string + - jsonPath: .spec.placement + name: Placement + type: string + name: v1alpha1 + schema: + openAPIV3Schema: + description: Auto-generated derived type for FreyaDiffusionWorkerSpec via `CustomResource` + properties: + 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. + properties: + authSecretRef: + description: Optional admin/API token Secret for remote LoRA install + generate. + nullable: true + properties: + key: + default: apiKey + type: string + name: + type: string + required: + - name + type: object + engine: + default: vllm-omni + enum: + - vllm-omni + - sglang + type: string + externalEndpoint: + description: 'Required when `placement: external` — e.g. `http://gpu-box.lan:8091`.' + nullable: true + type: string + gpuCount: + default: 1 + format: int32 + type: integer + image: + description: Image reference for Freya components. + nullable: true + properties: + pullPolicy: + nullable: true + type: string + repository: + nullable: true + type: string + tag: + nullable: true + type: string + type: object + model: + default: stabilityai/stable-diffusion-xl-base-1.0 + description: HuggingFace / local model id passed to the engine (in-cluster). + type: string + modelsPvcSize: + default: 100Gi + type: string + nodeSelector: + additionalProperties: + type: string + nullable: true + type: object + placement: + default: incluster + description: |- + Where the diffusion / LoRA engine runs. + + CRD enum values are lowercase (`incluster`, `external`). The `inCluster` alias is accepted by Rust serde for convenience; kubectl/OpenAPI only allow `incluster`. + enum: + - incluster + - external + type: string + port: + default: 8091 + format: int32 + type: integer + storageClassName: + nullable: true + type: string + type: object + status: + nullable: true + properties: + endpoint: + nullable: true + type: string + phase: + nullable: true + type: string + type: object + required: + - spec + title: FreyaDiffusionWorker + type: object + served: true + storage: true + subresources: + status: {} + +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: freyamodelassets.freya.dataknife.ai +spec: + group: freya.dataknife.ai + names: + categories: [] + kind: FreyaModelAsset + plural: freyamodelassets + shortNames: + - fasset + singular: freyamodelasset + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .status.phase + name: Phase + type: string + name: v1alpha1 + schema: + openAPIV3Schema: + description: Auto-generated derived type for FreyaModelAssetSpec via `CustomResource` + properties: + spec: + description: Declarative model/LoRA download into a worker PVC. + properties: + destPath: + description: Relative path under the worker models PVC (e.g. `loras/my.safetensors`). + type: string + secretRef: + description: Reference to a Secret key holding credentials. + nullable: true + properties: + key: + default: apiKey + type: string + name: + type: string + required: + - name + type: object + source: + description: '`huggingface` | `civitai` | `url`' + type: string + url: + type: string + workerRef: + type: string + required: + - destPath + - source + - url + - workerRef + type: object + status: + nullable: true + properties: + message: + nullable: true + type: string + phase: + nullable: true + type: string + type: object + required: + - spec + title: FreyaModelAsset + type: object + served: true + storage: true + subresources: + status: {} + diff --git a/config/default/kustomization.yaml b/config/default/kustomization.yaml new file mode 100644 index 0000000..a5604c7 --- /dev/null +++ b/config/default/kustomization.yaml @@ -0,0 +1,7 @@ +namespace: freya-system +resources: + - ../rbac/service_account.yaml + - ../rbac/role.yaml + - ../rbac/role_binding.yaml + - ../manager/deployment.yaml + - namespace.yaml diff --git a/config/default/namespace.yaml b/config/default/namespace.yaml new file mode 100644 index 0000000..2f53bba --- /dev/null +++ b/config/default/namespace.yaml @@ -0,0 +1,4 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: freya-system diff --git a/config/manager/deployment.yaml b/config/manager/deployment.yaml new file mode 100644 index 0000000..3953c71 --- /dev/null +++ b/config/manager/deployment.yaml @@ -0,0 +1,23 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: freya-operator + namespace: freya-system +spec: + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/name: freya-operator + template: + metadata: + labels: + app.kubernetes.io/name: freya-operator + spec: + serviceAccountName: freya-operator + containers: + - name: manager + image: harbor.dataknife.net/library/freya-operator:0.1.0 + imagePullPolicy: IfNotPresent + env: + - name: RUST_LOG + value: info diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml new file mode 100644 index 0000000..713652a --- /dev/null +++ b/config/rbac/role.yaml @@ -0,0 +1,30 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: freya-operator +rules: + - apiGroups: ["freya.dataknife.ai"] + resources: + - freyastudios + - freyastudios/status + - freyagenerations + - freyagenerations/status + - freyastyles + - freyastyles/status + - freyadiffusionworkers + - freyadiffusionworkers/status + - freyamodelassets + - freyamodelassets/status + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: ["apps"] + resources: ["deployments"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: [""] + resources: ["services", "persistentvolumeclaims", "pods", "configmaps", "secrets"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: ["batch"] + resources: ["jobs"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: ["networking.k8s.io"] + resources: ["ingresses"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] diff --git a/config/rbac/role_binding.yaml b/config/rbac/role_binding.yaml new file mode 100644 index 0000000..d7d3d92 --- /dev/null +++ b/config/rbac/role_binding.yaml @@ -0,0 +1,12 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: freya-operator +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: freya-operator +subjects: + - kind: ServiceAccount + name: freya-operator + namespace: freya-system diff --git a/config/rbac/service_account.yaml b/config/rbac/service_account.yaml new file mode 100644 index 0000000..18a716b --- /dev/null +++ b/config/rbac/service_account.yaml @@ -0,0 +1,6 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: freya-operator + labels: + app.kubernetes.io/name: freya-operator diff --git a/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml b/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml new file mode 100644 index 0000000..12a3874 --- /dev/null +++ b/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml @@ -0,0 +1,14 @@ +# Remote physical GPU box (or any host running vLLM-Omni / freya-worker) +apiVersion: freya.dataknife.ai/v1alpha1 +kind: FreyaDiffusionWorker +metadata: + name: freya-gpu + namespace: freya +spec: + placement: external + externalEndpoint: http://gpu-box.lan:8091 + engine: vllm-omni + # Must match FREYA_WORKER_TOKEN on the remote worker process + authSecretRef: + name: freya-worker-token + key: apiKey diff --git a/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml b/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml new file mode 100644 index 0000000..83d6fd3 --- /dev/null +++ b/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml @@ -0,0 +1,17 @@ +# In-cluster GPU Deployment (requires nvidia.com/gpu) +apiVersion: freya.dataknife.ai/v1alpha1 +kind: FreyaDiffusionWorker +metadata: + name: freya-gpu + namespace: freya +spec: + placement: incluster + engine: vllm-omni + model: stabilityai/stable-diffusion-xl-base-1.0 + gpuCount: 1 + modelsPvcSize: 100Gi + port: 8091 + # Same secret as FreyaStudio → FREYA_WORKER_TOKEN on API + worker + authSecretRef: + name: freya-worker-token + key: apiKey diff --git a/config/samples/freya_v1alpha1_freyamodelasset.yaml b/config/samples/freya_v1alpha1_freyamodelasset.yaml new file mode 100644 index 0000000..8fd474e --- /dev/null +++ b/config/samples/freya_v1alpha1_freyamodelasset.yaml @@ -0,0 +1,14 @@ +# Install a Civitai LoRA onto the worker (uses FreyaStudio civitai secret via Job token, or remote install API) +apiVersion: freya.dataknife.ai/v1alpha1 +kind: FreyaModelAsset +metadata: + name: example-lora + namespace: freya +spec: + source: civitai + url: https://civitai.com/api/download/models/VERSION_ID + destPath: loras/example.safetensors + workerRef: freya-gpu + secretRef: + name: freya-civitai + key: apiKey diff --git a/config/samples/freya_v1alpha1_freyastudio.yaml b/config/samples/freya_v1alpha1_freyastudio.yaml new file mode 100644 index 0000000..4007418 --- /dev/null +++ b/config/samples/freya_v1alpha1_freyastudio.yaml @@ -0,0 +1,37 @@ +apiVersion: freya.dataknife.ai/v1alpha1 +kind: FreyaStudio +metadata: + name: freya + namespace: freya +spec: + replicas: 1 + 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 (UI nginx injects it). + apiTokenSecretRef: + name: freya-api-token + key: token + # Optional — search Civitai + install LoRAs onto the worker for the UI + civitai: + secretRef: + name: freya-civitai + key: apiKey + huggingFace: + secretRef: + name: freya-hf + key: token + diffusionWorkerRef: freya-gpu + storage: + gallerySize: 20Gi + ingress: + enabled: false +--- +# kubectl -n freya create secret generic freya-openrouter --from-literal=apiKey=sk-or-... +# kubectl -n freya create secret generic freya-civitai --from-literal=apiKey=YOUR_CIVITAI_KEY +# kubectl -n freya create secret generic freya-hf --from-literal=token=hf_... +# 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)" diff --git a/crates/freya-api/Cargo.toml b/crates/freya-api/Cargo.toml new file mode 100644 index 0000000..01c5222 --- /dev/null +++ b/crates/freya-api/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "freya-api" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Freya automation API — OpenRouter + local diffusion worker router" + +[[bin]] +name = "freya-api" +path = "src/main.rs" + +[dependencies] +anyhow = { workspace = true } +axum = { workspace = true } +base64 = { workspace = true } +chrono = { workspace = true } +clap = { workspace = true } +reqwest = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +serde_yaml = { workspace = true } +tokio = { workspace = true } +tower-http = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +uuid = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/freya-api/src/civitai.rs b/crates/freya-api/src/civitai.rs new file mode 100644 index 0000000..6bfa41c --- /dev/null +++ b/crates/freya-api/src/civitai.rs @@ -0,0 +1,134 @@ +//! Civitai search / download URL helpers (requires user-provided API key). + +use anyhow::{anyhow, Context, Result}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone)] +pub struct CivitaiClient { + http: reqwest::Client, + api_key: String, +} + +impl CivitaiClient { + pub fn new(api_key: impl Into) -> Self { + Self { + http: reqwest::Client::new(), + api_key: api_key.into(), + } + } + + pub fn configured(&self) -> bool { + !self.api_key.trim().is_empty() + } + + pub async fn search(&self, query: &str, limit: u32) -> 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?limit={limit}&query={}", + urlencoding_lite(query) + ); + let resp = self + .http + .get(&url) + .header("Authorization", format!("Bearer {}", self.api_key)) + .send() + .await + .context("civitai search")?; + let status = resp.status(); + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + return Err(anyhow!("civitai {status}: {text}")); + } + 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()); + } + } + } + } + out.push(CivitaiModelCard { + id, + name, + model_type, + version_id, + download_url, + thumbnail_url: thumbnail, + example_prompt, + }); + } + } + Ok(out) + } +} + +fn urlencoding_lite(s: &str) -> String { + // Percent-encode UTF-8 bytes (not truncated chars) for non-ASCII queries. + let mut out = String::with_capacity(s.len() * 3); + for &b in s.as_bytes() { + match b { + b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(b as char); + } + b' ' => out.push_str("%20"), + _ => out.push_str(&format!("%{b:02X}")), + } + } + out +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CivitaiModelCard { + 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 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, +} diff --git a/crates/freya-api/src/config.rs b/crates/freya-api/src/config.rs new file mode 100644 index 0000000..ff2337f --- /dev/null +++ b/crates/freya-api/src/config.rs @@ -0,0 +1,92 @@ +use clap::Parser; +use std::path::PathBuf; + +#[derive(Debug, Clone, Parser)] +#[command(name = "freya-api", about = "Freya automation API")] +pub struct Config { + #[arg(long, env = "FREYA_BIND", default_value = "0.0.0.0:8080")] + pub bind: String, + + #[arg(long, env = "OPENROUTER_API_KEY", default_value = "")] + pub openrouter_api_key: String, + + #[arg( + long, + env = "OPENROUTER_BASE_URL", + default_value = "https://openrouter.ai/api/v1" + )] + pub openrouter_base_url: String, + + #[arg(long, env = "FREYA_CHAT_MODEL", default_value = "openrouter/auto")] + pub chat_model: String, + + #[arg( + long, + env = "FREYA_IMAGE_MODEL", + default_value = "black-forest-labs/flux.2-klein-4b" + )] + pub image_model: String, + + #[arg(long, env = "FREYA_CHAT_BACKEND", default_value = "openrouter")] + pub chat_backend: String, + + #[arg(long, env = "FREYA_CHAT_BASE_URL")] + pub chat_base_url: Option, + + #[arg(long, env = "FREYA_GALLERY_DIR", default_value = "./data/gallery")] + pub gallery_dir: PathBuf, + + #[arg(long, env = "FREYA_PACKS_DIR", default_value = "./packs")] + pub packs_dir: PathBuf, + + #[arg(long, env = "FREYA_DIFFUSION_WORKER_URL")] + pub diffusion_worker_url: Option, + + /// Civitai API key — used for search/install of LoRAs onto workers. Never logged. + #[arg(long, env = "CIVITAI_API_KEY", default_value = "")] + pub civitai_api_key: String, + + #[arg(long, env = "HF_TOKEN", default_value = "")] + pub hf_token: String, + + /// Optional path to persist runtime secrets written from the UI (local/dev). + #[arg( + long, + env = "FREYA_SECRETS_FILE", + default_value = "./data/secrets.json" + )] + pub secrets_file: PathBuf, + + /// Optional bearer token for `/v1/*` routes. Empty = open (local/dev only). + #[arg(long, env = "FREYA_API_TOKEN", default_value = "")] + pub api_token: String, + + /// Bearer token the API sends to the diffusion worker (`FREYA_WORKER_TOKEN`). + #[arg(long, env = "FREYA_WORKER_TOKEN", default_value = "")] + pub worker_token: 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, +} + +impl Config { + pub fn openrouter_configured(&self) -> bool { + !self.openrouter_api_key.trim().is_empty() + } + + pub fn civitai_configured(&self) -> bool { + !self.civitai_api_key.trim().is_empty() + } + + pub fn chat_url(&self) -> String { + if self.chat_backend == "vllm" { + self.chat_base_url + .clone() + .unwrap_or_else(|| self.openrouter_base_url.clone()) + } else { + self.openrouter_base_url.clone() + } + } +} diff --git a/crates/freya-api/src/gallery.rs b/crates/freya-api/src/gallery.rs new file mode 100644 index 0000000..5d7fed0 --- /dev/null +++ b/crates/freya-api/src/gallery.rs @@ -0,0 +1,104 @@ +use anyhow::{Context, Result}; +use chrono::Utc; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; +use tokio::fs; +use uuid::Uuid; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ArtifactMeta { + pub id: String, + pub prompt: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enhanced_prompt: Option, + pub backend: String, + pub model: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub style_ref: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub loras: Vec, + pub created_at: String, + pub mime: String, + pub filename: String, +} + +#[derive(Clone)] +pub struct Gallery { + root: PathBuf, +} + +impl Gallery { + pub async fn open(root: PathBuf) -> Result { + fs::create_dir_all(&root).await?; + Ok(Self { root }) + } + + pub async fn save( + &self, + bytes: &[u8], + mime: &str, + meta: &mut ArtifactMeta, + ) -> Result { + let id = Uuid::new_v4().to_string(); + let ext = if mime.contains("jpeg") || mime.contains("jpg") { + "jpg" + } else { + "png" + }; + let filename = format!("{id}.{ext}"); + meta.id = id.clone(); + meta.filename = filename.clone(); + meta.created_at = Utc::now().to_rfc3339(); + meta.mime = mime.to_string(); + + let img_path = self.root.join(&filename); + let meta_path = self.root.join(format!("{id}.json")); + fs::write(&img_path, bytes).await.context("write image")?; + let json = serde_json::to_vec_pretty(meta)?; + fs::write(&meta_path, json).await.context("write meta")?; + Ok(meta.clone()) + } + + pub async fn list(&self) -> Result> { + let mut out = Vec::new(); + let mut rd = fs::read_dir(&self.root).await?; + while let Some(ent) = rd.next_entry().await? { + let path = ent.path(); + if path.extension().and_then(|e| e.to_str()) != Some("json") { + continue; + } + let raw = fs::read(&path).await?; + if let Ok(m) = serde_json::from_slice::(&raw) { + out.push(m); + } + } + out.sort_by(|a, b| b.created_at.cmp(&a.created_at)); + Ok(out) + } + + pub async fn get(&self, id: &str) -> Result> { + let Some(id) = sanitize_gallery_id(id) else { + return Ok(None); + }; + let path = self.root.join(format!("{id}.json")); + if !path.exists() { + return Ok(None); + } + let raw = fs::read(path).await?; + Ok(Some(serde_json::from_slice(&raw)?)) + } + + pub fn image_path(&self, meta: &ArtifactMeta) -> PathBuf { + self.root.join(&meta.filename) + } +} + +/// Gallery ids are UUIDs written by [`Gallery::save`]. Reject path traversal. +fn sanitize_gallery_id(id: &str) -> Option<&str> { + if Uuid::parse_str(id).is_ok() { + Some(id) + } else { + None + } +} diff --git a/crates/freya-api/src/main.rs b/crates/freya-api/src/main.rs new file mode 100644 index 0000000..45008a6 --- /dev/null +++ b/crates/freya-api/src/main.rs @@ -0,0 +1,165 @@ +mod civitai; +mod config; +mod gallery; +mod openrouter; +mod routes; +mod state; +mod styles; +mod worker; + +use axum::extract::Request; +use axum::http::{header, HeaderValue, Method, StatusCode}; +use axum::middleware::{self, Next}; +use axum::response::Response; +use axum::routing::{get, post}; +use axum::Router; +use clap::Parser; +use config::Config; +use state::AppState; +use tower_http::cors::{AllowOrigin, CorsLayer}; +use tower_http::trace::TraceLayer; +use tracing::{info, warn}; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .init(); + + let cfg = Config::parse(); + let bind = cfg.bind.clone(); + let cors = build_cors(&cfg); + let require_auth = !cfg.api_token.trim().is_empty(); + 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." + ); + } else { + info!("FREYA_API_TOKEN set — bearer auth required on /v1 routes (except gallery images)"); + } + + let state = AppState::from_config(cfg).await?; + + let protected = Router::new() + .route("/v1/assist", post(routes::assist)) + .route("/v1/generate", post(routes::generate)) + .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}/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/install", post(routes::civitai_install)) + .route( + "/v1/settings", + get(routes::settings_get).put(routes::settings_put), + ) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_api_token, + )); + + let app = Router::new() + .route("/healthz", get(routes::health)) + .route("/v1/health", get(routes::health)) + .merge(protected) + .layer(cors) + .layer(TraceLayer::new_for_http()) + .with_state(state); + + let listener = tokio::net::TcpListener::bind(&bind).await?; + info!(%bind, "freya-api listening"); + axum::serve(listener, app).await?; + Ok(()) +} + +fn build_cors(cfg: &Config) -> CorsLayer { + let origins = cfg.cors_origins.trim(); + let has_token = !cfg.api_token.trim().is_empty(); + if !origins.is_empty() { + let list: Vec = origins + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .filter_map(|o| o.parse().ok()) + .collect(); + CorsLayer::new() + .allow_origin(AllowOrigin::list(list)) + .allow_methods([Method::GET, Method::POST, Method::PUT, Method::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_headers([header::AUTHORIZATION, header::CONTENT_TYPE]) + } else { + CorsLayer::permissive() + } +} + +/// When `FREYA_API_TOKEN` is set, require `Authorization: Bearer ` on all `/v1` methods +/// except OPTIONS (CORS) and gallery image GETs (`` cannot send Authorization). +async fn require_api_token( + axum::extract::State(state): axum::extract::State, + req: Request, + next: Next, +) -> Result { + let method = req.method().clone(); + if method == Method::OPTIONS { + return Ok(next.run(req).await); + } + // UUID gallery ids are unguessable; list/detail/search still require the bearer. + if matches!(method, Method::GET | Method::HEAD) && is_gallery_image_path(req.uri().path()) { + return Ok(next.run(req).await); + } + + let expected = { + let cfg = state.config.read().await; + cfg.api_token.trim().to_string() + }; + if expected.is_empty() { + return Ok(next.run(req).await); + } + + let auth = req + .headers() + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + let ok = auth + .strip_prefix("Bearer ") + .map(|t| t == expected) + .unwrap_or(false); + if !ok { + return Err(StatusCode::UNAUTHORIZED); + } + Ok(next.run(req).await) +} + +fn is_gallery_image_path(path: &str) -> bool { + let parts: Vec<&str> = path.trim_end_matches('/').split('/').collect(); + matches!( + parts.as_slice(), + ["", "v1", "gallery", id, "image"] if !id.is_empty() + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gallery_image_path_match() { + assert!(is_gallery_image_path("/v1/gallery/abc-123/image")); + assert!(is_gallery_image_path("/v1/gallery/abc-123/image/")); + assert!(!is_gallery_image_path("/v1/gallery")); + assert!(!is_gallery_image_path("/v1/gallery/abc-123")); + assert!(!is_gallery_image_path("/v1/civitai/search")); + } +} diff --git a/crates/freya-api/src/openrouter.rs b/crates/freya-api/src/openrouter.rs new file mode 100644 index 0000000..41c7175 --- /dev/null +++ b/crates/freya-api/src/openrouter.rs @@ -0,0 +1,238 @@ +use crate::config::Config; +use anyhow::{anyhow, Context, Result}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone)] +pub struct OpenRouterClient { + http: reqwest::Client, + base: String, + api_key: String, + chat_model: String, + image_model: String, +} + +impl OpenRouterClient { + pub fn new(cfg: &Config) -> Self { + Self { + http: reqwest::Client::new(), + base: cfg.chat_url().trim_end_matches('/').to_string(), + api_key: cfg.openrouter_api_key.clone(), + chat_model: cfg.chat_model.clone(), + image_model: cfg.image_model.clone(), + } + } + + pub fn with_key(mut self, key: String) -> Self { + self.api_key = key; + self + } + + pub fn default_image_model(&self) -> &str { + &self.image_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")); + } + 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 !status.is_success() { + return Err(anyhow!("openrouter {status}: {text}")); + } + serde_json::from_str(&text).context("parse openrouter json") + } + + 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!({ + "model": model, + "messages": [ + {"role": "system", "content": system}, + {"role": "user", "content": user} + ] + }); + let v = self.auth_post("/chat/completions", body).await?; + v.pointer("/choices/0/message/content") + .and_then(|c| c.as_str()) + .map(|s| s.to_string()) + .ok_or_else(|| anyhow!("missing chat content")) + } + + pub async fn list_image_models(&self) -> Result> { + if self.api_key.is_empty() { + return Ok(fallback_models()); + } + let url = format!("{}/images/models", self.base); + let resp = self + .http + .get(&url) + .bearer_auth(&self.api_key) + .send() + .await + .context("list image models")?; + if !resp.status().is_success() { + return Ok(fallback_models()); + } + let v: Value = resp.json().await.unwrap_or(Value::Null); + let mut out = Vec::new(); + if let Some(arr) = v.get("data").and_then(|d| d.as_array()) { + for m in arr { + let id = m + .get("id") + .and_then(|x| x.as_str()) + .unwrap_or("") + .to_string(); + if id.is_empty() { + 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(), + }); + } + } + if out.is_empty() { + return Ok(fallback_models()); + } + Ok(out) + } + + pub async fn generate_image( + &self, + prompt: &str, + model: Option<&str>, + size: Option<&str>, + ) -> Result { + let model = model.unwrap_or(&self.image_model); + let mut body = serde_json::json!({ + "model": model, + "prompt": prompt, + "n": 1, + }); + if let Some(size) = size { + if let Some(ratio) = size_to_aspect(size) { + body["aspect_ratio"] = Value::String(ratio.into()); + } else { + body["size"] = Value::String(size.into()); + } + } + + // 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) + } + } + } +} + +fn size_to_aspect(size: &str) -> Option<&'static str> { + match size { + "1024x1024" | "1:1" => Some("1:1"), + "1024x576" | "16:9" => Some("16:9"), + "576x1024" | "9:16" => Some("9:16"), + _ => None, + } +} + +fn extract_image(v: &Value) -> Result { + if let Some(b64) = v.pointer("/data/0/b64_json").and_then(|x| x.as_str()) { + return Ok(GeneratedImage { + b64: b64.to_string(), + mime: "image/png".into(), + }); + } + 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,") { + return Ok(GeneratedImage { + b64: rest.to_string(), + mime: "image/png".into(), + }); + } + return Err(anyhow!("image url responses not downloaded yet: {url}")); + } + Err(anyhow!("no image in openrouter response")) +} + +fn extract_image_from_chat(v: &Value) -> Result { + if let Some(images) = v + .pointer("/choices/0/message/images") + .and_then(|x| x.as_array()) + { + if let Some(url) = images + .first() + .and_then(|i| i.pointer("/image_url/url")) + .and_then(|u| u.as_str()) + { + 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: mime.into(), + }); + } + } + } + Err(anyhow!("no image in chat completion")) +} + +fn fallback_models() -> Vec { + vec![ + ImageModel { + id: "black-forest-labs/flux.2-klein-4b".into(), + name: "FLUX.2 Klein 4B".into(), + backend: "openrouter".into(), + }, + ImageModel { + id: "openai/gpt-image-2".into(), + name: "GPT Image 2".into(), + backend: "openrouter".into(), + }, + ] +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ImageModel { + pub id: String, + pub name: String, + pub backend: String, +} + +#[derive(Debug, Clone)] +pub struct GeneratedImage { + pub b64: String, + pub mime: String, +} diff --git a/crates/freya-api/src/routes.rs b/crates/freya-api/src/routes.rs new file mode 100644 index 0000000..85047e4 --- /dev/null +++ b/crates/freya-api/src/routes.rs @@ -0,0 +1,642 @@ +use crate::gallery::ArtifactMeta; +use crate::state::{AppState, RuntimeSecrets}; +use crate::styles::{self, StylePack}; +use crate::worker::LoraWeight; +use axum::extract::{Path, Query, State}; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use axum::Json; +use base64::Engine; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +type ApiResult = Result; + +pub async fn health(State(state): State) -> impl IntoResponse { + let cfg = state.config.read().await; + let worker_ok = { + let w = state.worker.read().await; + match w.as_ref() { + Some(c) => c.health().await, + None => false, + } + }; + Json(json!({ + "ok": true, + "openRouter": cfg.openrouter_configured(), + "civitai": cfg.civitai_configured(), + "diffusionWorker": worker_ok, + })) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AssistRequest { + pub mode: String, + pub message: String, + #[serde(default)] + pub model: Option, + /// Optional prior turns for agentic session context. + #[serde(default)] + pub session: Option, +} + +fn strip_json_fence(raw: &str) -> &str { + raw.trim() + .trim_start_matches("```json") + .trim_start_matches("```") + .trim_end_matches("```") + .trim() +} + +pub async fn assist( + State(state): State, + Json(req): Json, +) -> ApiResult> { + let system = 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() + ) + } 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, 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()); + } + } + } + } + } + } + + Ok(Json(out)) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GenerateRequest { + pub prompt: String, + #[serde(default)] + pub negative_prompt: Option, + #[serde(default)] + pub enhance: Option, + #[serde(default)] + pub backend: Option, + #[serde(default)] + pub model: Option, + #[serde(default)] + pub style_ref: Option, + #[serde(default)] + pub loras: Vec, + #[serde(default)] + pub size: Option, + #[serde(default)] + pub seed: Option, +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct LoraIn { + pub name: String, + #[serde(default = "one")] + pub scale: f32, +} + +fn one() -> f32 { + 1.0 +} + +pub async fn generate( + State(state): State, + Json(req): Json, +) -> ApiResult> { + run_generate(&state, req).await.map(Json) +} + +pub async fn run( + State(state): State, + Json(mut req): Json, +) -> ApiResult> { + // Auto-plan when backend/model unset. + if req.backend.as_deref().unwrap_or("auto") == "auto" && req.model.is_none() { + let system = styles::load_instruction(&state.packs_dir, "plan").await; + let or = state.openrouter.read().await; + if let Ok(plan_txt) = or.chat(&system, &req.prompt, None).await { + if let Ok(plan) = serde_json::from_str::( + plan_txt + .trim() + .trim_start_matches("```json") + .trim_start_matches("```") + .trim_end_matches("```") + .trim(), + ) { + if let Some(b) = plan.get("backend").and_then(|x| x.as_str()) { + req.backend = Some(b.into()); + } + if let Some(m) = plan.get("model").and_then(|x| x.as_str()) { + req.model = Some(m.into()); + } + if let Some(s) = plan.get("styleId").and_then(|x| x.as_str()) { + req.style_ref = Some(s.into()); + } + if req.enhance.is_none() { + if let Some(e) = plan.get("enhanceMode").and_then(|x| x.as_str()) { + req.enhance = Some(e.into()); + } + } + } + } + } + run_generate(&state, req).await.map(Json) +} + +async fn run_generate(state: &AppState, mut req: GenerateRequest) -> ApiResult { + let styles = styles::load_styles(&state.packs_dir) + .await + .unwrap_or_default(); + let style: Option = req + .style_ref + .as_ref() + .and_then(|id| styles.into_iter().find(|s| s.id == *id)); + + if let Some(ref s) = style { + if req.model.is_none() { + req.model = s.open_router_model.clone().or(s.local_checkpoint.clone()); + } + if req.backend.is_none() || req.backend.as_deref() == Some("auto") { + req.backend = Some(s.backend.clone()); + } + if req.size.is_none() { + req.size = s.recommended_size.clone(); + } + if req.loras.is_empty() { + req.loras = s + .loras + .iter() + .map(|l| LoraIn { + name: l.name.clone(), + scale: l.scale, + }) + .collect(); + } + if let Some(tw) = &s.trigger_words { + if !req.prompt.contains(tw) { + req.prompt = format!("{tw}, {}", req.prompt); + } + } + } + + // LoRAs only apply on the local worker — prefer local when weights are pinned and a worker exists. + if !req.loras.is_empty() + && (req.backend.is_none() || req.backend.as_deref() == Some("auto")) + && state.worker.read().await.is_some() + { + req.backend = Some("local".into()); + } + + let backend = req.backend.clone().unwrap_or_else(|| "openrouter".into()); + let enhance = req.enhance.clone().unwrap_or_else(|| "auto".into()); + let mut final_prompt = req.prompt.clone(); + let mut enhanced = None; + + let wants_enhance = + enhance == "on" || enhance == "auto" || enhance == "prompt-prose" || enhance == "prompt-sd"; + if wants_enhance && enhance != "off" { + let mode = if enhance == "prompt-sd" || backend == "local" { + "prompt-sd" + } else { + "prompt-prose" + }; + let system = styles::load_instruction(&state.packs_dir, mode).await; + let or = state.openrouter.read().await; + if let Ok(text) = or.chat(&system, &req.prompt, None).await { + enhanced = Some(text.clone()); + final_prompt = text; + } + } + + let (bytes, mime, model_used, backend_used) = if backend == "local" { + let worker = state.worker.read().await; + let client = worker.as_ref().ok_or(ApiError::NoWorker)?; + let loras: Vec = req + .loras + .iter() + .map(|l| LoraWeight { + lora_name: l.name.clone(), + lora_scale: l.scale, + }) + .collect(); + let bytes = client + .generate( + &final_prompt, + req.model.as_deref(), + &loras, + req.size.as_deref(), + req.seed, + req.negative_prompt.as_deref(), + ) + .await + .map_err(ApiError::from)?; + ( + bytes, + "image/png".to_string(), + req.model.clone().unwrap_or_else(|| "local".into()), + "local".to_string(), + ) + } else { + let or = state.openrouter.read().await; + let img = or + .generate_image(&final_prompt, req.model.as_deref(), req.size.as_deref()) + .await + .map_err(ApiError::from)?; + let bytes = base64::engine::general_purpose::STANDARD + .decode(&img.b64) + .map_err(|e| ApiError::Msg(e.to_string()))?; + ( + bytes, + img.mime, + req.model + .clone() + .unwrap_or_else(|| or.default_image_model().to_string()), + "openrouter".to_string(), + ) + }; + + let mut meta = ArtifactMeta { + id: String::new(), + prompt: req.prompt.clone(), + enhanced_prompt: enhanced.clone(), + backend: backend_used.clone(), + model: model_used.clone(), + style_ref: req.style_ref.clone(), + loras: req.loras.iter().map(|l| l.name.clone()).collect(), + created_at: String::new(), + mime: mime.clone(), + filename: String::new(), + }; + let saved = state + .gallery + .save(&bytes, &mime, &mut meta) + .await + .map_err(ApiError::from)?; + + Ok(json!({ + "artifactId": saved.id, + "backend": backend_used, + "model": model_used, + "enhancedPrompt": enhanced, + "url": format!("/v1/gallery/{}/image", saved.id), + "meta": saved, + })) +} + +pub async fn gallery_list(State(state): State) -> ApiResult> { + let items = state.gallery.list().await.map_err(ApiError::from)?; + Ok(Json(json!({ "items": items }))) +} + +pub async fn gallery_get( + State(state): State, + Path(id): Path, +) -> ApiResult> { + let meta = state + .gallery + .get(&id) + .await + .map_err(ApiError::from)? + .ok_or(ApiError::NotFound)?; + Ok(Json(meta)) +} + +pub async fn gallery_image( + State(state): State, + Path(id): Path, +) -> ApiResult { + let meta = state + .gallery + .get(&id) + .await + .map_err(ApiError::from)? + .ok_or(ApiError::NotFound)?; + 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" + }; + Ok(([(axum::http::header::CONTENT_TYPE, ct)], bytes).into_response()) +} + +pub async fn gallery_remix( + State(state): State, + Path(id): Path, +) -> ApiResult> { + let meta = state + .gallery + .get(&id) + .await + .map_err(ApiError::from)? + .ok_or(ApiError::NotFound)?; + Ok(Json(json!({ + // Prefer the user's natural-language prompt for remix; model brief is secondary + "prompt": meta.prompt.clone(), + "enhancedPrompt": meta.enhanced_prompt, + "backend": meta.backend, + "model": meta.model, + "styleRef": meta.style_ref, + "loras": meta.loras, + }))) +} + +pub async fn models(State(state): State) -> ApiResult> { + let or = state.openrouter.read().await; + let mut cloud = or.list_image_models().await.unwrap_or_default(); + let mut local = Vec::new(); + if let Some(w) = state.worker.read().await.as_ref() { + if let Ok(loras) = w.list_loras().await { + for a in loras { + local.push(json!({ + "id": a.id, + "name": a.id, + "backend": "local", + "kind": a.kind, + "path": a.path, + })); + } + } + } + Ok(Json(json!({ + "openrouter": cloud.drain(..).map(|m| json!({ + "id": m.id, "name": m.name, "backend": m.backend + })).collect::>(), + "local": local, + }))) +} + +pub async fn styles_list(State(state): State) -> ApiResult> { + let items = styles::load_styles(&state.packs_dir) + .await + .map_err(ApiError::from)?; + Ok(Json(json!({ "items": items }))) +} + +#[derive(Debug, Deserialize)] +pub struct CivitaiSearchQuery { + pub q: String, + #[serde(default = "default_limit")] + pub limit: u32, +} + +fn default_limit() -> u32 { + 20 +} + +pub async fn civitai_search( + State(state): State, + Query(q): Query, +) -> ApiResult> { + let civ = state.civitai.read().await; + let items = civ.search(&q.q, q.limit).await.map_err(ApiError::from)?; + Ok(Json(json!({ "items": items }))) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InstallCivitaiRequest { + pub download_url: String, + pub dest_path: String, + #[serde(default)] + pub name: Option, +} + +/// Allowlist Civitai hosts before attaching the API token (never send token to untrusted URLs). +fn civitai_download_url_ok(url: &str) -> bool { + let Ok(parsed) = reqwest::Url::parse(url) else { + return false; + }; + if !matches!(parsed.scheme(), "https" | "http") { + return false; + } + match parsed.host_str() { + Some(h) => { + h.eq_ignore_ascii_case("civitai.com") + || h.to_ascii_lowercase().ends_with(".civitai.com") + } + None => false, + } +} + +/// Install a Civitai download onto the configured diffusion worker (remote or in-cluster URL). +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)?; + // Prefer authenticated Civitai URL; worker performs the fetch with Freya-provided source tag. + let url = if req.download_url.contains('?') { + format!("{}&token={}", req.download_url, cfg.civitai_api_key) + } else { + format!("{}?token={}", req.download_url, cfg.civitai_api_key) + }; + drop(cfg); + client + .install_asset("civitai", &url, &req.dest_path) + .await + .map_err(ApiError::from)?; + Ok(Json(json!({ + "ok": true, + "destPath": req.dest_path, + "name": req.name, + }))) +} + +#[derive(Debug, 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, + pub chat_model: String, + pub image_model: String, +} + +pub async fn settings_get(State(state): State) -> Json { + let cfg = state.config.read().await; + Json(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(), + }) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SettingsUpdate { + #[serde(default)] + pub openrouter_api_key: Option, + /// User-provided Civitai API key for search + LoRA installs. + #[serde(default)] + pub civitai_api_key: Option, + #[serde(default)] + pub hf_token: Option, + #[serde(default)] + pub diffusion_worker_url: Option, + #[serde(default)] + pub chat_model: Option, + #[serde(default)] + pub image_model: 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(); + { + 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()), + ); + } + } + if let Some(m) = upd.chat_model { + cfg.chat_model = m; + } + if let Some(m) = upd.image_model { + cfg.image_model = m; + } + } + + let secrets = RuntimeSecrets { + openrouter_api_key: upd.openrouter_api_key, + civitai_api_key: upd.civitai_api_key, + hf_token: upd.hf_token, + }; + state.apply_secrets(secrets).await; + let _ = state.persist_secrets().await; + + // OpenRouterClient captures chat/image model at construction — rebuild after changes. + if models_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) +} + +#[derive(Debug)] +pub enum ApiError { + Msg(String), + NotFound, + NoWorker, +} + +impl From for ApiError { + fn from(e: anyhow::Error) -> Self { + ApiError::Msg(e.to_string()) + } +} + +impl From for ApiError { + fn from(e: std::io::Error) -> Self { + ApiError::Msg(e.to_string()) + } +} + +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + let (code, msg) = match self { + ApiError::NotFound => (StatusCode::NOT_FOUND, "not found".into()), + ApiError::NoWorker => ( + StatusCode::BAD_REQUEST, + "No diffusion worker configured — set worker URL or deploy FreyaDiffusionWorker" + .into(), + ), + ApiError::Msg(m) => (StatusCode::BAD_REQUEST, m), + }; + (code, Json(json!({ "error": msg }))).into_response() + } +} diff --git a/crates/freya-api/src/state.rs b/crates/freya-api/src/state.rs new file mode 100644 index 0000000..54d5ed6 --- /dev/null +++ b/crates/freya-api/src/state.rs @@ -0,0 +1,105 @@ +use crate::civitai::CivitaiClient; +use crate::config::Config; +use crate::gallery::Gallery; +use crate::openrouter::OpenRouterClient; +use crate::worker::DiffusionWorkerClient; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; +use std::sync::Arc; +use tokio::sync::RwLock; + +#[derive(Clone)] +pub struct AppState { + pub config: Arc>, + pub gallery: Gallery, + pub packs_dir: PathBuf, + pub openrouter: Arc>, + pub civitai: Arc>, + pub worker: Arc>>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct RuntimeSecrets { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub openrouter_api_key: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub civitai_api_key: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hf_token: Option, +} + +impl AppState { + pub async fn from_config(cfg: Config) -> anyhow::Result { + 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())); + let packs_dir = cfg.packs_dir.clone(); + let state = Self { + config: Arc::new(RwLock::new(cfg)), + gallery, + packs_dir, + openrouter: Arc::new(RwLock::new(openrouter)), + civitai: Arc::new(RwLock::new(civitai)), + worker: Arc::new(RwLock::new(worker)), + }; + state.load_secrets_file().await?; + Ok(state) + } + + async fn load_secrets_file(&self) -> anyhow::Result<()> { + let path = { + let cfg = self.config.read().await; + cfg.secrets_file.clone() + }; + if !path.exists() { + return Ok(()); + } + let raw = tokio::fs::read(&path).await?; + let secrets: RuntimeSecrets = serde_json::from_slice(&raw).unwrap_or_default(); + self.apply_secrets(secrets).await; + Ok(()) + } + + pub async fn apply_secrets(&self, secrets: RuntimeSecrets) { + 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 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(k) = secrets.hf_token { + if !k.is_empty() { + cfg.hf_token = k; + } + } + } + + pub async fn persist_secrets(&self) -> anyhow::Result<()> { + let cfg = self.config.read().await; + if let Some(parent) = cfg.secrets_file.parent() { + 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()), + }; + let raw = serde_json::to_vec_pretty(&secrets)?; + tokio::fs::write(&cfg.secrets_file, raw).await?; + Ok(()) + } +} diff --git a/crates/freya-api/src/styles.rs b/crates/freya-api/src/styles.rs new file mode 100644 index 0000000..fa72421 --- /dev/null +++ b/crates/freya-api/src/styles.rs @@ -0,0 +1,137 @@ +use anyhow::Result; +use serde::{Deserialize, Serialize}; +use std::path::Path; +use tokio::fs; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StylePack { + pub id: String, + pub display_name: String, + #[serde(default)] + pub tags: Vec, + pub example_prompt: String, + #[serde(default = "default_backend")] + pub backend: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub open_router_model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub local_checkpoint: Option, + #[serde(default)] + pub loras: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub trigger_words: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub recommended_size: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thumbnail_url: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StyleLora { + pub name: String, + #[serde(default = "one")] + pub scale: f32, +} + +fn one() -> f32 { + 1.0 +} + +fn default_backend() -> String { + "openrouter".into() +} + +pub async fn load_styles(packs_dir: &Path) -> Result> { + let dir = packs_dir.join("styles"); + if !dir.exists() { + return Ok(builtin_styles()); + } + let mut out = Vec::new(); + let mut rd = fs::read_dir(&dir).await?; + while let Some(ent) = rd.next_entry().await? { + let path = ent.path(); + let ext = path.extension().and_then(|e| e.to_str()); + if ext != Some("yaml") && ext != Some("yml") { + continue; + } + let raw = fs::read_to_string(&path).await?; + if let Ok(s) = serde_yaml::from_str::(&raw) { + out.push(s); + } + } + if out.is_empty() { + return Ok(builtin_styles()); + } + Ok(out) +} + +pub async fn load_instruction(packs_dir: &Path, mode: &str) -> String { + let path = packs_dir.join("instructions").join(format!("{mode}.txt")); + if let Ok(s) = fs::read_to_string(path).await { + return s; + } + builtin_instruction(mode).to_string() +} + +fn builtin_styles() -> Vec { + vec![ + 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(), + 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: "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(), + 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("768x1024".into()), + thumbnail_url: None, + }, + ] +} + +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." + } + "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." + } + "caption" => { + "You are Freya. Describe the image in third person: subjects, setting, composition, style, lighting. Plain prose, 150–300 words. Output only the caption." + } + "prompt" | "prompt-sd" => { + "You are Freya. Output ONLY an optimized positive prompt for Stable Diffusion. One continuous comma-separated keyword list. Keep trigger words and underscores intact. No negative prompt. No preamble." + } + "prompt-prose" => { + "You are Freya. Expand the user's natural-language description into a rich image brief for modern models: one continuous paragraph of vivid prose. Do NOT output comma-separated Stable Diffusion keyword lists. Output ONLY the prose brief." + } + "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." + } + "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." + } + "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, a helpful image studio agent.", + } +} diff --git a/crates/freya-api/src/worker.rs b/crates/freya-api/src/worker.rs new file mode 100644 index 0000000..1201435 --- /dev/null +++ b/crates/freya-api/src/worker.rs @@ -0,0 +1,175 @@ +//! Local / remote diffusion worker client (vLLM-Omni compatible + Freya LoRA install). + +use anyhow::{anyhow, Context, Result}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone)] +pub struct DiffusionWorkerClient { + http: reqwest::Client, + base: String, + token: Option, +} + +impl DiffusionWorkerClient { + pub fn new(base: impl Into) -> Self { + Self { + http: reqwest::Client::new(), + base: base.into().trim_end_matches('/').to_string(), + token: None, + } + } + + pub fn with_token(mut self, token: impl Into) -> Self { + let t = token.into(); + self.token = if t.trim().is_empty() { None } else { Some(t) }; + self + } + + fn apply_auth(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder { + match &self.token { + Some(t) => req.bearer_auth(t), + None => req, + } + } + + pub async fn health(&self) -> bool { + self.http + .get(format!("{}/health", self.base)) + .send() + .await + .map(|r| r.status().is_success()) + .unwrap_or(false) + } + + pub async fn list_loras(&self) -> Result> { + let resp = self + .apply_auth(self.http.get(format!("{}/v1/loras", self.base))) + .send() + .await + .context("list loras")?; + if !resp.status().is_success() { + return Ok(Vec::new()); + } + let v: Value = resp.json().await.unwrap_or(Value::Null); + let mut out = Vec::new(); + if let Some(arr) = v.get("data").and_then(|d| d.as_array()) { + for a in arr { + out.push(LocalAsset { + id: a + .get("id") + .or_else(|| a.get("name")) + .and_then(|x| x.as_str()) + .unwrap_or("") + .to_string(), + kind: a + .get("kind") + .and_then(|x| x.as_str()) + .unwrap_or("lora") + .to_string(), + path: a + .get("path") + .and_then(|x| x.as_str()) + .unwrap_or("") + .to_string(), + }); + } + } + Ok(out) + } + + pub async fn generate( + &self, + prompt: &str, + model: Option<&str>, + loras: &[LoraWeight], + size: Option<&str>, + seed: Option, + negative: Option<&str>, + ) -> Result> { + let mut body = serde_json::json!({ + "prompt": prompt, + "n": 1, + "response_format": "b64_json", + }); + 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()); + } + if !loras.is_empty() { + body["lora_request"] = serde_json::to_value(loras)?; + } + + let resp = self + .apply_auth( + self.http + .post(format!("{}/v1/images/generations", self.base)) + .json(&body), + ) + .send() + .await + .context("worker generate")?; + let status = resp.status(); + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + return Err(anyhow!("worker {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 missing b64_json"))?; + use base64::Engine; + base64::engine::general_purpose::STANDARD + .decode(b64) + .context("decode worker image") + } + + pub async fn install_asset(&self, source: &str, url: &str, dest_path: &str) -> Result<()> { + let body = serde_json::json!({ + "source": source, + "url": url, + "destPath": dest_path, + }); + let resp = self + .apply_auth( + self.http + .post(format!("{}/v1/assets/install", self.base)) + .json(&body), + ) + .send() + .await + .context("worker install")?; + if !resp.status().is_success() { + let t = resp.text().await.unwrap_or_default(); + return Err(anyhow!("install failed: {t}")); + } + Ok(()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LoraWeight { + pub lora_name: String, + #[serde(default = "one")] + pub lora_scale: f32, +} + +fn one() -> f32 { + 1.0 +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LocalAsset { + pub id: String, + pub kind: String, + pub path: String, +} diff --git a/crates/freya-crd/Cargo.toml b/crates/freya-crd/Cargo.toml new file mode 100644 index 0000000..bf537c9 --- /dev/null +++ b/crates/freya-crd/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "freya-crd" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Freya Kubernetes CRD types (v1alpha1)" + +[dependencies] +kube = { workspace = true, features = ["derive"] } +k8s-openapi = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +schemars = { workspace = true } diff --git a/crates/freya-crd/src/lib.rs b/crates/freya-crd/src/lib.rs new file mode 100644 index 0000000..830b644 --- /dev/null +++ b/crates/freya-crd/src/lib.rs @@ -0,0 +1,478 @@ +//! Freya CRD types for `freya.dataknife.ai/v1alpha1`. + +use kube::CustomResource; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +pub const API_GROUP: &str = "freya.dataknife.ai"; +pub const API_VERSION: &str = "v1alpha1"; + +/// Image reference for Freya components. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub struct ImageRef { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub repository: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tag: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pull_policy: Option, +} + +/// Reference to a Secret key holding credentials. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub struct SecretKeyRef { + pub name: String, + #[serde(default = "default_api_key_key")] + pub key: String, +} + +fn default_api_key_key() -> String { + "apiKey".into() +} + +/// Default Secret key name for Civitai tokens. +pub fn default_civitai_key() -> String { + "apiKey".into() +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct OpenRouterSpec { + pub secret_ref: SecretKeyRef, + /// Default chat / plan model id (OpenRouter). + #[serde(default = "default_chat_model")] + pub chat_model: String, + /// Default cloud image model id (OpenRouter). + #[serde(default = "default_image_model")] + pub image_model: String, + #[serde(default = "default_openrouter_base")] + pub base_url: String, +} + +fn default_chat_model() -> String { + "openrouter/auto".into() +} + +fn default_image_model() -> String { + "black-forest-labs/flux.2-klein-4b".into() +} + +fn default_openrouter_base() -> String { + "https://openrouter.ai/api/v1".into() +} + +impl Default for OpenRouterSpec { + fn default() -> Self { + Self { + secret_ref: SecretKeyRef { + name: "freya-openrouter".into(), + key: default_api_key_key(), + }, + chat_model: default_chat_model(), + image_model: default_image_model(), + base_url: default_openrouter_base(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "lowercase")] +pub enum ChatBackendKind { + #[default] + Openrouter, + Vllm, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub struct ChatBackendSpec { + #[serde(default)] + pub kind: ChatBackendKind, + /// When kind=vllm, OpenAI-compatible base URL. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base_url: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub struct IngressSpec { + #[serde(default)] + pub enabled: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub class_name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct StorageSpec { + #[serde(default = "default_gallery_size")] + pub gallery_size: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub storage_class_name: Option, +} + +fn default_gallery_size() -> String { + "20Gi".into() +} + +impl Default for StorageSpec { + fn default() -> Self { + Self { + gallery_size: default_gallery_size(), + storage_class_name: None, + } + } +} + +/// Optional Civitai credentials for automated model/LoRA installs (never inline the key). +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub struct CivitaiSpec { + /// Secret holding the Civitai API token (create from UI or `kubectl create secret`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub secret_ref: Option, +} + +/// Optional Hugging Face token for gated checkpoints. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub struct HuggingFaceSpec { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub secret_ref: Option, +} + +/// Namespaced Freya studio: API + UI + gallery. +#[derive(CustomResource, Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[kube( + group = "freya.dataknife.ai", + version = "v1alpha1", + kind = "FreyaStudio", + plural = "freyastudios", + shortname = "fstudio", + namespaced, + status = "FreyaStudioStatus", + printcolumn = r#"{"name":"Phase","type":"string","jsonPath":".status.phase"}"#, + printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"# +)] +#[serde(rename_all = "camelCase")] +pub struct FreyaStudioSpec { + #[serde(default)] + pub open_router: OpenRouterSpec, + /// Civitai API key for browsing/installing LoRAs & checkpoints onto workers. + #[serde(default)] + pub civitai: CivitaiSpec, + #[serde(default)] + pub hugging_face: HuggingFaceSpec, + #[serde(default)] + pub chat_backend: ChatBackendSpec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api_image: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ui_image: Option, + #[serde(default)] + pub storage: StorageSpec, + #[serde(default)] + pub ingress: IngressSpec, + /// 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 (and UI nginx proxy). Set for non-dev / Ingress. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api_token_secret_ref: Option, + #[serde(default = "default_replicas")] + pub replicas: i32, +} + +fn default_replicas() -> i32 { + 1 +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub struct FreyaStudioStatus { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub phase: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api_endpoint: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ui_endpoint: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub observed_generation: Option, +} + +/// Generation backend selection. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "lowercase")] +pub enum GenerationBackend { + #[default] + Auto, + Openrouter, + Local, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] +#[serde(rename_all = "camelCase")] +pub struct LoraRef { + pub name: String, + #[serde(default = "default_lora_scale")] + pub scale: f32, +} + +fn default_lora_scale() -> f32 { + 1.0 +} + +/// Declarative image generation request. +#[derive(CustomResource, Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[kube( + group = "freya.dataknife.ai", + version = "v1alpha1", + kind = "FreyaGeneration", + plural = "freyagenerations", + shortname = "fgen", + namespaced, + status = "FreyaGenerationStatus", + printcolumn = r#"{"name":"Phase","type":"string","jsonPath":".status.phase"}"#, + printcolumn = r#"{"name":"Backend","type":"string","jsonPath":".status.backend"}"#, + printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"# +)] +#[serde(rename_all = "camelCase")] +pub struct FreyaGenerationSpec { + pub prompt: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub negative_prompt: Option, + /// `off` | `on` | `auto` + #[serde(default = "default_enhance")] + pub enhance: String, + #[serde(default)] + pub backend: GenerationBackend, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub style_ref: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub loras: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub seed: Option, + /// FreyaStudio that owns API routing (same namespace). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub studio_ref: Option, +} + +fn default_enhance() -> String { + "auto".into() +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub struct FreyaGenerationStatus { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub phase: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub backend: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub artifact_path: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enhanced_prompt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, +} + +/// Curated style pack (Civitai-inspired metadata, not weight hosting by itself). +#[derive(CustomResource, Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[kube( + group = "freya.dataknife.ai", + version = "v1alpha1", + kind = "FreyaStyle", + plural = "freyastyles", + shortname = "fstyle", + namespaced, + status = "FreyaStyleStatus" +)] +#[serde(rename_all = "camelCase")] +pub struct FreyaStyleSpec { + pub display_name: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tags: Vec, + pub example_prompt: String, + #[serde(default)] + pub backend: GenerationBackend, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub open_router_model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub local_checkpoint: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub loras: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub trigger_words: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub recommended_size: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thumbnail_url: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub struct FreyaStyleStatus { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub phase: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "lowercase")] +pub enum DiffusionEngine { + #[default] + #[serde(rename = "vllm-omni")] + VllmOmni, + #[serde(rename = "sglang")] + Sglang, +} + +/// Where the diffusion / LoRA engine runs. +/// +/// CRD enum values are lowercase (`incluster`, `external`). The `inCluster` alias +/// is accepted by Rust serde for convenience; kubectl/OpenAPI only allow `incluster`. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "lowercase")] +pub enum WorkerPlacement { + /// Operator creates a GPU Deployment in-cluster. + #[default] + #[serde(alias = "inCluster")] + InCluster, + /// Reach a remote physical (or other) host Freya already can HTTP to. + External, +} + +/// 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. +#[derive(CustomResource, Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[kube( + group = "freya.dataknife.ai", + version = "v1alpha1", + kind = "FreyaDiffusionWorker", + plural = "freyadiffusionworkers", + shortname = "fdiff", + namespaced, + status = "FreyaDiffusionWorkerStatus", + printcolumn = r#"{"name":"Phase","type":"string","jsonPath":".status.phase"}"#, + printcolumn = r#"{"name":"Engine","type":"string","jsonPath":".spec.engine"}"#, + printcolumn = r#"{"name":"Placement","type":"string","jsonPath":".spec.placement"}"# +)] +#[serde(rename_all = "camelCase")] +pub struct FreyaDiffusionWorkerSpec { + #[serde(default)] + pub placement: WorkerPlacement, + /// Required when `placement: external` — e.g. `http://gpu-box.lan:8091`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub external_endpoint: Option, + #[serde(default)] + pub engine: DiffusionEngine, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub image: Option, + /// HuggingFace / local model id passed to the engine (in-cluster). + #[serde(default = "default_local_model")] + pub model: String, + #[serde(default = "default_gpu_count")] + pub gpu_count: i32, + #[serde(default = "default_models_size")] + pub models_pvc_size: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub storage_class_name: Option, + #[serde(default = "default_worker_port")] + pub port: i32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub node_selector: Option>, + /// Optional admin/API token Secret for remote LoRA install + generate. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auth_secret_ref: Option, +} + +fn default_local_model() -> String { + "stabilityai/stable-diffusion-xl-base-1.0".into() +} + +fn default_gpu_count() -> i32 { + 1 +} + +fn default_models_size() -> String { + "100Gi".into() +} + +fn default_worker_port() -> i32 { + 8091 +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub struct FreyaDiffusionWorkerStatus { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub phase: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub endpoint: Option, +} + +/// Declarative model/LoRA download into a worker PVC. +#[derive(CustomResource, Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[kube( + group = "freya.dataknife.ai", + version = "v1alpha1", + kind = "FreyaModelAsset", + plural = "freyamodelassets", + shortname = "fasset", + namespaced, + status = "FreyaModelAssetStatus", + printcolumn = r#"{"name":"Phase","type":"string","jsonPath":".status.phase"}"# +)] +#[serde(rename_all = "camelCase")] +pub struct FreyaModelAssetSpec { + /// `huggingface` | `civitai` | `url` + pub source: String, + pub url: String, + /// Relative path under the worker models PVC (e.g. `loras/my.safetensors`). + pub dest_path: String, + pub worker_ref: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub secret_ref: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] +#[serde(rename_all = "camelCase")] +pub struct FreyaModelAssetStatus { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub phase: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + use kube::CustomResourceExt; + + #[test] + fn studio_crd_has_group() { + let crd = FreyaStudio::crd(); + assert_eq!(crd.spec.group, API_GROUP); + } + + #[test] + fn all_crds_render() { + let _ = FreyaStudio::crd(); + let _ = FreyaGeneration::crd(); + let _ = FreyaStyle::crd(); + let _ = FreyaDiffusionWorker::crd(); + let _ = FreyaModelAsset::crd(); + } +} diff --git a/crates/freya-operator/Cargo.toml b/crates/freya-operator/Cargo.toml new file mode 100644 index 0000000..a84c05e --- /dev/null +++ b/crates/freya-operator/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "freya-operator" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Freya Kubernetes operator" + +[[bin]] +name = "freya-operator" +path = "src/main.rs" + +[[bin]] +name = "freya-crdgen" +path = "src/crdgen.rs" + +[dependencies] +freya-crd = { workspace = true } +anyhow = { workspace = true } +tokio = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +kube = { workspace = true } +k8s-openapi = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +serde_yaml = { workspace = true } +futures = { workspace = true } +thiserror = { workspace = true } +reqwest = { workspace = true } diff --git a/crates/freya-operator/src/crdgen.rs b/crates/freya-operator/src/crdgen.rs new file mode 100644 index 0000000..38f56b4 --- /dev/null +++ b/crates/freya-operator/src/crdgen.rs @@ -0,0 +1,20 @@ +//! Print installable CRD YAML for all Freya kinds. + +use freya_crd::{FreyaDiffusionWorker, FreyaGeneration, FreyaModelAsset, FreyaStudio, FreyaStyle}; +use kube::CustomResourceExt; + +fn main() { + let docs = [ + FreyaStudio::crd(), + FreyaGeneration::crd(), + FreyaStyle::crd(), + FreyaDiffusionWorker::crd(), + FreyaModelAsset::crd(), + ]; + for (i, crd) in docs.iter().enumerate() { + if i > 0 { + println!("---"); + } + println!("{}", serde_yaml::to_string(crd).expect("serialize CRD")); + } +} diff --git a/crates/freya-operator/src/main.rs b/crates/freya-operator/src/main.rs new file mode 100644 index 0000000..b83ffef --- /dev/null +++ b/crates/freya-operator/src/main.rs @@ -0,0 +1,116 @@ +//! Freya operator — reconciles FreyaStudio, FreyaGeneration, FreyaDiffusionWorker, FreyaModelAsset. + +mod reconcile; + +use anyhow::Context; +use freya_crd::{ + FreyaDiffusionWorker, FreyaGeneration, FreyaModelAsset, FreyaStudio, API_GROUP, API_VERSION, +}; +use futures::StreamExt; +use kube::runtime::controller::{Action, Controller}; +use kube::runtime::watcher::Config; +use kube::{Api, Client}; +use std::sync::Arc; +use tracing::{error, info}; + +#[derive(Clone)] +pub struct Ctx { + pub client: Client, +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .init(); + + info!( + group = API_GROUP, + version = API_VERSION, + "freya-operator starting" + ); + + let client = Client::try_default() + .await + .context("create kube client (in-cluster or KUBECONFIG)")?; + let ctx = Arc::new(Ctx { + client: client.clone(), + }); + + let studios = Api::::all(client.clone()); + let generations = Api::::all(client.clone()); + let workers = Api::::all(client.clone()); + let assets = Api::::all(client.clone()); + + let studio_ctrl = Controller::new(studios, Config::default()) + .run( + reconcile::studio::reconcile, + reconcile::studio::error_policy, + ctx.clone(), + ) + .for_each(|res| async move { + match res { + Ok((obj, _)) => info!(name = %obj.name, "studio reconcile ok"), + Err(e) => error!(error = %e, "studio reconcile error"), + } + }); + + let gen_ctrl = Controller::new(generations, Config::default()) + .run( + reconcile::generation::reconcile, + reconcile::generation::error_policy, + ctx.clone(), + ) + .for_each(|res| async move { + match res { + Ok((obj, _)) => info!(name = %obj.name, "generation reconcile ok"), + Err(e) => error!(error = %e, "generation reconcile error"), + } + }); + + let worker_ctrl = Controller::new(workers, Config::default()) + .run( + reconcile::worker::reconcile, + reconcile::worker::error_policy, + ctx.clone(), + ) + .for_each(|res| async move { + match res { + Ok((obj, _)) => info!(name = %obj.name, "worker reconcile ok"), + Err(e) => error!(error = %e, "worker reconcile error"), + } + }); + + let asset_ctrl = Controller::new(assets, Config::default()) + .run( + reconcile::asset::reconcile, + reconcile::asset::error_policy, + ctx.clone(), + ) + .for_each(|res| async move { + match res { + Ok((obj, _)) => info!(name = %obj.name, "asset reconcile ok"), + Err(e) => error!(error = %e, "asset reconcile error"), + } + }); + + tokio::select! { + _ = studio_ctrl => {}, + _ = gen_ctrl => {}, + _ = worker_ctrl => {}, + _ = asset_ctrl => {}, + _ = tokio::signal::ctrl_c() => { + info!("shutdown signal received"); + } + } + + Ok(()) +} + +#[allow(dead_code)] +fn _action_requeue() -> Action { + Action::requeue(std::time::Duration::from_secs(60)) +} diff --git a/crates/freya-operator/src/reconcile/asset.rs b/crates/freya-operator/src/reconcile/asset.rs new file mode 100644 index 0000000..71e9ccb --- /dev/null +++ b/crates/freya-operator/src/reconcile/asset.rs @@ -0,0 +1,381 @@ +//! Reconcile FreyaModelAsset — install LoRA/checkpoint onto worker (in-cluster Job or remote HTTP). + +use crate::reconcile::{LABEL_INSTANCE, LABEL_MANAGED, LABEL_NAME, MANAGED_BY}; +use crate::Ctx; +use freya_crd::{FreyaDiffusionWorker, FreyaModelAsset, WorkerPlacement}; +use k8s_openapi::api::batch::v1::{Job, JobSpec}; +use k8s_openapi::api::core::v1::{ + Container, EnvVar, EnvVarSource, PersistentVolumeClaimVolumeSource, PodSpec, PodTemplateSpec, + SecretKeySelector, Volume, VolumeMount, +}; +use k8s_openapi::apimachinery::pkg::apis::meta::v1::{ObjectMeta, OwnerReference}; +use kube::api::{Patch, PatchParams}; +use kube::runtime::controller::Action; +use kube::{Api, Resource, ResourceExt}; +use std::collections::BTreeMap; +use std::path::{Component, Path}; +use std::sync::Arc; +use std::time::Duration; +use tracing::{info, warn}; + +pub async fn reconcile(asset: Arc, ctx: Arc) -> Result { + let ns = asset.namespace().ok_or(Error::MissingNamespace)?; + let name = asset.name_any(); + + match asset.status.as_ref().and_then(|s| s.phase.as_deref()) { + Some("Succeeded") | Some("Failed") => return Ok(Action::await_change()), + _ => {} + } + + patch_phase(&ctx, &ns, &name, "Installing", None).await?; + + let workers: Api = Api::namespaced(ctx.client.clone(), &ns); + let worker = workers + .get(&asset.spec.worker_ref) + .await + .map_err(Error::Kube)?; + + let owner = asset.controller_owner_ref(&()).ok_or(Error::OwnerRef)?; + + match worker.spec.placement { + WorkerPlacement::External => { + let endpoint = worker + .spec + .external_endpoint + .clone() + .or_else(|| worker.status.as_ref().and_then(|s| s.endpoint.clone())) + .ok_or(Error::MissingEndpoint)?; + + info!(%ns, asset = %name, %endpoint, "installing LoRA/asset on remote worker"); + install_remote(&ctx, &ns, &asset, &worker, &endpoint).await?; + patch_phase( + &ctx, + &ns, + &name, + "Succeeded", + Some("installed on remote worker".into()), + ) + .await?; + Ok(Action::await_change()) + } + WorkerPlacement::InCluster => { + info!(%ns, asset = %name, "creating download Job into worker models PVC"); + ensure_download_job(&ctx, &ns, &name, &asset, &worker, &owner).await?; + watch_download_job(&ctx, &ns, &name).await + } + } +} + +async fn install_remote( + ctx: &Ctx, + ns: &str, + asset: &FreyaModelAsset, + worker: &FreyaDiffusionWorker, + endpoint: &str, +) -> Result<(), Error> { + sanitize_dest_path(&asset.spec.dest_path)?; + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(600)) + .build() + .map_err(|e| Error::Http(e.to_string()))?; + + let body = serde_json::json!({ + "source": asset.spec.source, + "url": asset.spec.url, + "destPath": asset.spec.dest_path, + }); + + let mut req = client + .post(format!( + "{}/v1/assets/install", + endpoint.trim_end_matches('/') + )) + .json(&body); + + if let Some(auth) = &worker.spec.auth_secret_ref { + let token = read_secret_key(ctx, ns, &auth.name, &auth.key).await?; + req = req.bearer_auth(token); + } + + let resp = req.send().await.map_err(|e| Error::Http(e.to_string()))?; + + if !resp.status().is_success() { + let msg = resp.text().await.unwrap_or_default(); + return Err(Error::Http(format!("remote install failed: {msg}"))); + } + Ok(()) +} + +async fn read_secret_key(ctx: &Ctx, ns: &str, name: &str, key: &str) -> Result { + use k8s_openapi::api::core::v1::Secret; + let api: Api = Api::namespaced(ctx.client.clone(), ns); + let secret = api.get(name).await.map_err(Error::Kube)?; + let data = secret + .data + .ok_or_else(|| Error::Http(format!("secret {name} has no data")))?; + let bytes = data + .get(key) + .ok_or_else(|| Error::Http(format!("secret {name} missing key {key}")))?; + String::from_utf8(bytes.0.clone()) + .map_err(|e| Error::Http(format!("secret {name}/{key} not utf8: {e}"))) +} + +/// Reject absolute / `..` / shell-metachar dest paths; must stay under `/models`. +fn sanitize_dest_path(dest: &str) -> Result<(), Error> { + if dest.is_empty() { + return Err(Error::BadDest("destPath is empty".into())); + } + let path = Path::new(dest); + if path.is_absolute() + || path + .components() + .any(|c| matches!(c, Component::ParentDir | Component::RootDir)) + { + return Err(Error::BadDest( + "destPath must be relative under /models (no '..')".into(), + )); + } + if dest.chars().any(|c| { + matches!( + c, + ';' | '|' + | '&' + | '$' + | '`' + | '\n' + | '\r' + | '"' + | '\'' + | '\\' + | '\0' + | '(' + | ')' + | '<' + | '>' + | '*' + | '?' + | '[' + | ']' + | '{' + | '}' + | '!' + | '#' + ) + }) { + return Err(Error::BadDest( + "destPath contains disallowed characters".into(), + )); + } + Ok(()) +} + +async fn ensure_download_job( + ctx: &Ctx, + ns: &str, + name: &str, + asset: &FreyaModelAsset, + worker: &FreyaDiffusionWorker, + owner: &OwnerReference, +) -> Result<(), Error> { + sanitize_dest_path(&asset.spec.dest_path)?; + let job_name = format!("freya-asset-{name}"); + let pvc = format!("{}-models", asset.spec.worker_ref); + let mut env = vec![ + EnvVar { + name: "ASSET_URL".into(), + value: Some(asset.spec.url.clone()), + ..Default::default() + }, + EnvVar { + name: "DEST_PATH".into(), + value: Some(asset.spec.dest_path.clone()), + ..Default::default() + }, + EnvVar { + name: "MODELS_DIR".into(), + value: Some("/models".into()), + ..Default::default() + }, + ]; + + if let Some(secret) = &asset.spec.secret_ref { + env.push(EnvVar { + name: "ASSET_TOKEN".into(), + value_from: Some(EnvVarSource { + secret_key_ref: Some(SecretKeySelector { + name: secret.name.clone(), + key: secret.key.clone(), + optional: Some(true), + }), + ..Default::default() + }), + ..Default::default() + }); + } + + let _ = worker; // model path layout shared via PVC + + // No `eval`: curl argv stays literal; dest constrained under MODELS_DIR in-script + Rust. + let job = Job { + metadata: ObjectMeta { + name: Some(job_name.clone()), + namespace: Some(ns.to_string()), + labels: Some(BTreeMap::from([ + (LABEL_MANAGED.to_string(), MANAGED_BY.to_string()), + (LABEL_NAME.to_string(), "freya-asset".to_string()), + (LABEL_INSTANCE.to_string(), name.to_string()), + ])), + owner_references: Some(vec![owner.clone()]), + ..Default::default() + }, + spec: Some(JobSpec { + backoff_limit: Some(2), + ttl_seconds_after_finished: Some(3600), + template: PodTemplateSpec { + metadata: Some(ObjectMeta { + labels: Some(BTreeMap::from([ + (LABEL_MANAGED.to_string(), MANAGED_BY.to_string()), + (LABEL_INSTANCE.to_string(), name.to_string()), + ])), + ..Default::default() + }), + spec: Some(PodSpec { + restart_policy: Some("OnFailure".into()), + containers: vec![Container { + name: "download".into(), + image: Some("curlimages/curl:8.11.1".into()), + command: Some(vec!["/bin/sh".into(), "-c".into()]), + args: Some(vec![r#"set -eu +case "$DEST_PATH" in + /*|*..*) + echo "refusing unsafe DEST_PATH" >&2 + exit 1 + ;; +esac +DEST="$MODELS_DIR/$DEST_PATH" +case "$DEST" in + "$MODELS_DIR"/*) ;; + *) + echo "dest escapes models dir" >&2 + exit 1 + ;; +esac +mkdir -p "$(dirname "$DEST")" +if [ -n "${ASSET_TOKEN:-}" ]; then + curl -fL -H "Authorization: Bearer ${ASSET_TOKEN}" -o "$DEST" -- "$ASSET_URL" +else + curl -fL -o "$DEST" -- "$ASSET_URL" +fi +echo "installed $DEST_PATH" +"# + .into()]), + env: Some(env), + volume_mounts: Some(vec![VolumeMount { + name: "models".into(), + mount_path: "/models".into(), + ..Default::default() + }]), + ..Default::default() + }], + volumes: Some(vec![Volume { + name: "models".into(), + persistent_volume_claim: Some(PersistentVolumeClaimVolumeSource { + claim_name: pvc, + ..Default::default() + }), + ..Default::default() + }]), + ..Default::default() + }), + }, + ..Default::default() + }), + ..Default::default() + }; + + let api: Api = Api::namespaced(ctx.client.clone(), ns); + api.patch( + &job_name, + &PatchParams::apply(MANAGED_BY).force(), + &Patch::Apply(&job), + ) + .await + .map_err(Error::Kube)?; + Ok(()) +} + +async fn watch_download_job(ctx: &Ctx, ns: &str, name: &str) -> Result { + let job_name = format!("freya-asset-{name}"); + let api: Api = Api::namespaced(ctx.client.clone(), ns); + let job = api.get(&job_name).await.map_err(Error::Kube)?; + let status = job.status.as_ref(); + let succeeded = status.and_then(|s| s.succeeded).unwrap_or(0); + let failed = status.and_then(|s| s.failed).unwrap_or(0); + + if succeeded > 0 { + patch_phase( + ctx, + ns, + name, + "Succeeded", + Some("download Job completed".into()), + ) + .await?; + return Ok(Action::await_change()); + } + if failed > 0 { + patch_phase(ctx, ns, name, "Failed", Some("download Job failed".into())).await?; + return Ok(Action::await_change()); + } + + patch_phase( + ctx, + ns, + name, + "Installing", + Some("waiting for download Job".into()), + ) + .await?; + Ok(Action::requeue(Duration::from_secs(15))) +} + +async fn patch_phase( + ctx: &Ctx, + ns: &str, + name: &str, + phase: &str, + message: Option, +) -> Result<(), Error> { + let api: Api = Api::namespaced(ctx.client.clone(), ns); + let status = serde_json::json!({ + "status": { + "phase": phase, + "message": message, + } + }); + api.patch_status(name, &PatchParams::default(), &Patch::Merge(&status)) + .await + .map_err(Error::Kube)?; + Ok(()) +} + +pub fn error_policy(asset: Arc, err: &Error, _ctx: Arc) -> Action { + warn!(asset = %asset.name_any(), error = %err, "asset reconcile failed"); + Action::requeue(Duration::from_secs(30)) +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("missing namespace")] + MissingNamespace, + #[error("owner reference")] + OwnerRef, + #[error("worker has no endpoint")] + MissingEndpoint, + #[error("bad destPath: {0}")] + BadDest(String), + #[error("kube: {0}")] + Kube(#[from] kube::Error), + #[error("http: {0}")] + Http(String), +} diff --git a/crates/freya-operator/src/reconcile/generation.rs b/crates/freya-operator/src/reconcile/generation.rs new file mode 100644 index 0000000..d587e6b --- /dev/null +++ b/crates/freya-operator/src/reconcile/generation.rs @@ -0,0 +1,160 @@ +//! Reconcile FreyaGeneration — call Freya API /v1/run and update status. + +use crate::Ctx; +use freya_crd::{FreyaGeneration, FreyaStudio, GenerationBackend}; +use kube::api::{Patch, PatchParams}; +use kube::runtime::controller::Action; +use kube::{Api, ResourceExt}; +use serde::Deserialize; +use std::sync::Arc; +use std::time::Duration; +use tracing::{info, warn}; + +pub async fn reconcile(gen: Arc, ctx: Arc) -> Result { + let ns = gen.namespace().ok_or(Error::MissingNamespace)?; + let name = gen.name_any(); + + if gen.status.as_ref().and_then(|s| s.phase.as_deref()) == Some("Succeeded") + || gen.status.as_ref().and_then(|s| s.phase.as_deref()) == Some("Failed") + { + return Ok(Action::await_change()); + } + + patch_status( + &ctx, + &ns, + &name, + StatusPatch { + phase: "Running", + ..Default::default() + }, + ) + .await?; + + let studio_name = gen + .spec + .studio_ref + .clone() + .unwrap_or_else(|| "freya".into()); + let studios: Api = Api::namespaced(ctx.client.clone(), &ns); + let studio = studios.get(&studio_name).await.map_err(Error::Kube)?; + let api_base = studio + .status + .as_ref() + .and_then(|s| s.api_endpoint.clone()) + .unwrap_or_else(|| format!("http://{studio_name}-api.{ns}.svc.cluster.local:8080")); + + let backend = match gen.spec.backend { + GenerationBackend::Auto => "auto", + GenerationBackend::Openrouter => "openrouter", + GenerationBackend::Local => "local", + }; + + let body = serde_json::json!({ + "prompt": gen.spec.prompt, + "negativePrompt": gen.spec.negative_prompt, + "enhance": gen.spec.enhance, + "backend": backend, + "model": gen.spec.model, + "styleRef": gen.spec.style_ref, + "loras": gen.spec.loras, + "size": gen.spec.size, + "seed": gen.spec.seed, + }); + + info!(%ns, generation = %name, %api_base, "calling Freya API /v1/run"); + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(600)) + .build() + .map_err(|e| Error::Http(e.to_string()))?; + + let resp = client + .post(format!("{api_base}/v1/run")) + .json(&body) + .send() + .await + .map_err(|e| Error::Http(e.to_string()))?; + + if !resp.status().is_success() { + let msg = resp.text().await.unwrap_or_default(); + patch_status( + &ctx, + &ns, + &name, + StatusPatch { + phase: "Failed", + message: Some(msg.chars().take(500).collect()), + ..Default::default() + }, + ) + .await?; + return Ok(Action::await_change()); + } + + let result: RunResponse = resp.json().await.map_err(|e| Error::Http(e.to_string()))?; + patch_status( + &ctx, + &ns, + &name, + StatusPatch { + phase: "Succeeded", + backend: Some(result.backend), + artifact: result.artifact_id.map(|id| format!("gallery/{id}")), + enhanced_prompt: result.enhanced_prompt, + message: None, + }, + ) + .await?; + + Ok(Action::await_change()) +} + +#[derive(Debug, Deserialize)] +struct RunResponse { + backend: String, + #[serde(default, alias = "artifactId")] + artifact_id: Option, + #[serde(default, alias = "enhancedPrompt")] + enhanced_prompt: Option, +} + +#[derive(Default)] +struct StatusPatch { + phase: &'static str, + backend: Option, + artifact: Option, + enhanced_prompt: Option, + message: Option, +} + +async fn patch_status(ctx: &Ctx, ns: &str, name: &str, patch: StatusPatch) -> Result<(), Error> { + let api: Api = Api::namespaced(ctx.client.clone(), ns); + let status = serde_json::json!({ + "status": { + "phase": patch.phase, + "backend": patch.backend, + "artifactPath": patch.artifact, + "enhancedPrompt": patch.enhanced_prompt, + "message": patch.message, + } + }); + api.patch_status(name, &PatchParams::default(), &Patch::Merge(&status)) + .await + .map_err(Error::Kube)?; + Ok(()) +} + +pub fn error_policy(gen: Arc, err: &Error, _ctx: Arc) -> Action { + warn!(generation = %gen.name_any(), error = %err, "generation reconcile failed"); + Action::requeue(Duration::from_secs(20)) +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("missing namespace")] + MissingNamespace, + #[error("kube: {0}")] + Kube(#[from] kube::Error), + #[error("http: {0}")] + Http(String), +} diff --git a/crates/freya-operator/src/reconcile/mod.rs b/crates/freya-operator/src/reconcile/mod.rs new file mode 100644 index 0000000..a2044fd --- /dev/null +++ b/crates/freya-operator/src/reconcile/mod.rs @@ -0,0 +1,31 @@ +pub mod asset; +pub mod generation; +pub mod studio; +pub mod worker; + +pub const LABEL_MANAGED: &str = "app.kubernetes.io/managed-by"; +pub const LABEL_NAME: &str = "app.kubernetes.io/name"; +pub const LABEL_INSTANCE: &str = "app.kubernetes.io/instance"; +pub const LABEL_COMPONENT: &str = "app.kubernetes.io/component"; +pub const MANAGED_BY: &str = "freya-operator"; + +pub fn default_api_image() -> (String, String) { + ( + "harbor.dataknife.net/library/freya-api".into(), + "0.1.0".into(), + ) +} + +pub fn default_ui_image() -> (String, String) { + ( + "harbor.dataknife.net/library/freya-web".into(), + "0.1.0".into(), + ) +} + +pub fn default_worker_image() -> (String, String) { + ( + "harbor.dataknife.net/library/freya-diffusion-worker".into(), + "0.1.0".into(), + ) +} diff --git a/crates/freya-operator/src/reconcile/studio.rs b/crates/freya-operator/src/reconcile/studio.rs new file mode 100644 index 0000000..b92239b --- /dev/null +++ b/crates/freya-operator/src/reconcile/studio.rs @@ -0,0 +1,544 @@ +//! Reconcile FreyaStudio → API/UI 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, +}; +use crate::Ctx; +use freya_crd::{FreyaDiffusionWorker, FreyaStudio, WorkerPlacement}; +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, +}; +use k8s_openapi::api::networking::v1::{ + HTTPIngressPath, HTTPIngressRuleValue, Ingress, IngressBackend, IngressRule, + IngressServiceBackend, IngressSpec, ServiceBackendPort, +}; +use k8s_openapi::apimachinery::pkg::apis::meta::v1::{LabelSelector, ObjectMeta, OwnerReference}; +use k8s_openapi::apimachinery::pkg::util::intstr::IntOrString; +use kube::api::{Patch, PatchParams}; +use kube::runtime::controller::Action; +use kube::{Api, Resource, ResourceExt}; +use std::collections::BTreeMap; +use std::sync::Arc; +use std::time::Duration; +use tracing::{info, warn}; + +pub async fn reconcile(studio: Arc, ctx: Arc) -> Result { + let ns = studio.namespace().ok_or(Error::MissingNamespace)?; + let name = studio.name_any(); + info!(%ns, studio = %name, "reconciling FreyaStudio"); + + let owner = studio.controller_owner_ref(&()).ok_or(Error::OwnerRef)?; + ensure_gallery_pvc(&ctx, &ns, &name, &studio, &owner).await?; + ensure_api_deployment(&ctx, &ns, &name, &studio, &owner).await?; + ensure_ui_deployment(&ctx, &ns, &name, &studio, &owner).await?; + ensure_service(&ctx, &ns, &name, "api", 8080, &owner).await?; + ensure_service(&ctx, &ns, &name, "ui", 80, &owner).await?; + if studio.spec.ingress.enabled { + if studio.spec.api_token_secret_ref.is_none() { + warn!( + studio = %name, + "ingress enabled without apiTokenSecretRef — API stays open to the cluster/Internet" + ); + } + ensure_ingress(&ctx, &ns, &name, &studio, &owner).await?; + } + + let api_svc = format!("http://{name}-api.{ns}.svc.cluster.local:8080"); + let ui_svc = format!("http://{name}-ui.{ns}.svc.cluster.local:80"); + patch_status(&ctx, &ns, &name, "Ready", &api_svc, &ui_svc).await?; + + Ok(Action::requeue(Duration::from_secs(120))) +} + +async fn resolve_worker( + ctx: &Ctx, + ns: &str, + worker_name: &str, +) -> Result<(String, Option), Error> { + let workers: Api = Api::namespaced(ctx.client.clone(), ns); + let worker = workers.get(worker_name).await.map_err(Error::Kube)?; + let url = match worker.spec.placement { + WorkerPlacement::External => worker + .spec + .external_endpoint + .clone() + .or_else(|| worker.status.as_ref().and_then(|s| s.endpoint.clone())) + .ok_or(Error::MissingWorkerEndpoint)?, + WorkerPlacement::InCluster => format!( + "http://{worker_name}.{ns}.svc.cluster.local:{}", + worker.spec.port + ), + }; + Ok((url, worker.spec.auth_secret_ref.clone())) +} + +fn labels(instance: &str, component: &str) -> BTreeMap { + BTreeMap::from([ + (LABEL_MANAGED.to_string(), MANAGED_BY.to_string()), + (LABEL_NAME.to_string(), "freya".to_string()), + (LABEL_INSTANCE.to_string(), instance.to_string()), + (LABEL_COMPONENT.to_string(), component.to_string()), + ]) +} + +async fn ensure_gallery_pvc( + ctx: &Ctx, + ns: &str, + name: &str, + studio: &FreyaStudio, + owner: &OwnerReference, +) -> Result<(), Error> { + let pvc_name = format!("{name}-gallery"); + let pvc = PersistentVolumeClaim { + metadata: ObjectMeta { + name: Some(pvc_name.clone()), + namespace: Some(ns.to_string()), + labels: Some(labels(name, "gallery")), + owner_references: Some(vec![owner.clone()]), + ..Default::default() + }, + spec: Some(PersistentVolumeClaimSpec { + access_modes: Some(vec!["ReadWriteOnce".into()]), + resources: Some(k8s_openapi::api::core::v1::VolumeResourceRequirements { + requests: Some(BTreeMap::from([( + "storage".into(), + k8s_openapi::apimachinery::pkg::api::resource::Quantity( + studio.spec.storage.gallery_size.clone(), + ), + )])), + ..Default::default() + }), + storage_class_name: studio.spec.storage.storage_class_name.clone(), + ..Default::default() + }), + ..Default::default() + }; + + let api: Api = Api::namespaced(ctx.client.clone(), ns); + api.patch( + &pvc_name, + &PatchParams::apply(MANAGED_BY).force(), + &Patch::Apply(&pvc), + ) + .await + .map_err(Error::Kube)?; + Ok(()) +} + +fn image_parts( + custom: &Option, + defaults: (String, String), +) -> (String, String, String) { + let (def_repo, def_tag) = defaults; + let repo = custom + .as_ref() + .and_then(|i| i.repository.clone()) + .unwrap_or(def_repo); + let tag = custom + .as_ref() + .and_then(|i| i.tag.clone()) + .unwrap_or(def_tag); + let pull = custom + .as_ref() + .and_then(|i| i.pull_policy.clone()) + .unwrap_or_else(|| "IfNotPresent".into()); + (repo, tag, pull) +} + +fn secret_env(name: &str, secret: &freya_crd::SecretKeyRef, optional: bool) -> EnvVar { + EnvVar { + name: name.into(), + value_from: Some(EnvVarSource { + secret_key_ref: Some(SecretKeySelector { + name: secret.name.clone(), + key: secret.key.clone(), + optional: Some(optional), + }), + ..Default::default() + }), + ..Default::default() + } +} + +async fn ensure_api_deployment( + ctx: &Ctx, + ns: &str, + name: &str, + studio: &FreyaStudio, + owner: &OwnerReference, +) -> Result<(), Error> { + let (repo, tag, pull) = image_parts(&studio.spec.api_image, default_api_image()); + let image = format!("{repo}:{tag}"); + let dep_name = format!("{name}-api"); + let gallery = format!("{name}-gallery"); + let secret = &studio.spec.open_router.secret_ref; + + let mut env = vec![ + EnvVar { + name: "FREYA_GALLERY_DIR".into(), + value: Some("/data/gallery".into()), + ..Default::default() + }, + EnvVar { + name: "FREYA_PACKS_DIR".into(), + value: Some("/packs".into()), + ..Default::default() + }, + EnvVar { + name: "OPENROUTER_BASE_URL".into(), + value: Some(studio.spec.open_router.base_url.clone()), + ..Default::default() + }, + EnvVar { + name: "FREYA_CHAT_MODEL".into(), + value: Some(studio.spec.open_router.chat_model.clone()), + ..Default::default() + }, + EnvVar { + name: "FREYA_IMAGE_MODEL".into(), + value: Some(studio.spec.open_router.image_model.clone()), + ..Default::default() + }, + secret_env("OPENROUTER_API_KEY", secret, false), + ]; + + if let Some(ref worker_name) = studio.spec.diffusion_worker_ref { + env.push(EnvVar { + name: "FREYA_DIFFUSION_WORKER_REF".into(), + value: Some(worker_name.clone()), + ..Default::default() + }); + let (worker_url, worker_auth) = resolve_worker(ctx, ns, worker_name).await?; + env.push(EnvVar { + name: "FREYA_DIFFUSION_WORKER_URL".into(), + value: Some(worker_url), + ..Default::default() + }); + 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 { + env.push(secret_env("FREYA_API_TOKEN", api_tok, false)); + } + + if let Some(ref civ) = studio.spec.civitai.secret_ref { + env.push(secret_env("CIVITAI_API_KEY", civ, true)); + } + + if let Some(ref hf) = studio.spec.hugging_face.secret_ref { + env.push(secret_env("HF_TOKEN", hf, true)); + } + + if matches!( + studio.spec.chat_backend.kind, + freya_crd::ChatBackendKind::Vllm + ) { + if let Some(url) = &studio.spec.chat_backend.base_url { + env.push(EnvVar { + name: "FREYA_CHAT_BASE_URL".into(), + value: Some(url.clone()), + ..Default::default() + }); + env.push(EnvVar { + name: "FREYA_CHAT_BACKEND".into(), + value: Some("vllm".into()), + ..Default::default() + }); + } + } + + let dep = Deployment { + metadata: ObjectMeta { + name: Some(dep_name.clone()), + namespace: Some(ns.to_string()), + labels: Some(labels(name, "api")), + owner_references: Some(vec![owner.clone()]), + ..Default::default() + }, + spec: Some(DeploymentSpec { + replicas: Some(studio.spec.replicas), + selector: LabelSelector { + match_labels: Some(labels(name, "api")), + ..Default::default() + }, + template: PodTemplateSpec { + metadata: Some(ObjectMeta { + labels: Some(labels(name, "api")), + ..Default::default() + }), + spec: Some(PodSpec { + containers: vec![Container { + name: "api".into(), + image: Some(image), + image_pull_policy: Some(pull), + ports: Some(vec![ContainerPort { + container_port: 8080, + name: Some("http".into()), + ..Default::default() + }]), + env: Some(env), + volume_mounts: Some(vec![VolumeMount { + name: "gallery".into(), + mount_path: "/data/gallery".into(), + ..Default::default() + }]), + ..Default::default() + }], + volumes: Some(vec![Volume { + name: "gallery".into(), + persistent_volume_claim: Some(PersistentVolumeClaimVolumeSource { + claim_name: gallery, + ..Default::default() + }), + ..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_ui_deployment( + ctx: &Ctx, + ns: &str, + name: &str, + studio: &FreyaStudio, + owner: &OwnerReference, +) -> Result<(), Error> { + let (repo, tag, pull) = image_parts(&studio.spec.ui_image, default_ui_image()); + let image = format!("{repo}:{tag}"); + let dep_name = format!("{name}-ui"); + + let dep = Deployment { + metadata: ObjectMeta { + name: Some(dep_name.clone()), + namespace: Some(ns.to_string()), + labels: Some(labels(name, "ui")), + owner_references: Some(vec![owner.clone()]), + ..Default::default() + }, + spec: Some(DeploymentSpec { + replicas: Some(studio.spec.replicas), + selector: LabelSelector { + match_labels: Some(labels(name, "ui")), + ..Default::default() + }, + template: PodTemplateSpec { + metadata: Some(ObjectMeta { + labels: Some(labels(name, "ui")), + ..Default::default() + }), + spec: Some(PodSpec { + containers: vec![Container { + name: "ui".into(), + image: Some(image), + image_pull_policy: Some(pull), + ports: Some(vec![ContainerPort { + container_port: 80, + name: Some("http".into()), + ..Default::default() + }]), + env: Some({ + let mut ui_env = vec![EnvVar { + // Consumed by nginx envsubst template → upstream for /v1/. + name: "FREYA_API_UPSTREAM".into(), + value: Some(format!("http://{name}-api:8080")), + ..Default::default() + }]; + // Same token as API so nginx can inject Authorization on /v1/. + if let Some(ref api_tok) = studio.spec.api_token_secret_ref { + ui_env.push(secret_env("FREYA_API_TOKEN", api_tok, false)); + } + ui_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, + instance: &str, + component: &str, + port: i32, + owner: &OwnerReference, +) -> Result<(), Error> { + let svc_name = format!("{instance}-{component}"); + let svc = Service { + metadata: ObjectMeta { + name: Some(svc_name.clone()), + namespace: Some(ns.to_string()), + labels: Some(labels(instance, component)), + owner_references: Some(vec![owner.clone()]), + ..Default::default() + }, + spec: Some(ServiceSpec { + selector: Some(labels(instance, component)), + ports: Some(vec![ServicePort { + name: Some("http".into()), + port, + target_port: Some(IntOrString::Int(port)), + ..Default::default() + }]), + ..Default::default() + }), + ..Default::default() + }; + let api: Api = Api::namespaced(ctx.client.clone(), ns); + api.patch( + &svc_name, + &PatchParams::apply(MANAGED_BY).force(), + &Patch::Apply(&svc), + ) + .await + .map_err(Error::Kube)?; + Ok(()) +} + +async fn ensure_ingress( + ctx: &Ctx, + ns: &str, + name: &str, + studio: &FreyaStudio, + owner: &OwnerReference, +) -> Result<(), Error> { + let host = studio + .spec + .ingress + .host + .clone() + .unwrap_or_else(|| format!("{name}.freya.local")); + 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()]), + ..Default::default() + }, + spec: Some(IngressSpec { + ingress_class_name: studio.spec.ingress.class_name.clone(), + 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() + }, + }, + ], + }), + }]), + ..Default::default() + }), + ..Default::default() + }; + let api: Api = Api::namespaced(ctx.client.clone(), ns); + api.patch( + name, + &PatchParams::apply(MANAGED_BY).force(), + &Patch::Apply(&ing), + ) + .await + .map_err(Error::Kube)?; + Ok(()) +} + +async fn patch_status( + ctx: &Ctx, + ns: &str, + name: &str, + phase: &str, + api_endpoint: &str, + ui_endpoint: &str, +) -> 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, + } + }); + api.patch_status(name, &PatchParams::default(), &Patch::Merge(&status)) + .await + .map_err(Error::Kube)?; + Ok(()) +} + +pub fn error_policy(studio: Arc, err: &Error, _ctx: Arc) -> Action { + warn!(studio = %studio.name_any(), error = %err, "studio reconcile failed"); + Action::requeue(Duration::from_secs(30)) +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("missing namespace")] + MissingNamespace, + #[error("owner reference")] + OwnerRef, + #[error("diffusion worker missing externalEndpoint")] + MissingWorkerEndpoint, + #[error("kube: {0}")] + Kube(#[from] kube::Error), +} diff --git a/crates/freya-operator/src/reconcile/worker.rs b/crates/freya-operator/src/reconcile/worker.rs new file mode 100644 index 0000000..f85bcf6 --- /dev/null +++ b/crates/freya-operator/src/reconcile/worker.rs @@ -0,0 +1,313 @@ +//! Reconcile FreyaDiffusionWorker — in-cluster GPU Deployment or external remote endpoint. + +use crate::reconcile::{ + default_worker_image, LABEL_COMPONENT, LABEL_INSTANCE, LABEL_MANAGED, LABEL_NAME, MANAGED_BY, +}; +use crate::Ctx; +use freya_crd::{FreyaDiffusionWorker, WorkerPlacement}; +use k8s_openapi::api::apps::v1::{Deployment, DeploymentSpec}; +use k8s_openapi::api::core::v1::{ + Container, ContainerPort, EnvVar, PersistentVolumeClaim, PersistentVolumeClaimSpec, + PersistentVolumeClaimVolumeSource, PodSpec, PodTemplateSpec, ResourceRequirements, Service, + ServicePort, ServiceSpec, Volume, VolumeMount, +}; +use k8s_openapi::apimachinery::pkg::apis::meta::v1::{LabelSelector, ObjectMeta, OwnerReference}; +use k8s_openapi::apimachinery::pkg::util::intstr::IntOrString; +use kube::api::{Patch, PatchParams}; +use kube::runtime::controller::Action; +use kube::{Api, Resource, ResourceExt}; +use std::collections::BTreeMap; +use std::sync::Arc; +use std::time::Duration; +use tracing::{info, warn}; + +pub async fn reconcile(worker: Arc, ctx: Arc) -> Result { + let ns = worker.namespace().ok_or(Error::MissingNamespace)?; + let name = worker.name_any(); + info!(%ns, worker = %name, placement = ?worker.spec.placement, "reconciling FreyaDiffusionWorker"); + + let owner = worker.controller_owner_ref(&()).ok_or(Error::OwnerRef)?; + + let endpoint = match worker.spec.placement { + WorkerPlacement::External => { + let ep = worker + .spec + .external_endpoint + .clone() + .ok_or(Error::MissingExternalEndpoint)?; + patch_status(&ctx, &ns, &name, "Ready", &ep).await?; + return Ok(Action::requeue(Duration::from_secs(300))); + } + WorkerPlacement::InCluster => { + ensure_models_pvc(&ctx, &ns, &name, &worker, &owner).await?; + ensure_deployment(&ctx, &ns, &name, &worker, &owner).await?; + ensure_service(&ctx, &ns, &name, worker.spec.port, &owner).await?; + format!("http://{name}.{ns}.svc.cluster.local:{}", worker.spec.port) + } + }; + + patch_status(&ctx, &ns, &name, "Ready", &endpoint).await?; + Ok(Action::requeue(Duration::from_secs(120))) +} + +fn labels(instance: &str) -> BTreeMap { + BTreeMap::from([ + (LABEL_MANAGED.to_string(), MANAGED_BY.to_string()), + (LABEL_NAME.to_string(), "freya-diffusion".to_string()), + (LABEL_INSTANCE.to_string(), instance.to_string()), + (LABEL_COMPONENT.to_string(), "worker".to_string()), + ]) +} + +async fn ensure_models_pvc( + ctx: &Ctx, + ns: &str, + name: &str, + worker: &FreyaDiffusionWorker, + owner: &OwnerReference, +) -> Result<(), Error> { + let pvc_name = format!("{name}-models"); + let pvc = PersistentVolumeClaim { + metadata: ObjectMeta { + name: Some(pvc_name.clone()), + namespace: Some(ns.to_string()), + labels: Some(labels(name)), + owner_references: Some(vec![owner.clone()]), + ..Default::default() + }, + spec: Some(PersistentVolumeClaimSpec { + access_modes: Some(vec!["ReadWriteOnce".into()]), + resources: Some(k8s_openapi::api::core::v1::VolumeResourceRequirements { + requests: Some(BTreeMap::from([( + "storage".into(), + k8s_openapi::apimachinery::pkg::api::resource::Quantity( + worker.spec.models_pvc_size.clone(), + ), + )])), + ..Default::default() + }), + storage_class_name: worker.spec.storage_class_name.clone(), + ..Default::default() + }), + ..Default::default() + }; + let api: Api = Api::namespaced(ctx.client.clone(), ns); + api.patch( + &pvc_name, + &PatchParams::apply(MANAGED_BY).force(), + &Patch::Apply(&pvc), + ) + .await + .map_err(Error::Kube)?; + Ok(()) +} + +async fn ensure_deployment( + ctx: &Ctx, + ns: &str, + name: &str, + worker: &FreyaDiffusionWorker, + owner: &OwnerReference, +) -> Result<(), Error> { + let (repo, tag) = match &worker.spec.image { + Some(i) => ( + i.repository + .clone() + .unwrap_or_else(|| default_worker_image().0), + i.tag.clone().unwrap_or_else(|| default_worker_image().1), + ), + None => default_worker_image(), + }; + let image = format!("{repo}:{tag}"); + let port = worker.spec.port; + + let mut resources = ResourceRequirements { + limits: Some(BTreeMap::from([( + "nvidia.com/gpu".into(), + k8s_openapi::apimachinery::pkg::api::resource::Quantity( + worker.spec.gpu_count.to_string(), + ), + )])), + ..Default::default() + }; + let _ = &mut resources; + + let dep = Deployment { + metadata: ObjectMeta { + name: Some(name.to_string()), + namespace: Some(ns.to_string()), + labels: Some(labels(name)), + owner_references: Some(vec![owner.clone()]), + ..Default::default() + }, + spec: Some(DeploymentSpec { + replicas: Some(1), + selector: LabelSelector { + match_labels: Some(labels(name)), + ..Default::default() + }, + template: PodTemplateSpec { + metadata: Some(ObjectMeta { + labels: Some(labels(name)), + ..Default::default() + }), + spec: Some(PodSpec { + node_selector: worker.spec.node_selector.clone(), + containers: vec![Container { + name: "diffusion".into(), + image: Some(image), + ports: Some(vec![ContainerPort { + container_port: port, + name: Some("http".into()), + ..Default::default() + }]), + env: Some({ + let mut env = vec![ + EnvVar { + name: "FREYA_WORKER_MODEL".into(), + value: Some(worker.spec.model.clone()), + ..Default::default() + }, + EnvVar { + name: "FREYA_WORKER_PORT".into(), + value: Some(port.to_string()), + ..Default::default() + }, + EnvVar { + name: "FREYA_MODELS_DIR".into(), + value: Some("/models".into()), + ..Default::default() + }, + ]; + if let Some(ref auth) = worker.spec.auth_secret_ref { + env.push(EnvVar { + name: "FREYA_WORKER_TOKEN".into(), + value_from: Some(k8s_openapi::api::core::v1::EnvVarSource { + secret_key_ref: Some( + k8s_openapi::api::core::v1::SecretKeySelector { + name: auth.name.clone(), + key: auth.key.clone(), + optional: Some(false), + }, + ), + ..Default::default() + }), + ..Default::default() + }); + } else { + warn!( + worker = %name, + "authSecretRef unset — worker /v1 routes are open on the cluster network" + ); + } + env + }), + resources: Some(resources), + volume_mounts: Some(vec![VolumeMount { + name: "models".into(), + mount_path: "/models".into(), + ..Default::default() + }]), + ..Default::default() + }], + volumes: Some(vec![Volume { + name: "models".into(), + persistent_volume_claim: Some(PersistentVolumeClaimVolumeSource { + claim_name: format!("{name}-models"), + ..Default::default() + }), + ..Default::default() + }]), + ..Default::default() + }), + }, + ..Default::default() + }), + ..Default::default() + }; + + let api: Api = Api::namespaced(ctx.client.clone(), ns); + api.patch( + name, + &PatchParams::apply(MANAGED_BY).force(), + &Patch::Apply(&dep), + ) + .await + .map_err(Error::Kube)?; + Ok(()) +} + +async fn ensure_service( + ctx: &Ctx, + ns: &str, + name: &str, + port: i32, + owner: &OwnerReference, +) -> Result<(), Error> { + let svc = Service { + metadata: ObjectMeta { + name: Some(name.to_string()), + namespace: Some(ns.to_string()), + labels: Some(labels(name)), + owner_references: Some(vec![owner.clone()]), + ..Default::default() + }, + spec: Some(ServiceSpec { + selector: Some(labels(name)), + ports: Some(vec![ServicePort { + name: Some("http".into()), + port, + target_port: Some(IntOrString::Int(port)), + ..Default::default() + }]), + ..Default::default() + }), + ..Default::default() + }; + let api: Api = Api::namespaced(ctx.client.clone(), ns); + api.patch( + name, + &PatchParams::apply(MANAGED_BY).force(), + &Patch::Apply(&svc), + ) + .await + .map_err(Error::Kube)?; + Ok(()) +} + +async fn patch_status( + ctx: &Ctx, + ns: &str, + name: &str, + phase: &str, + endpoint: &str, +) -> Result<(), Error> { + let api: Api = Api::namespaced(ctx.client.clone(), ns); + let status = serde_json::json!({ + "status": { + "phase": phase, + "endpoint": endpoint, + } + }); + api.patch_status(name, &PatchParams::default(), &Patch::Merge(&status)) + .await + .map_err(Error::Kube)?; + Ok(()) +} + +pub fn error_policy(worker: Arc, err: &Error, _ctx: Arc) -> Action { + warn!(worker = %worker.name_any(), error = %err, "worker reconcile failed"); + Action::requeue(Duration::from_secs(30)) +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("missing namespace")] + MissingNamespace, + #[error("owner reference")] + OwnerRef, + #[error("placement=external requires spec.externalEndpoint")] + MissingExternalEndpoint, + #[error("kube: {0}")] + Kube(#[from] kube::Error), +} diff --git a/crates/freya-worker/Cargo.toml b/crates/freya-worker/Cargo.toml new file mode 100644 index 0000000..2190d0d --- /dev/null +++ b/crates/freya-worker/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "freya-worker" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Minimal Freya diffusion worker stub (OpenAI images API + LoRA install)" + +[[bin]] +name = "freya-worker" +path = "src/main.rs" + +[dependencies] +anyhow = { workspace = true } +axum = { workspace = true } +base64 = { workspace = true } +clap = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +tokio = { workspace = true } +tower-http = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +reqwest = { workspace = true } +uuid = { workspace = true } diff --git a/crates/freya-worker/src/main.rs b/crates/freya-worker/src/main.rs new file mode 100644 index 0000000..e75a252 --- /dev/null +++ b/crates/freya-worker/src/main.rs @@ -0,0 +1,279 @@ +//! Minimal diffusion worker: OpenAI-compatible images + asset install for Freya. +//! Production: replace with vLLM-Omni. This stub enables LoRA install + API wiring. + +use axum::extract::{Request, State}; +use axum::http::{header, StatusCode}; +use axum::middleware::{self, Next}; +use axum::response::Response; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use base64::Engine; +use clap::Parser; +use serde::Deserialize; +use serde_json::json; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use tokio::fs; +use tower_http::trace::TraceLayer; +use tracing::{info, warn}; + +#[derive(Parser, Clone)] +struct Config { + #[arg(long, env = "FREYA_WORKER_PORT", default_value = "8091")] + port: u16, + #[arg(long, env = "FREYA_MODELS_DIR", default_value = "./data/models")] + models_dir: PathBuf, + /// Optional bearer token for `/v1/*`. Empty = open (local/dev only). + #[arg(long, env = "FREYA_WORKER_TOKEN", default_value = "")] + token: String, +} + +#[derive(Clone)] +struct App { + models_dir: PathBuf, + token: String, +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .init(); + let cfg = Config::parse(); + if cfg.token.trim().is_empty() { + warn!( + "FREYA_WORKER_TOKEN unset — /v1 routes are open (local/dev only). \ + Set FreyaDiffusionWorker authSecretRef in-cluster." + ); + } else { + info!("FREYA_WORKER_TOKEN set — bearer auth required on /v1 routes"); + } + fs::create_dir_all(cfg.models_dir.join("loras")).await?; + fs::create_dir_all(cfg.models_dir.join("checkpoints")).await?; + let state = Arc::new(App { + models_dir: cfg.models_dir.clone(), + token: cfg.token.trim().to_string(), + }); + let protected = Router::new() + .route("/v1/loras", get(list_loras)) + .route("/v1/images/generations", post(generate)) + .route("/v1/assets/install", post(install)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_worker_token, + )); + let app = Router::new() + .route("/health", get(|| async { Json(json!({"ok": true})) })) + .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)"); + let listener = tokio::net::TcpListener::bind(&bind).await?; + axum::serve(listener, app).await?; + Ok(()) +} + +async fn require_worker_token( + State(app): State>, + req: Request, + next: Next, +) -> Result { + if app.token.is_empty() { + return Ok(next.run(req).await); + } + let auth = req + .headers() + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + let ok = auth + .strip_prefix("Bearer ") + .map(|t| t == app.token) + .unwrap_or(false); + if !ok { + return Err(StatusCode::UNAUTHORIZED); + } + Ok(next.run(req).await) +} + +async fn list_loras(State(app): State>) -> Json { + 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}"), + })); + } + } + Json(json!({ "data": data })) +} + +#[derive(Deserialize)] +struct GenReq { + prompt: String, +} + +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 InstallReq { + url: String, + dest_path: String, +} + +/// Resolve `dest_path` under `models_dir`, rejecting absolute paths and `..` escape. +fn resolve_dest(models_dir: &Path, dest_path: &str) -> Result { + let rel = Path::new(dest_path); + if dest_path.is_empty() || rel.is_absolute() { + return Err("destPath must be a non-empty relative path under models dir".into()); + } + if rel + .components() + .any(|c| matches!(c, Component::ParentDir | Component::RootDir)) + { + return Err("destPath must not contain '..' or absolute components".into()); + } + let models_root = models_dir + .canonicalize() + .map_err(|e| format!("models dir: {e}"))?; + let dest = models_root.join(rel); + // Ensure the joined path still lives under models_root (defense in depth). + if !dest.starts_with(&models_root) { + return Err("destPath escapes models dir".into()); + } + Ok(dest) +} + +fn install_host_ok(host: &str) -> bool { + let h = host.to_ascii_lowercase(); + h == "civitai.com" + || h.ends_with(".civitai.com") + || h == "huggingface.co" + || h.ends_with(".huggingface.co") + || h == "hf.co" + || h.ends_with(".hf.co") +} + +fn install_url_ok(url: &str) -> bool { + let Ok(parsed) = reqwest::Url::parse(url) else { + return false; + }; + if !matches!(parsed.scheme(), "https" | "http") { + return false; + } + parsed.host_str().is_some_and(install_host_ok) +} + +fn download_client() -> Result { + reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::custom(|attempt| { + if attempt.previous().len() >= 5 { + return attempt.error("too many redirects"); + } + match attempt.url().host_str() { + Some(h) if install_host_ok(h) => attempt.follow(), + _ => attempt.error("redirect to disallowed host"), + } + })) + .build() + .map_err(|e| e.to_string()) +} + +async fn install( + State(app): State>, + Json(req): Json, +) -> Result, (axum::http::StatusCode, Json)> { + let dest = resolve_dest(&app.models_dir, &req.dest_path).map_err(|e| { + ( + axum::http::StatusCode::BAD_REQUEST, + Json(json!({ "error": e })), + ) + })?; + if !install_url_ok(&req.url) { + return Err(( + axum::http::StatusCode::BAD_REQUEST, + Json(json!({ + "error": "url must be http(s) on civitai.com, huggingface.co, or hf.co" + })), + )); + } + if let Some(parent) = dest.parent() { + fs::create_dir_all(parent).await.map_err(internal)?; + } + let client = download_client().map_err(internal)?; + let resp = client.get(&req.url).send().await.map_err(internal)?; + if !resp.status().is_success() { + return Err(( + axum::http::StatusCode::BAD_REQUEST, + Json(json!({ + "error": format!("download failed with HTTP {}", resp.status()) + })), + )); + } + let bytes = resp.bytes().await.map_err(internal)?; + fs::write(&dest, &bytes).await.map_err(internal)?; + info!(path = %dest.display(), bytes = bytes.len(), "installed asset"); + Ok(Json(json!({ "ok": true, "path": req.dest_path }))) +} + +fn internal(e: impl std::fmt::Display) -> (axum::http::StatusCode, Json) { + ( + axum::http::StatusCode::BAD_REQUEST, + Json(json!({ "error": e.to_string() })), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + #[test] + fn reject_path_escape() { + let dir = tempfile_dir(); + assert!(resolve_dest(&dir, "../etc/passwd").is_err()); + assert!(resolve_dest(&dir, "/etc/passwd").is_err()); + assert!(resolve_dest(&dir, "loras/../../etc/passwd").is_err()); + assert!(resolve_dest(&dir, "loras/ok.safetensors").is_ok()); + } + + #[test] + fn allowlist_install_hosts() { + assert!(install_url_ok( + "https://civitai.com/api/download/models/1?token=x" + )); + assert!(install_url_ok( + "https://huggingface.co/org/model/resolve/main/file.safetensors" + )); + assert!(!install_url_ok("https://evil.example/steal")); + assert!(!install_url_ok("file:///etc/passwd")); + } + + 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")); + dir + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..1bc562f --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,27 @@ +# 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) +``` + +## Secrets + +| Secret | FreyaStudio / Worker field | Env | Notes | +|--------|----------------------------|-----|-------| +| OpenRouter | `spec.openRouter.secretRef` | `OPENROUTER_API_KEY` | Also editable in UI Settings | +| Civitai | `spec.civitai.secretRef` | `CIVITAI_API_KEY` | UI Settings | +| Hugging Face | `spec.huggingFace.secretRef` | `HF_TOKEN` | optional | +| API bearer | `FreyaStudio.spec.apiTokenSecretRef` | `FREYA_API_TOKEN` | UI nginx injects `Authorization`; 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. diff --git a/docs/CONCEPTS.md b/docs/CONCEPTS.md new file mode 100644 index 0000000..bc1f68d --- /dev/null +++ b/docs/CONCEPTS.md @@ -0,0 +1,13 @@ +# Concepts from legacy Freya + +Source material lives in [`legacy/`](../legacy/) (Compose, ComfyUI, SwarmUI, Ollama, MagicPrompt docs). + +| Old Freya (`legacy/`) | This stack (repo root) | +|-----------|------------| +| 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 | + +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 new file mode 100644 index 0000000..f51237f --- /dev/null +++ b/docs/LOCAL.md @@ -0,0 +1,48 @@ +# Local development + +## Interactive UI mock (no API) + +Iterate on Freya UI without OpenRouter, Civitai, or a worker: + +```bash +make mock-ui +# or: cd web && npm i && npm run dev:mock +``` + +Also: open the normal UI with `?mock=1`, or click **Remember mock** in the banner (stores `localStorage.freya.mock=1`). + +Mock covers Generate, Enhance, Styles, Civitai search/install flow, Gallery remix, and Settings — in-memory with SVG placeholders. + +## Full local stack + +```bash +cp .env.example .env # fill keys +export $(grep -v '^#' .env | xargs) + +make run-api +# other terminal +cd web && npm i && npm run dev + +# optional +make run-worker +# Settings → worker URL http://127.0.0.1:8091 +# Settings → paste Civitai API key → Civitai tab → Install to worker +``` + +### API / worker auth (non-dev) + +By default `FREYA_API_TOKEN` / `FREYA_WORKER_TOKEN` are empty and `/v1` routes are open — both binaries log a warning (local/dev). For anything exposed beyond localhost: + +```bash +export FREYA_API_TOKEN='long-random-secret' +export FREYA_WORKER_TOKEN='long-random-secret' # same value on API + worker +# optional: restrict browser origins (comma-separated) +export FREYA_CORS_ORIGINS='https://freya.example.com,http://127.0.0.1:5173' +# optional for Vite UI: VITE_FREYA_API_TOKEN=$FREYA_API_TOKEN +``` + +Send `Authorization: Bearer $FREYA_API_TOKEN` on `/v1` calls (UI nginx injects this in-cluster). Gallery image GETs stay open so `` works; list/search/settings require the bearer when the token is set. + +In-cluster: set `FreyaStudio.spec.apiTokenSecretRef` and `FreyaDiffusionWorker.spec.authSecretRef`. + +`make ci` runs fmt, clippy, and tests. diff --git a/docs/OPENROUTER.md b/docs/OPENROUTER.md new file mode 100644 index 0000000..ef1b65a --- /dev/null +++ b/docs/OPENROUTER.md @@ -0,0 +1,8 @@ +# OpenRouter + +Freya uses: + +- `POST /api/v1/chat/completions` — plan / enhance / assist +- `GET /api/v1/images/models` + `POST /api/v1/images` — cloud generation + +OpenRouter does **not** accept arbitrary Civitai LoRA files. For LoRAs, configure a diffusion worker and install via Civitai key + Freya UI or `FreyaModelAsset`. diff --git a/.gitlab-ci.yml b/legacy/.gitlab-ci.yml similarity index 100% rename from .gitlab-ci.yml rename to legacy/.gitlab-ci.yml diff --git a/Dockerfile.comfyui b/legacy/Dockerfile.comfyui similarity index 100% rename from Dockerfile.comfyui rename to legacy/Dockerfile.comfyui diff --git a/Dockerfile.swarmui b/legacy/Dockerfile.swarmui similarity index 100% rename from Dockerfile.swarmui rename to legacy/Dockerfile.swarmui diff --git a/legacy/Makefile b/legacy/Makefile new file mode 100644 index 0000000..fd62803 --- /dev/null +++ b/legacy/Makefile @@ -0,0 +1,217 @@ +.PHONY: help check-deps fix-docker-group build build-comfyui build-swarmui up down sui sui-rebuild swarmui-update cui llm llm-pull llm-import-hf llm-list llm-rm llm-logs swarmui-rebuild swarmui-extensions-check restart logs clean + +help: ## Show this help message + @echo 'Usage: make [target]' + @echo '' + @echo 'Available targets:' + @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf " %-15s %s\n", $$1, $$2}' $(MAKEFILE_LIST) + +check-deps: ## Check Docker, Docker Compose, Git; install Git on Linux if missing; warn on NVIDIA + chmod +x scripts/linux/check-deps.sh && ./scripts/linux/check-deps.sh + +fix-docker-group: ## Create docker group if missing, add current user (fixes permission denied) + chmod +x scripts/linux/add-docker-group.sh && ./scripts/linux/add-docker-group.sh + +setup: ## Run initial directory setup (runs check-deps first, then creates dirs) + chmod +x scripts/linux/setup.sh && ./scripts/linux/setup.sh + +quick-setup: ## Non-interactive setup: directories + ComfyUI starter models (SDXL + VAE) + chmod +x scripts/linux/quick-setup.sh && ./scripts/linux/quick-setup.sh + +download-starter-models: ## Download ComfyUI starter models (SDXL base + VAE, ~7.3 GB) + chmod +x scripts/linux/download-model.sh && ./scripts/linux/download-model.sh starter + +download-model: ## Download one ComfyUI model (make download-model TYPE=checkpoint URL=... [FILE=...]) + @if [ -z "$(TYPE)" ] || [ -z "$(URL)" ]; then \ + echo "Usage: make download-model TYPE= URL= [FILE=]"; \ + echo "Types: checkpoint, lora, vae, controlnet, upscale, embedding"; \ + echo "See docs/model-downloads.md for Hugging Face / Civitai (account + API key required)."; \ + exit 1; \ + fi + chmod +x scripts/linux/download-model.sh + ./scripts/linux/download-model.sh "$(TYPE)" "$(URL)" "$(FILE)" + +build: ## Build all Docker images + docker compose build + +build-comfyui: ## Build ComfyUI image only + docker compose build comfyui + +build-swarmui: ## Build SwarmUI image only + docker compose build swarmui + +build-no-cache: ## Build all images without cache + docker compose build --no-cache + +up: ## Start all services + docker compose up -d + +sui: ## SwarmUI + Ollama (stops ComfyUI first; updates SwarmUI; preserves running containers) + -docker compose stop comfyui 2>/dev/null || true + docker compose up -d swarmui ollama + @$(MAKE) swarmui-update + +swarmui-update: ## Pull latest SwarmUI, rebuild if needed, and restart (requires swarmui container) + @docker ps >/dev/null 2>&1 || (echo "Error: Docker not accessible. Run: make fix-docker-group, then newgrp docker" && exit 1) + @docker compose up -d swarmui 2>/dev/null || true + @i=0; while [ $$i -lt 90 ]; do \ + status=$$(docker compose ps swarmui --format '{{.Health}}' 2>/dev/null); \ + echo "$$status" | grep -q healthy && break; \ + docker compose ps swarmui --status running -q 2>/dev/null | grep -q . || { sleep 1; i=$$((i+1)); continue; }; \ + [ -z "$$status" ] && break; \ + i=$$((i+1)); sleep 1; \ + done + @docker compose ps swarmui --status running -q 2>/dev/null | grep -q . \ + || (echo "Error: SwarmUI not running. Start with: docker compose up -d swarmui" && exit 1) + @echo "Updating SwarmUI (git pull + dotnet build if needed)..." + @docker compose exec -T swarmui bash -c 'set -e; cd /app/SwarmUI; \ + prior=$$(git rev-parse HEAD); \ + for attempt in 1 2 3 4 5; do \ + if git fetch origin master && git reset --hard origin/master; then break; fi; \ + [ "$$attempt" -eq 5 ] && exit 1; \ + echo "Git fetch failed (attempt $$attempt), retrying..."; sleep 2; \ + done; \ + new=$$(git rev-parse HEAD); \ + rm -f src/bin/must_rebuild; \ + if [ "$$prior" != "$$new" ] || [ ! -f src/bin/live_release/SwarmUI.dll ]; then \ + echo "Building SwarmUI ($$prior -> $$new)..."; \ + dotnet build src/SwarmUI.csproj -c Release -o src/bin/live_release; \ + touch src/bin/.swarmui_restarted; \ + else \ + echo "SwarmUI source already up to date; skipping build."; \ + fi' + @if docker compose exec -T swarmui test -f /app/SwarmUI/src/bin/.swarmui_restarted 2>/dev/null; then \ + docker compose exec -T swarmui rm -f /app/SwarmUI/src/bin/.swarmui_restarted; \ + docker compose restart swarmui; \ + fi + +sui-rebuild: ## Restart SwarmUI + Ollama (SwarmUI builds extensions at startup; use after adding extension via UI) + @docker ps >/dev/null 2>&1 || (echo "Error: Docker not accessible. Run: make fix-docker-group, then newgrp docker" && exit 1) + docker compose down && docker compose up -d swarmui ollama + +cui: ## ComfyUI only (stops other compose services first) + docker compose down && docker compose up -d comfyui + +llm: ## Ollama only (for SwarmUI MagicPrompt / LLM API; stops other compose services first) + docker compose down && docker compose up -d ollama + +down: ## Stop all services + docker compose down + +restart: ## Restart all services + docker compose restart + +logs: ## Show logs from all services + docker compose logs -f + +logs-comfyui: ## Show logs from ComfyUI service + docker compose logs -f comfyui + +logs-swarmui: ## Show logs from SwarmUI service + docker compose logs -f swarmui + +llm-logs: ## Show logs from Ollama service + docker compose logs -f ollama + +clean: ## Remove containers, volumes, and images + docker compose down -v + +ps: ## Show running containers + docker compose ps + +shell-comfyui: ## Open shell in ComfyUI container + docker compose exec comfyui /bin/bash + +shell-swarmui: ## Open shell in SwarmUI container + docker compose exec swarmui /bin/bash + +swarmui-rebuild: ## [Debug] Force rebuild inside container without git pull. Prefer: make swarmui-update + @docker ps >/dev/null 2>&1 || (echo "Error: Docker not accessible. Run: make fix-docker-group, then newgrp docker" && exit 1) + @docker compose ps swarmui 2>/dev/null | grep -q Up || (echo "Error: SwarmUI not running. Start with: make sui" && exit 1) + docker compose exec swarmui bash -c "set -e; cd /app/SwarmUI && dotnet build src/SwarmUI.csproj -c Release -o src/bin/live_release" + docker compose restart swarmui + +swarmui-extensions-check: ## [Debug] List extensions dir and run build; use if extension not showing after restart + @docker ps >/dev/null 2>&1 || (echo "Error: Docker not accessible. Run: make fix-docker-group, then newgrp docker" && exit 1) + @docker compose ps swarmui 2>/dev/null | grep -q Up || (echo "Error: SwarmUI not running. Start with: make sui" && exit 1) + @echo "=== Extension dir (host: swarmui/extensions) ===" + @docker compose exec swarmui ls -la /app/SwarmUI/src/Extensions/ 2>/dev/null || true + @echo "=== Extension subdirs (.cs) ===" + @docker compose exec swarmui find /app/SwarmUI/src/Extensions -maxdepth 2 -type f -name "*.cs" 2>/dev/null || true + @echo "=== Manual build (SwarmUI usually builds at startup) ===" + docker compose exec swarmui bash -c "set -e; cd /app/SwarmUI && dotnet build src/SwarmUI.csproj -c Release -o src/bin/live_release -v minimal" + +llm-pull: ## Download Ollama model (usage: make llm-pull MODEL=dolphin3) + @if [ -z "$(MODEL)" ]; then \ + echo "Usage: make llm-pull MODEL="; \ + echo "Example: make llm-pull MODEL=dolphin3 (default for MagicPrompt: https://ollama.com/library/dolphin3)"; \ + echo "Browse available models: https://ollama.com/library"; \ + echo "Popular: dolphin3, llama3.2:1b, llama3.2:3b, mistral, gemma2:7b"; \ + exit 1; \ + fi + @echo "Pulling Ollama model: $(MODEL)" + @docker compose exec ollama ollama pull $(MODEL) || \ + docker compose run --rm ollama ollama pull $(MODEL) + +llm-import-hf: ## Import GGUF model from Hugging Face into Ollama (usage: make llm-import-hf REPO=user/repo [QUANT=Q4_K_M]) + @if [ -z "$(REPO)" ]; then \ + echo "Usage: make llm-import-hf REPO= [QUANT=]"; \ + echo "Example: make llm-import-hf REPO=bartowski/Llama-3.2-1B-Instruct-GGUF"; \ + echo "Example: make llm-import-hf REPO=bartowski/Llama-3.2-3B-Instruct-GGUF QUANT=IQ3_M"; \ + echo "Browse GGUF models: https://huggingface.co/models?library=gguf"; \ + echo "Ollama uses hf.co/REPO; default quant is Q4_K_M when present."; \ + echo ""; \ + echo "Note: Only GGUF repos work. Transformers/Safetensors models (e.g. dphn/dolphin-vision-72b)"; \ + echo "cannot be imported unless a GGUF version exists on Hugging Face."; \ + exit 1; \ + fi + @HF_MODEL="hf.co/$(REPO)"; \ + if [ -n "$(QUANT)" ]; then HF_MODEL="$$HF_MODEL:$(QUANT)"; fi; \ + echo "Importing from Hugging Face: $$HF_MODEL"; \ + docker compose exec ollama ollama pull "$$HF_MODEL" || \ + docker compose run --rm ollama ollama pull "$$HF_MODEL" + +llm-list: ## List installed Ollama models and show available models link + @echo "=== Available models ===" + @echo "Browse: https://ollama.com/library" + @echo "" + @echo "Default for MagicPrompt (control + compatibility): dolphin3 — https://ollama.com/library/dolphin3" + @echo "Other options: Light (1-3B) llama3.2:1b, phi3:mini | Balanced (7-8B) mistral, gemma2:7b" + @echo "" + @echo "=== Installed models ===" + @docker compose exec ollama ollama list 2>/dev/null || \ + docker compose run --rm ollama ollama list || \ + (echo "Ollama not running. Start with: make llm" && exit 1) + @echo "" + @echo "Pull a model: make llm-pull MODEL=" + @echo "Import from Hugging Face (GGUF): make llm-import-hf REPO=user/repo [QUANT=...]" + @echo "Remove a model: make llm-rm MODEL=" + +llm-rm: ## Remove an Ollama model (usage: make llm-rm MODEL=dolphin3) + @if [ -z "$(MODEL)" ]; then \ + echo "Usage: make llm-rm MODEL="; \ + echo "Example: make llm-rm MODEL=dolphin3"; \ + echo "List installed models: make llm-list"; \ + exit 1; \ + fi + @echo "Removing Ollama model: $(MODEL)" + @docker compose exec ollama ollama rm $(MODEL) || \ + docker compose run --rm ollama ollama rm $(MODEL) + +check-gpu: ## Run GPU diagnostic check + chmod +x scripts/linux/check-gpu.sh && ./scripts/linux/check-gpu.sh + +check-gpu-comfyui: ## Check GPU availability in ComfyUI container + docker compose exec comfyui python3 -c "import torch; print(f'CUDA available: {torch.cuda.is_available()}'); print(f'GPU count: {torch.cuda.device_count()}'); [torch.cuda.is_available()] and print(f'GPU name: {torch.cuda.get_device_name(0)}')" + +check-gpu-swarmui: ## Check GPU availability in SwarmUI container + docker compose exec swarmui nvidia-smi || echo "nvidia-smi not available, checking CUDA..." + @docker compose exec swarmui dotnet --version || echo "DotNET check failed" + +status: ## Show service status and URLs + @echo "=== Service Status ===" + @docker compose ps + @echo "\n=== Access URLs ===" + @echo "ComfyUI: http://localhost:8188" + @echo "SwarmUI: http://localhost:7801" + @echo "Ollama API: http://localhost:11434" diff --git a/legacy/README.compose.md b/legacy/README.compose.md new file mode 100644 index 0000000..2c0444f --- /dev/null +++ b/legacy/README.compose.md @@ -0,0 +1,133 @@ +# Freya - Stable Diffusion with UI on Kubernetes + +![Freya](freya.png) + +A Kubernetes-ready platform for running ComfyUI and SwarmUI Stable Diffusion interfaces with discrete GPU support. Both UIs are built from source using custom Docker images. + +## Features + +- 🎨 **ComfyUI**: Advanced node-based workflow interface for Stable Diffusion (built from source) +- 🐝 **SwarmUI**: Modular AI image and video generation web interface (built from source) +- 💬 **Ollama**: Local LLM API; use inside SwarmUI via the [MagicPrompt extension](https://github.com/HartsyAI/SwarmUI-MagicPromptExtension) for prompt generation and enhancement +- 🐳 **Docker Support**: Custom-built containers with GPU support for local development +- ☸️ **Kubernetes Ready**: Designed to run in Kubernetes clusters +- 🚀 **GPU Accelerated**: Full CUDA support for discrete GPUs +- 🔧 **Custom Builds**: All images built from source, not using public images + +## Quick Start + +### Prerequisites + +- **Platform**: Linux (primary) or Windows only (NVIDIA support; macOS not supported). See [Installation Guide](docs/installation.md). +- **Linux / WSL2**: Docker Engine 20.10+ and Docker Compose v2 — [check and install](docs/installation.md#checking-and-installing-docker) per your OS. +- **Windows**: From repo root run **PowerShell** `.\make.ps1` (same name as Linux `make`); or use WSL2 and `make`. Docker Desktop (WSL2 backend) recommended. +- **GPU**: NVIDIA GPU with 8GB+ VRAM (16GB+ recommended); NVIDIA Container Toolkit required on Linux. + +See [Installation Guide](docs/installation.md) for dependency check/install and [Windows / PowerShell](docs/installation.md#windows) setup. + +### Getting Started + +```bash +# Setup directories +make setup + +# Optional: Quick setup = dirs + ComfyUI starter models (SDXL + VAE); add more via make download-model +make quick-setup + +# Build images +make build + +# Start services +make up +``` + +### Access the Interfaces + +- **ComfyUI**: http://localhost:8188 +- **SwarmUI**: http://localhost:7801 +- **Ollama API**: http://localhost:11434 (use from SwarmUI via MagicPrompt extension) + +### Example: SwarmUI with a sample prompt and model + +![Freya UI](freya-ui.png) + +Try this in **SwarmUI** (http://localhost:7801) after downloading the model: + +**Model:** [SDXL Yamer's Anime Unstable Illustrator](https://civitai.com/models/76489/sdxl-yamers-anime-unstable-illustrator?modelVersionId=377674) (Civitai — checkpoint, ~6.46 GB SafeTensors). Place the file in `swarmui/data/Models/` or use SwarmUI’s built-in downloader. + +**Positive prompt:** +``` +45 megapixel, the ethereal beauty of a mystical landscape under the red moonlight, The scene should be illuminated by a large, radiant moon, casting its glow upon a twisted, yet majestic tree with blossoms that seem to sparkle in the night, The tree's roots should be deeply embedded into rocky terrain, symbolizing its ancient existence, In the background, towering mountains loom, their peaks veiled in mist, A serene lake at the foot of the mountains reflects the moon's luminescence, Incorporate elements that evoke a sense of magic and mystery +``` + +**Negative prompt:** +``` +bad quality, bad anatomy, worst quality, low quality, low resolution, extra fingers, blur, blurry, ugly, wrong proportions, watermark, image artifacts, lowres, ugly, jpeg artifacts, deformed, noisy image +``` + +**Suggested settings (from model page):** Resolution 1024×1024 (or 576×1024, 768×1024), Steps 20–50, CFG 5–20. + +## Makefile Commands + +On **Linux** or **WSL2** run `make` from the repo root. On **Windows** run `.\make.ps1` from the repo root (e.g. `.\make.ps1 help`, `.\make.ps1 up`). See [Installation Guide](docs/installation.md#windows). + +```bash +make help # Show all available commands +make build # Build all Docker images +make up # Start all services +make down # Stop all services +make sui # SwarmUI + Ollama (stops others first; updates SwarmUI) +make cui # ComfyUI only (stops others first) +make llm # Ollama only (stops others first) +make swarmui-update # Pull latest SwarmUI, rebuild, and restart +make swarmui-rebuild # Rebuild SwarmUI from current source (no git pull) +make logs # View logs from all services +make restart # Restart services +make status # Show service status and URLs +make check-gpu-comfyui # Verify GPU access in ComfyUI +make check-gpu-swarmui # Verify GPU access in SwarmUI +make llm-pull MODEL=dolphin3 # Pull default Ollama model (MagicPrompt); see https://ollama.com/library/dolphin3 +make llm-list # List installed models + browse link +make llm-rm MODEL=dolphin3 # Remove an Ollama model +make llm-logs # View Ollama logs +``` + +See [Architecture Guide](docs/architecture.md) for complete command reference. + +## Documentation + +- [Installation Guide](docs/installation.md) - System requirements and setup +- [GPU Compatibility](docs/gpu-compatibility.md) - Compatible GPU cards +- [Kubernetes Deployment](docs/kubernetes.md) - Deploy to Kubernetes +- [Model Management](docs/MODELS.md) - Download and manage models +- [SwarmUI Video Guide](docs/swarmui-video-guide.md) - Beginner’s guide to T2V/I2V with SwarmUI (links to [HF guide](https://huggingface.co/blog/MonsterMMORPG/beginners-guide-generate-videos-with-swarmui)) +- [Architecture](docs/architecture.md) - Project structure and services +- [SwarmUI MagicPrompt](docs/swarmui-magicprompt.md) - Use Ollama inside SwarmUI for prompt generation (MagicPrompt extension) +- [MagicPrompt Default Prompts](docs/magicprompt-default-prompts.md) - Optimized Freya system prompts for Ollama/dolphin3 +- [MagicPrompt Custom Instructions](docs/magicprompt-custom-instructions.md) - Create custom instructions for specific styles and workflows +- [Troubleshooting](docs/troubleshooting.md) - Common issues and solutions + +## Requirements + +- **OS**: Linux (Ubuntu, Debian, Fedora, RHEL, openSUSE, Arch) or Windows via WSL2 — see [installation](docs/installation.md) +- **GPU**: NVIDIA GPU with CUDA 12.4+ or 13.x (images use 13.1.1) +- **VRAM**: Minimum 8GB (16GB+ recommended for both services) +- **RAM**: Minimum 16GB system RAM +- **Storage**: Minimum 50GB free space + +See [Installation Guide](docs/installation.md) for detailed requirements. + +## Notes + +- Models are downloaded on first use and cached in mounted volumes +- Generated images are saved to respective `output/` directories +- First build may take 15-30 minutes +- Both services can run simultaneously with 16GB+ GPU memory + +## Acknowledgments + +This project was built with [Cursor](https://cursor.sh) using the Composer model. + +## License + +MIT diff --git a/legacy/README.md b/legacy/README.md new file mode 100644 index 0000000..3adc60c --- /dev/null +++ b/legacy/README.md @@ -0,0 +1,14 @@ +# Legacy Freya (Compose / ComfyUI / SwarmUI / Ollama) + +This directory holds the previous Freya stack: custom Docker images, Kubernetes YAML, and Makefile targets for ComfyUI, SwarmUI, and Ollama. + +The **current** Freya product lives at the repository root: Rust operator + Freya API/UI over OpenRouter, with optional remote/in-cluster diffusion workers and Civitai LoRA install. + +See root [README.md](../README.md) and [docs/CONCEPTS.md](../docs/CONCEPTS.md). + +To run the legacy stack from this folder: + +```bash +cd legacy +# follow README.compose.md / Makefile help +``` diff --git a/docker-compose.yml b/legacy/docker-compose.yml similarity index 100% rename from docker-compose.yml rename to legacy/docker-compose.yml diff --git a/docs/MODELS.md b/legacy/docs/MODELS.md similarity index 100% rename from docs/MODELS.md rename to legacy/docs/MODELS.md diff --git a/docs/architecture.md b/legacy/docs/architecture.md similarity index 100% rename from docs/architecture.md rename to legacy/docs/architecture.md diff --git a/docs/gitlab-ci.md b/legacy/docs/gitlab-ci.md similarity index 100% rename from docs/gitlab-ci.md rename to legacy/docs/gitlab-ci.md diff --git a/docs/gpu-compatibility.md b/legacy/docs/gpu-compatibility.md similarity index 100% rename from docs/gpu-compatibility.md rename to legacy/docs/gpu-compatibility.md diff --git a/docs/installation.md b/legacy/docs/installation.md similarity index 100% rename from docs/installation.md rename to legacy/docs/installation.md diff --git a/docs/kubernetes.md b/legacy/docs/kubernetes.md similarity index 100% rename from docs/kubernetes.md rename to legacy/docs/kubernetes.md diff --git a/docs/magicprompt-custom-instructions.md b/legacy/docs/magicprompt-custom-instructions.md similarity index 100% rename from docs/magicprompt-custom-instructions.md rename to legacy/docs/magicprompt-custom-instructions.md diff --git a/docs/magicprompt-default-prompts.md b/legacy/docs/magicprompt-default-prompts.md similarity index 100% rename from docs/magicprompt-default-prompts.md rename to legacy/docs/magicprompt-default-prompts.md diff --git a/docs/model-downloads.md b/legacy/docs/model-downloads.md similarity index 100% rename from docs/model-downloads.md rename to legacy/docs/model-downloads.md diff --git a/docs/swarmui-magicprompt.md b/legacy/docs/swarmui-magicprompt.md similarity index 100% rename from docs/swarmui-magicprompt.md rename to legacy/docs/swarmui-magicprompt.md diff --git a/docs/swarmui-video-guide.md b/legacy/docs/swarmui-video-guide.md similarity index 100% rename from docs/swarmui-video-guide.md rename to legacy/docs/swarmui-video-guide.md diff --git a/docs/troubleshooting.md b/legacy/docs/troubleshooting.md similarity index 100% rename from docs/troubleshooting.md rename to legacy/docs/troubleshooting.md diff --git a/k8s/comfyui/deployment.yaml b/legacy/k8s/comfyui/deployment.yaml similarity index 100% rename from k8s/comfyui/deployment.yaml rename to legacy/k8s/comfyui/deployment.yaml diff --git a/k8s/deploy-to-prd-apps.sh b/legacy/k8s/deploy-to-prd-apps.sh similarity index 100% rename from k8s/deploy-to-prd-apps.sh rename to legacy/k8s/deploy-to-prd-apps.sh diff --git a/k8s/ingress.yaml b/legacy/k8s/ingress.yaml similarity index 100% rename from k8s/ingress.yaml rename to legacy/k8s/ingress.yaml diff --git a/k8s/ollama/deployment.yaml b/legacy/k8s/ollama/deployment.yaml similarity index 100% rename from k8s/ollama/deployment.yaml rename to legacy/k8s/ollama/deployment.yaml diff --git a/k8s/swarmui/deployment.yaml b/legacy/k8s/swarmui/deployment.yaml similarity index 100% rename from k8s/swarmui/deployment.yaml rename to legacy/k8s/swarmui/deployment.yaml diff --git a/make.ps1 b/legacy/make.ps1 similarity index 100% rename from make.ps1 rename to legacy/make.ps1 diff --git a/scripts/linux/add-docker-group.sh b/legacy/scripts/linux/add-docker-group.sh similarity index 100% rename from scripts/linux/add-docker-group.sh rename to legacy/scripts/linux/add-docker-group.sh diff --git a/scripts/linux/check-deps.sh b/legacy/scripts/linux/check-deps.sh similarity index 100% rename from scripts/linux/check-deps.sh rename to legacy/scripts/linux/check-deps.sh diff --git a/scripts/linux/check-gpu.sh b/legacy/scripts/linux/check-gpu.sh similarity index 100% rename from scripts/linux/check-gpu.sh rename to legacy/scripts/linux/check-gpu.sh diff --git a/scripts/linux/download-model.sh b/legacy/scripts/linux/download-model.sh similarity index 100% rename from scripts/linux/download-model.sh rename to legacy/scripts/linux/download-model.sh diff --git a/scripts/linux/install-nvidia-toolkit.sh b/legacy/scripts/linux/install-nvidia-toolkit.sh similarity index 100% rename from scripts/linux/install-nvidia-toolkit.sh rename to legacy/scripts/linux/install-nvidia-toolkit.sh diff --git a/scripts/linux/quick-setup.sh b/legacy/scripts/linux/quick-setup.sh similarity index 100% rename from scripts/linux/quick-setup.sh rename to legacy/scripts/linux/quick-setup.sh diff --git a/scripts/linux/setup.sh b/legacy/scripts/linux/setup.sh similarity index 100% rename from scripts/linux/setup.sh rename to legacy/scripts/linux/setup.sh diff --git a/scripts/windows/check-deps.ps1 b/legacy/scripts/windows/check-deps.ps1 similarity index 100% rename from scripts/windows/check-deps.ps1 rename to legacy/scripts/windows/check-deps.ps1 diff --git a/scripts/windows/freya.ps1 b/legacy/scripts/windows/freya.ps1 similarity index 100% rename from scripts/windows/freya.ps1 rename to legacy/scripts/windows/freya.ps1 diff --git a/packs/instructions/chat.txt b/packs/instructions/chat.txt new file mode 100644 index 0000000..991210b --- /dev/null +++ b/packs/instructions/chat.txt @@ -0,0 +1 @@ +You are Freya, a friendly image studio guide. Users describe scenes in everyday language — you handle model briefs, LoRA discovery, and planning. Never teach them comma-separated tags or Civitai trigger syntax unless a selected LoRA literally requires one trigger word (then mention only that word). Help them iterate: suggest what to try next, not how to "prompt engineer." Be warm and clear. diff --git a/packs/instructions/plan.txt b/packs/instructions/plan.txt new file mode 100644 index 0000000..768ff0c --- /dev/null +++ b/packs/instructions/plan.txt @@ -0,0 +1,4 @@ +You are Freya's planner. Given user intent and optional session context (prior prompts, pinned LoRAs), reply with JSON only (no markdown): +{"backend":"openrouter"|"local","model":"...","styleId":null|"...","enhanceMode":"prompt-prose"|"prompt-sd","civitaiQuery":null|"short search","rationale":"short"} + +Prefer openrouter + prompt-prose (natural language). Use local + prompt-sd only when the user clearly needs a pinned LoRA/checkpoint on a diffusion worker. If a LoRA search would help the look, set civitaiQuery to a short phrase; otherwise null. diff --git a/packs/instructions/prompt-prose.txt b/packs/instructions/prompt-prose.txt new file mode 100644 index 0000000..8fe711a --- /dev/null +++ b/packs/instructions/prompt-prose.txt @@ -0,0 +1 @@ +You are Freya. The user wrote a natural-language description. Expand it into a rich image brief for modern models (Flux, GPT Image, Gemini): one continuous paragraph of vivid prose covering subject, setting, lighting, mood, and style. Keep their intent. Do NOT output comma-separated Stable Diffusion keyword lists. Output ONLY the prose brief — no preamble or labels. diff --git a/packs/instructions/prompt-sd.txt b/packs/instructions/prompt-sd.txt new file mode 100644 index 0000000..fb0b72d --- /dev/null +++ b/packs/instructions/prompt-sd.txt @@ -0,0 +1 @@ +You are Freya. Output ONLY an optimized positive prompt for Stable Diffusion image generation. One continuous comma-separated keyword list. CRITICAL: Each keyword MUST be 3 words or fewer—split longer phrases into separate keywords. Trigger words excepted. No duplicate keywords, no sections, no line breaks, no labels. Keep trigger words intact: names, LoRA triggers, and keywords with underscores must appear exactly as the user provided. No negative prompt. No preamble or explanation. diff --git a/packs/instructions/session.txt b/packs/instructions/session.txt new file mode 100644 index 0000000..a3a60c7 --- /dev/null +++ b/packs/instructions/session.txt @@ -0,0 +1,19 @@ +You are Freya running an agentic image-generation session — the image equivalent of agentic coding. + +The user states a goal in plain language. You plan a short loop: discover helpful LoRAs on Civitai if useful, generate a small set of natural-language variations, and leave room to iterate from what comes back. The user should never need prompt-engineering knowledge. + +Reply with JSON only (no markdown fences): +{ + "goal": "one-line restatement of what they want", + "steps": [ + {"kind": "search_loras|generate|iterate", "prompt": "natural language if generating", "note": "why this step"} + ], + "civitaiQuery": "2–6 word Civitai search, or empty string if cloud-only is fine", + "batchPrompts": ["variation one in prose", "variation two", "variation three"], + "sessionNote": "friendly sentence on how this set moves the session forward" +} + +Rules: +- batchPrompts: 2–4 everyday descriptions that explore the goal (mood, framing, time of day) — never comma-tag recipes +- Prefer exploring with a set over one perfect prompt +- Keep steps short (2–4). This is a plan the UI can follow, not a lecture diff --git a/packs/instructions/suggest.txt b/packs/instructions/suggest.txt new file mode 100644 index 0000000..be6b235 --- /dev/null +++ b/packs/instructions/suggest.txt @@ -0,0 +1,19 @@ +You are Freya. The user describes what they want in everyday language. They should never need SD tags, trigger syntax, or Civitai jargon. + +Reply with JSON only (no markdown fences): +{ + "ideas": ["...", "...", "..."], + "civitaiQuery": "short search phrase for matching LoRAs/styles on Civitai", + "sessionNote": "one friendly sentence on what to try next in this session" +} + +Rules for "ideas": +- 2–4 alternatives the user can try next, each a short natural-language scene description +- Build on what they already wrote; vary mood, time of day, framing, or subject focus +- Never use comma-separated keyword lists or "masterpiece, best quality" style tags + +Rules for "civitaiQuery": +- 2–6 words a Civitai search would understand (style, subject, medium) — not a full prompt +- Prefer terms that find LoRAs/checkpoints matching their vibe + +"sessionNote" is optional coaching toward iterating until the look is right. No preamble outside the JSON. diff --git a/packs/styles/ethereal-moon.yaml b/packs/styles/ethereal-moon.yaml new file mode 100644 index 0000000..4f083e5 --- /dev/null +++ b/packs/styles/ethereal-moon.yaml @@ -0,0 +1,9 @@ +id: ethereal-moon +displayName: Ethereal Moon Landscape +tags: [landscape, fantasy, moon] +examplePrompt: > + ethereal mystical landscape under a radiant red moon, twisted blossoming tree + on rocky terrain, misty mountains, serene lake reflecting moonlight, magical atmosphere +backend: openrouter +openRouterModel: black-forest-labs/flux.2-klein-4b +recommendedSize: "1024x1024" diff --git a/packs/styles/local-lora-example.yaml b/packs/styles/local-lora-example.yaml new file mode 100644 index 0000000..aed16d9 --- /dev/null +++ b/packs/styles/local-lora-example.yaml @@ -0,0 +1,11 @@ +id: local-character-lora +displayName: Local Character LoRA (worker) +tags: [lora, local, character] +examplePrompt: character portrait, soft studio light, detailed face +backend: local +localCheckpoint: stabilityai/stable-diffusion-xl-base-1.0 +loras: + - name: my_character + scale: 0.8 +triggerWords: my_character +recommendedSize: "1024x1024" diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..73cb934 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "stable" +components = ["rustfmt", "clippy"] diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..44ffe03 --- /dev/null +++ b/web/index.html @@ -0,0 +1,42 @@ + + + + + + + + Freya — agentic image studio + + + + + + + + + + + + + + +
+ + + diff --git a/web/nginx.conf b/web/nginx.conf new file mode 100644 index 0000000..4e11d68 --- /dev/null +++ b/web/nginx.conf @@ -0,0 +1,24 @@ +server { + listen 80; + server_name _; + root /usr/share/nginx/html; + index index.html; + + # FREYA_API_UPSTREAM defaults to http://freya-api:8080; operator sets + # http://{studio}-api:8080 via envsubst on the official nginx image templates dir. + location /v1/ { + proxy_pass ${FREYA_API_UPSTREAM}/v1/; + proxy_http_version 1.1; + proxy_set_header Host $host; + # Injected when FreyaStudio apiTokenSecretRef is set (empty = open local/dev). + proxy_set_header Authorization "Bearer ${FREYA_API_TOKEN}"; + } + + location /healthz { + proxy_pass ${FREYA_API_UPSTREAM}/healthz; + } + + location / { + try_files $uri /index.html; + } +} diff --git a/web/package-lock.json b/web/package-lock.json new file mode 100644 index 0000000..ee1c6e3 --- /dev/null +++ b/web/package-lock.json @@ -0,0 +1,1794 @@ +{ + "name": "freya-web", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "freya-web", + "version": "0.1.0", + "dependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@vitejs/plugin-react": "^4.3.4", + "vite": "^6.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz", + "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.15.tgz", + "integrity": "sha512-gNWJUX0FlevflramOkaInywOMhU1lkln38gAC7TFZv2tsWbLYbN/2WZFGcq8zbX0Z55e4vGa27IB/NaeZoauWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.15", + "@babel/types": "^7.29.15", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.14.tgz", + "integrity": "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.15.tgz", + "integrity": "sha512-C2FuapQ2Kh1OnVHAoLi5rD3GBJ8COb9Q609T6HEpLqaBAo560PDP5OxBE5dCI/h951MBO/+bCUYU5SZ+8ZlV+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.15.tgz", + "integrity": "sha512-l+ezV2czw3t2d2ELq+3CwPL4WLKK5O8IywBXb9/gpmbCOVZFmRYJPmHVqSCv2k+8iKbE30Zf54siOoIZ52XOxA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.15.tgz", + "integrity": "sha512-RpKWyisHoP81twtSCgmE02iU0RnPcq1DN5bBEbpUePrjA9Q3wXhufnCJrrayPpoZieqFh3zyZQqwtSK0gGccRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.15" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.15.tgz", + "integrity": "sha512-ZfawBo2i8vvt+BTt37dWDKBPjUfm/H+bw+ltwsCRhW7gPtyNVwUXuNo54eO2Xo+P4VXpalPFfFISbBTRKC8SOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.15", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.15", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.15", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.15.tgz", + "integrity": "sha512-/XKpKDakL//LZ66bq1XsZOswuqeI5MZqPLDu18o3XdkU1fNJ7bdPtzgnc4ZNS+bBGHV0FJG8jjb8SwcC3nNVQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.15", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.7.tgz", + "integrity": "sha512-ZL7MgOeMUiBum1bjzzyBotE3DuHVz+UUxcDVlLL7gpdhDM4RpjG4bZOIly7ensIcXw9jhWl7HTIIQ9KsgjykGQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.7.tgz", + "integrity": "sha512-cKZ2Hz/xt5DLY/vdUmMXEn3gnjLgwdeB/npHagbdTljLvBE6b/xKcPCcRWTiT0pHeVf8akl5Cb9K7ylRxbtHng==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.7.tgz", + "integrity": "sha512-P9vs1uCC2drepKKuiXrhY+r7ry/jtDCrBS8SUCYm2Rr7rVTR9eFH6XVAmD9TdfYFlDgRe5r1eH8tLQVuz+l/VA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.7.tgz", + "integrity": "sha512-Lgu2AV7jbOTNNhkQ/OurNm7Snqu1Ux/3y7k8q47fbpPa3q63aIzKKp1xFzax5KH4pcdUzbnX/riuFsxKflsF+g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.7.tgz", + "integrity": "sha512-wKo6rOzla+/3rN8QBqTgcrsQMfyqwa3y14TvCTotLLib/ACWTxX1zWDTYze90s2RWtYiSfTlavHLmZv0Jsafrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.7.tgz", + "integrity": "sha512-vAeCwbFyEu/vBt9O/uHCHJSvwtOpTSssnM/PoZgn8rmvAkS+9ixaUfJZ2IP3ltom+rvpuQQEIEqltPY7qhC9lQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.7.tgz", + "integrity": "sha512-HvjSxOKI+6Si4ytmaoCEpjwDMrH/1s0uWeTAhdE5oXY8/RMI92hCePI/psZuJtY5EHWoT7MfyvTz0HBDZb1ZwQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.7.tgz", + "integrity": "sha512-nz/Eu1sag3w5gPiKLJhAbKa4D9hUUJpDc9XzKXxGNHZqwgT2AbuVS2e4k9CIoLQp5dPhSN9ntiEVuz2jTzu1Gg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.7.tgz", + "integrity": "sha512-05CEv2G/kI261A1WQBZL8gx6xXULjPfVnTKAkfnV/0uqHeLo+dNEOeUzMaiK/HDGR0Z1Nn7KJjm/34bNbNcfTA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.7.tgz", + "integrity": "sha512-wrqk3EkxQt98lTdiYhjcaWmFHwvKiSgHFi7XmPTSF4X8+uGUTBOAc0CaynEvpUhBgkPRbwASrYoU/5uJPF+LFA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.7.tgz", + "integrity": "sha512-DnuEUWvzeSxHxzu5lvrN+I/UzrcQkR/fQ4Bibetdp73Rf7aP0XgFpalSDuHmVWsCLETE+Lrl3GVOqIvFP7rcjw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.7.tgz", + "integrity": "sha512-n0sr2s+rzVw8ntRucOxGhWeJ9lEl9KxCRzF3RmnZLE/tRnfKiloLuK8UqWrKFqVigEAh0IkRkPz5LVaV9/ZfvA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.7.tgz", + "integrity": "sha512-qDVJyMCbh7ekjt1kM9CZsyCFZvv5UW1QTIx3YfJ/gh8LkqpoPNpl9dCeYeOa+bsDOGTWZiMG2riXuoFSRISimQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.7.tgz", + "integrity": "sha512-GiIOHHIzgpMoR5DT1pA1b9qMk5i0Ngg2FRj4D6XFSBC8e/axHuIdB7K/OBozO2RtCVAMnH1rXcuJrGScg+bvzA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.7.tgz", + "integrity": "sha512-B132V2fwDl7UGLhvK6s3Ay7eNQ4dmDSDgsBm/Wwbz+Wgnunz0le4R2wzDp6TL5ExMu3MC1auJIrVtk2gOyxbyw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.7.tgz", + "integrity": "sha512-3NueHQilbssjxgJMx9hXBV+U5keb3CBzmW5WhoBG3iSLFcmz9U2FVoG4MUYpZoZ+KSNMQPN2AA79dTxlEF0VxQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.7.tgz", + "integrity": "sha512-8XRwbf76oAF1zZzg6OT8EY3swvCptZnLmiqMgO5+STyhTZ9s7rXa+tY8jESZW9IDyKACcVBGqa/RACDaLzRVjQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.7.tgz", + "integrity": "sha512-pvqqfjNdxVLvmovH681K5cPIL9DXj5n1RROaa0vb9JrtHddiScLrkHPRKj5flTKHF1M7xvRy0SS2yTRIc2TO0Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.7.tgz", + "integrity": "sha512-rsTjTf5HAm6F4sI6uUfJf2pc+7AWBKxgc2RveGvwB2OvVa1GezSSCDD1rtXPuFhcg3itPv7iHgcZsq/RwWvJ4Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.7.tgz", + "integrity": "sha512-VNLvsYMD5+zLCi5SohwDdL8PpicC9PnArLwyMJXXUcAduzrM3k9aZT9XiHw+mn5dOWr3UEyfyqJbOvxwJ2fCWQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.7.tgz", + "integrity": "sha512-7aOjdahkwiECWWOmjAemPd21yeQ18TW59DUiLWttzolMe5tDwHyBhlOfmxRUHOQnepTNkZ2Qwp1T6LxFZ5v7yQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.7.tgz", + "integrity": "sha512-BnNkTwE4FMCAoz3UYiJ6D6Y3pGozYIYZ2W+onH64uhiTI2iwD3KOaNSlkuHYfupZVemls3YTlvbPnuKwHsraiQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.7.tgz", + "integrity": "sha512-OH8tGWsJcRW6Vn0dmndyWJGdQa46bH2/2/PVfleBGUWuBd5/HVkIvw2UslgBwUZdtV78bJaoCNBmYI5+bcTJ4A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.7.tgz", + "integrity": "sha512-SpYx5X9+2JOF3hXe1cRaiFn562h4AMJhfgxkyHyiuh9dJ7PanPm7FTp8GJReSbS9N+TfjRiBbKacVk1g35kKxg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.7.tgz", + "integrity": "sha512-0ncKtQ55fqElV9Sk4cZ/4tiXVGlWxaH5PvDOlx1Sx8GuHIpSWgYrTcyrO51JnVFfy7LvAJiffkEg63ZHKwTMag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.7.tgz", + "integrity": "sha512-XY9DYHO5UxxVR8G6AErXDlccQmDpvGTLgKHFpvkgsyjwG/PrQuInRjQQfpEzBRuT+bhBtwfS8yDe9sPhVcq/9A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.39", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.39.tgz", + "integrity": "sha512-Q9buOYhr2ggrEZpImICecZTJHCCd8yXkRUokFlUEQ8uiD6oP82F4W4jWnhOHZYV+wlvrC51V7Wy0ULyWjil5Wg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.6", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz", + "integrity": "sha512-CmVVIQ3RVc5HxYEc9X84GvxK/C8C1wH8TlKAiO7uTxF8PDwt7r8t9Qk3J9NkMOVzX5O/HbLv3yzxZg9HPrnI9w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.37", + "caniuse-lite": "^1.0.30001826", + "electron-to-chromium": "^1.5.486", + "node-releases": "^2.0.64", + "update-browserslist-db": "^1.4.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001826", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001826.tgz", + "integrity": "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.492", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.492.tgz", + "integrity": "sha512-4uMs7omhajKiud0GqALLTazS/zyvHLTLmDWVTR+e6BnyJo5bSNrph/JoRWEFJJmY75ct9hCiSGsbFF9fLe5gDw==", + "dev": true, + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.65", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.65.tgz", + "integrity": "sha512-PfvofsGQ+MiOQIPkX9fU8ELUWmy5zL74CdQaph/ismKszfFkfwXaw0cGiwbwym2hT9k5+mdyl8O5WQ1MD8EHmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.68.7", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.7.tgz", + "integrity": "sha512-CxhzUIc+ocxPAWxHuff+PAluoW1otD6dHqqPK2h2Q38WA1VYk+3gizX6NEg5t2a8yNGQaiHM1R7V+qdwWuvp5Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.7", + "@rollup/rollup-android-arm64": "4.68.7", + "@rollup/rollup-android-x64": "4.68.7", + "@rollup/rollup-darwin-arm64": "4.68.7", + "@rollup/rollup-darwin-x64": "4.68.7", + "@rollup/rollup-freebsd-arm64": "4.68.7", + "@rollup/rollup-freebsd-x64": "4.68.7", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.7", + "@rollup/rollup-linux-arm-musleabihf": "4.68.7", + "@rollup/rollup-linux-arm64-gnu": "4.68.7", + "@rollup/rollup-linux-arm64-musl": "4.68.7", + "@rollup/rollup-linux-loong64-gnu": "4.68.7", + "@rollup/rollup-linux-loong64-musl": "4.68.7", + "@rollup/rollup-linux-ppc64-gnu": "4.68.7", + "@rollup/rollup-linux-ppc64-musl": "4.68.7", + "@rollup/rollup-linux-riscv64-gnu": "4.68.7", + "@rollup/rollup-linux-riscv64-musl": "4.68.7", + "@rollup/rollup-linux-s390x-gnu": "4.68.7", + "@rollup/rollup-linux-x64-gnu": "4.68.7", + "@rollup/rollup-linux-x64-musl": "4.68.7", + "@rollup/rollup-openbsd-x64": "4.68.7", + "@rollup/rollup-openharmony-arm64": "4.68.7", + "@rollup/rollup-win32-arm64-msvc": "4.68.7", + "@rollup/rollup-win32-ia32-msvc": "4.68.7", + "@rollup/rollup-win32-x64-gnu": "4.68.7", + "@rollup/rollup-win32-x64-msvc": "4.68.7", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/source-map-js": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", + "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.4.0.tgz", + "integrity": "sha512-WPJuOnjI9FWDct4fB+ej4Mz8opLaw5CDcZ2t44tFZ0vIQVYWzBhWR3mkixuUj/A7+vY4V9+ApOZ2YYLwdgq46w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "6.4.6", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.6.tgz", + "integrity": "sha512-RtsraAwEG68idOA6iUOoIpOlcSKROnf815aIq9qHTSrDNpLoBrBa12suyfcEd8qn0xwOVQI1Yhm1GbmTjF600A==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + } + } +} diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..6e9eedf --- /dev/null +++ b/web/package.json @@ -0,0 +1,20 @@ +{ + "name": "freya-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "dev:mock": "VITE_FREYA_MOCK=true vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@vitejs/plugin-react": "^4.3.4", + "vite": "^6.0.0" + } +} diff --git a/web/public/apple-touch-icon.png b/web/public/apple-touch-icon.png new file mode 100644 index 0000000..70d623c Binary files /dev/null and b/web/public/apple-touch-icon.png differ diff --git a/web/public/favicon-16.png b/web/public/favicon-16.png new file mode 100644 index 0000000..e46a496 Binary files /dev/null and b/web/public/favicon-16.png differ diff --git a/web/public/favicon-32.png b/web/public/favicon-32.png new file mode 100644 index 0000000..cfbda97 Binary files /dev/null and b/web/public/favicon-32.png differ diff --git a/web/public/favicon-64.png b/web/public/favicon-64.png new file mode 100644 index 0000000..d79c6a2 Binary files /dev/null and b/web/public/favicon-64.png differ diff --git a/web/public/favicon.ico b/web/public/favicon.ico new file mode 100644 index 0000000..5f0e603 Binary files /dev/null and b/web/public/favicon.ico differ diff --git a/web/public/favicon.png b/web/public/favicon.png new file mode 100644 index 0000000..d79c6a2 Binary files /dev/null and b/web/public/favicon.png differ diff --git a/web/public/favicon.svg b/web/public/favicon.svg new file mode 100644 index 0000000..b02d719 --- /dev/null +++ b/web/public/favicon.svg @@ -0,0 +1,9 @@ + + Freya — portrait + + + + + + diff --git a/web/public/icon-192.png b/web/public/icon-192.png new file mode 100644 index 0000000..e81a2d2 Binary files /dev/null and b/web/public/icon-192.png differ diff --git a/web/public/icon-512.png b/web/public/icon-512.png new file mode 100644 index 0000000..e52b832 Binary files /dev/null and b/web/public/icon-512.png differ diff --git a/web/public/icon-portrait.png b/web/public/icon-portrait.png new file mode 100644 index 0000000..cf9a77d Binary files /dev/null and b/web/public/icon-portrait.png differ diff --git a/web/public/icon.png b/web/public/icon.png new file mode 100644 index 0000000..e52b832 Binary files /dev/null and b/web/public/icon.png differ diff --git a/web/public/icon.svg b/web/public/icon.svg new file mode 100644 index 0000000..1c3f482 --- /dev/null +++ b/web/public/icon.svg @@ -0,0 +1,10 @@ + + Freya — portrait + + + + + + diff --git a/web/public/manifest.webmanifest b/web/public/manifest.webmanifest new file mode 100644 index 0000000..17fdfa3 --- /dev/null +++ b/web/public/manifest.webmanifest @@ -0,0 +1,14 @@ +{ + "name": "Freya — agentic image studio", + "short_name": "Freya", + "description": "Freya is an agentic image studio.", + "start_url": "/", + "display": "standalone", + "background_color": "#0e1418", + "theme_color": "#0e1418", + "icons": [ + { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" }, + { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" }, + { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" } + ] +} diff --git a/web/src/App.jsx b/web/src/App.jsx new file mode 100644 index 0000000..120e9ba --- /dev/null +++ b/web/src/App.jsx @@ -0,0 +1,2058 @@ +import { useEffect, useRef, useState } from "react"; +import { api, isMockMode } from "./api.js"; +import HeroCanvas from "./HeroCanvas.jsx"; +import { + BEGINNER_CIVITAI_QUERY, + BEGINNER_EXAMPLE, + demoCivitaiQuery, +} from "./mockApi.js"; + +const AUTOMATION_MODES = ["plan", "auto", "yolo"]; +const AUTOMATION_LABELS = { plan: "Plan", auto: "Auto", yolo: "YOLO" }; +const AUTOMATION_STORAGE_KEY = "freya.automationMode"; +const MODELS_STORAGE_KEY = "freya.models"; +const SESSIONS_STORAGE_KEY = "freya.sessions"; +const SIDEBAR_STORAGE_KEY = "freya.sidebarOpen"; +const THEME_STORAGE_KEY = "freya.theme"; + +function readStoredTheme() { + try { + const v = localStorage.getItem(THEME_STORAGE_KEY); + if (v === "light" || v === "dark") return v; + } catch { + /* ignore */ + } + return null; +} + +function systemTheme() { + try { + return window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark"; + } catch { + return "dark"; + } +} + +/** Saved `freya.theme` wins; otherwise follow `prefers-color-scheme`. */ +function resolveInitialTheme() { + const fromDom = document.documentElement.dataset.theme; + if (fromDom === "light" || fromDom === "dark") return fromDom; + return readStoredTheme() || systemTheme(); +} + +const MODE_HINTS = { + plan: "Plan only — steps, Civitai query, LoRAs, batch prompts. No generate or install.", + auto: "Run & ask when unsure — pauses on ambiguous LoRAs. Installs only if a worker is set; otherwise generates via OpenRouter.", + yolo: "Full auto — search, install only when a worker is set, otherwise generate via OpenRouter. No questions.", +}; + +const AGENT_MODELS = [ + { id: "openrouter/auto", label: "Auto", short: "Auto" }, + { id: "anthropic/claude-sonnet-4", label: "Claude Sonnet 4", short: "Sonnet 4" }, + { id: "openai/gpt-4.1-mini", label: "GPT-4.1 Mini", short: "GPT-4.1 Mini" }, + { id: "google/gemini-2.5-flash", label: "Gemini 2.5 Flash", short: "Gemini Flash" }, +]; + +const IMAGE_MODELS = [ + { id: "auto", label: "Auto", short: "Auto" }, + { id: "black-forest-labs/flux.2-klein-4b", label: "FLUX.2 Klein 4B", short: "FLUX Klein" }, + { id: "black-forest-labs/flux.1-schnell", label: "FLUX.1 Schnell", short: "FLUX Schnell" }, + { id: "stabilityai/sdxl-turbo", label: "SDXL Turbo", short: "SDXL Turbo" }, +]; + +const emptySession = () => ({ + goal: "", + pinnedLoras: [], + turns: [], + sessionNote: "", +}); + +function makeSessionId() { + return `s_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 7)}`; +} + +function sessionTitleFrom(prompt, session) { + const raw = (session?.goal || prompt || "").trim().replace(/\s+/g, " "); + if (!raw) return "Untitled session"; + return raw.length > 52 ? `${raw.slice(0, 52)}…` : raw; +} + +function sessionImageCount(entry) { + const fromTurns = (entry?.session?.turns || []).reduce( + (n, t) => n + (t.artifactIds?.length || 0), + 0, + ); + if (fromTurns) return fromTurns; + const results = entry?.results; + if (Array.isArray(results) && results.length) return results.length; + return entry?.result ? 1 : 0; +} + +function relativeTime(iso) { + if (!iso) return ""; + const t = new Date(iso).getTime(); + if (Number.isNaN(t)) return ""; + const sec = Math.max(0, Math.floor((Date.now() - t) / 1000)); + if (sec < 45) return "just now"; + const min = Math.floor(sec / 60); + if (min < 60) return `${min}m ago`; + const hr = Math.floor(min / 60); + if (hr < 24) return `${hr}h ago`; + const d = Math.floor(hr / 24); + return `${d}d ago`; +} + +function blankSessionEntry(id = makeSessionId()) { + const now = new Date().toISOString(); + return { + id, + title: "Untitled session", + createdAt: now, + updatedAt: now, + prompt: "", + session: emptySession(), + ideas: [], + suggestedLoras: [], + suggestNote: "", + civitaiQuery: "", + result: null, + results: [], + modelBrief: "", + pendingPlan: null, + pendingQuestion: null, + sessionLog: [], + }; +} + +function readStoredSidebarOpen() { + try { + const v = localStorage.getItem(SIDEBAR_STORAGE_KEY); + if (v === "0" || v === "false") return false; + if (v === "1" || v === "true") return true; + } catch { + /* ignore */ + } + return true; +} + +function readStoredSessions() { + try { + const raw = localStorage.getItem(SESSIONS_STORAGE_KEY); + if (!raw) return null; + const parsed = JSON.parse(raw); + if (!parsed || !Array.isArray(parsed.sessions) || !parsed.sessions.length) return null; + return { + activeId: parsed.activeId || parsed.sessions[0].id, + sessions: parsed.sessions, + }; + } catch { + /* ignore */ + } + return null; +} + +function persistSessionsStore(activeId, sessions) { + try { + localStorage.setItem( + SESSIONS_STORAGE_KEY, + JSON.stringify({ activeId, sessions }), + ); + } catch { + /* ignore */ + } +} + +function loraKey(l) { + return String(l.id ?? l.name); +} + +function readStoredMode() { + try { + const v = localStorage.getItem(AUTOMATION_STORAGE_KEY); + if (v === "review") return "plan"; + if (v === "approve") return "auto"; + if (AUTOMATION_MODES.includes(v)) return v; + } catch { + /* ignore */ + } + return "plan"; +} + +function readStoredModels() { + try { + const raw = localStorage.getItem(MODELS_STORAGE_KEY); + if (raw) { + const parsed = JSON.parse(raw); + return { + agentModel: AGENT_MODELS.some((m) => m.id === parsed.agentModel) + ? parsed.agentModel + : "openrouter/auto", + imageModel: IMAGE_MODELS.some((m) => m.id === parsed.imageModel) + ? parsed.imageModel + : "auto", + }; + } + } catch { + /* ignore */ + } + return { agentModel: "openrouter/auto", imageModel: "auto" }; +} + +function installableLoras(loras = []) { + return (loras || []).filter((l) => l.downloadUrl); +} + +function modelLabel(list, id) { + return list.find((m) => m.id === id)?.label || id; +} + +function modelShortLabel(list, id) { + const m = list.find((x) => x.id === id); + return m?.short || m?.label || id; +} + +/* Small inline glyphs (stroke = currentColor) — icons first, words in tooltips. */ +const Svg = ({ children, filled = false }) => ( + +); +const IconPlay = () => ( + + + +); +const IconSpinner = () => ( + + + + + +); +const IconBulb = () => ( + + + + +); +const IconLayers = () => ( + + + + +); +const IconSliders = () => ( + + + + + +); +const IconAgent = () => ( + + + + +); +const IconImage = () => ( + + + + + +); +const IconChevron = () => ( + + + +); +const IconSessions = () => ( + + + + +); +const IconSun = () => ( + + + + +); +const IconMoon = () => ( + + + +); + +function CompactMenu({ label, valueLabel, options, value, onChange, open, onOpen, icon, title }) { + const ref = useRef(null); + + useEffect(() => { + if (!open) return; + const onDoc = (e) => { + if (ref.current && !ref.current.contains(e.target)) onOpen(false); + }; + const onKey = (e) => { + if (e.key === "Escape") onOpen(false); + }; + document.addEventListener("mousedown", onDoc); + document.addEventListener("keydown", onKey); + return () => { + document.removeEventListener("mousedown", onDoc); + document.removeEventListener("keydown", onKey); + }; + }, [open, onOpen]); + + return ( +
+ + {open && ( +
    + {options.map((opt) => ( +
  • + +
  • + ))} +
+ )} +
+ ); +} + +export default function App() { + const storedSessions = readStoredSessions(); + const bootSession = + storedSessions?.sessions?.find((s) => s.id === storedSessions.activeId) || + storedSessions?.sessions?.[0] || + blankSessionEntry(); + + const [mock] = useState(() => isMockMode()); + /** `make mock-ui` / `npm run dev:mock` bake mock in — Exit cannot leave. */ + const mockLocked = import.meta.env.VITE_FREYA_MOCK === "true"; + const [tab, setTab] = useState("gallery"); + const [prompt, setPrompt] = useState(() => bootSession.prompt || ""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [result, setResult] = useState(() => bootSession.result ?? null); + const [batchResults, setBatchResults] = useState(() => + Array.isArray(bootSession.results) ? bootSession.results : [], + ); + const [styles, setStyles] = useState([]); + const [gallery, setGallery] = useState([]); + const [settings, setSettings] = useState(null); + const [civitaiKey, setCivitaiKey] = useState(""); + const [openrouterKey, setOpenrouterKey] = useState(""); + const [workerUrl, setWorkerUrl] = useState(""); + const [civitaiQ, setCivitaiQ] = useState(BEGINNER_CIVITAI_QUERY); + const [civitaiItems, setCivitaiItems] = useState([]); + const [savedMsg, setSavedMsg] = useState(""); + const [ideas, setIdeas] = useState(() => + Array.isArray(bootSession.ideas) ? bootSession.ideas : [], + ); + const [suggestedLoras, setSuggestedLoras] = useState(() => + Array.isArray(bootSession.suggestedLoras) ? bootSession.suggestedLoras : [], + ); + const [suggestNote, setSuggestNote] = useState(() => bootSession.suggestNote || ""); + const [civitaiQuery, setCivitaiQuery] = useState(() => bootSession.civitaiQuery || ""); + const [modelBrief, setModelBrief] = useState(() => bootSession.modelBrief || ""); + const [session, setSession] = useState(() => + bootSession.session + ? { + goal: bootSession.session.goal || "", + pinnedLoras: Array.isArray(bootSession.session.pinnedLoras) + ? bootSession.session.pinnedLoras + : [], + turns: Array.isArray(bootSession.session.turns) ? bootSession.session.turns : [], + sessionNote: bootSession.session.sessionNote || "", + } + : emptySession(), + ); + const [automationMode, setAutomationMode] = useState(readStoredMode); + const storedModels = readStoredModels(); + const [agentModel, setAgentModel] = useState(storedModels.agentModel); + const [imageModel, setImageModel] = useState(storedModels.imageModel); + const [pendingPlan, setPendingPlan] = useState(() => bootSession.pendingPlan ?? null); + const [pendingQuestion, setPendingQuestion] = useState( + () => bootSession.pendingQuestion ?? null, + ); + const [sessionLog, setSessionLog] = useState(() => + Array.isArray(bootSession.sessionLog) ? bootSession.sessionLog : [], + ); + const [menuOpen, setMenuOpen] = useState(null); + const [theme, setTheme] = useState(resolveInitialTheme); + const [sidebarOpen, setSidebarOpen] = useState(readStoredSidebarOpen); + const [activeSessionId, setActiveSessionId] = useState( + () => bootSession.id || makeSessionId(), + ); + const [sessions, setSessions] = useState(() => + storedSessions?.sessions?.length ? storedSessions.sessions : [bootSession], + ); + const sessionsRef = useRef(sessions); + const activeIdRef = useRef(activeSessionId); + const timelineRef = useRef(null); + + useEffect(() => { + sessionsRef.current = sessions; + }, [sessions]); + + useEffect(() => { + activeIdRef.current = activeSessionId; + }, [activeSessionId]); + + // Apply theme to ; persistence happens only on toggle, + // so an unsaved preference keeps following the system. + useEffect(() => { + document.documentElement.dataset.theme = theme; + document.documentElement.style.colorScheme = theme; + document + .querySelector('meta[name="theme-color"]') + ?.setAttribute("content", theme === "dark" ? "#0e1418" : "#f6f1e4"); + }, [theme]); + + // Follow system changes until the user picks a theme explicitly. + useEffect(() => { + if (readStoredTheme()) return; + const mq = window.matchMedia("(prefers-color-scheme: light)"); + const onChange = (e) => { + // Ignore OS changes after an explicit toggle writes freya.theme. + if (readStoredTheme()) return; + setTheme(e.matches ? "light" : "dark"); + }; + mq.addEventListener?.("change", onChange); + return () => mq.removeEventListener?.("change", onChange); + }, []); + + const toggleTheme = () => { + const next = theme === "dark" ? "light" : "dark"; + setTheme(next); + try { + localStorage.setItem(THEME_STORAGE_KEY, next); + } catch { + /* ignore */ + } + }; + + /** Featured style example from /v1/styles (styles[0]) — same text Styles tab shows. */ + const examplePrompt = styles[0]?.examplePrompt || BEGINNER_EXAMPLE; + const exampleCivitaiQuery = demoCivitaiQuery(examplePrompt); + + const snapshotCurrent = (id = activeSessionId) => { + const prev = sessionsRef.current.find((s) => s.id === id); + const now = new Date().toISOString(); + return { + id, + title: sessionTitleFrom(prompt, session), + createdAt: prev?.createdAt || now, + updatedAt: now, + prompt, + session: { + goal: session.goal || "", + pinnedLoras: session.pinnedLoras || [], + turns: session.turns || [], + sessionNote: session.sessionNote || "", + }, + ideas, + suggestedLoras, + suggestNote, + civitaiQuery, + result, + results: batchResults, + modelBrief, + pendingPlan, + pendingQuestion, + sessionLog, + }; + }; + + const applySessionEntry = (entry) => { + setPrompt(entry.prompt || ""); + setSession( + entry.session + ? { + goal: entry.session.goal || "", + pinnedLoras: Array.isArray(entry.session.pinnedLoras) + ? entry.session.pinnedLoras + : [], + turns: Array.isArray(entry.session.turns) ? entry.session.turns : [], + sessionNote: entry.session.sessionNote || "", + } + : emptySession(), + ); + setIdeas(Array.isArray(entry.ideas) ? entry.ideas : []); + setSuggestedLoras(Array.isArray(entry.suggestedLoras) ? entry.suggestedLoras : []); + setSuggestNote(entry.suggestNote || ""); + setCivitaiQuery(entry.civitaiQuery || ""); + if (entry.civitaiQuery) setCivitaiQ(entry.civitaiQuery); + setResult(entry.result ?? null); + setBatchResults(Array.isArray(entry.results) ? entry.results : []); + setModelBrief(entry.modelBrief || ""); + setPendingPlan(entry.pendingPlan ?? null); + setPendingQuestion(entry.pendingQuestion ?? null); + setSessionLog(Array.isArray(entry.sessionLog) ? entry.sessionLog : []); + setError(""); + setSavedMsg(""); + }; + + const upsertSessionList = (snap, list = sessionsRef.current) => { + const idx = list.findIndex((s) => s.id === snap.id); + if (idx === -1) return [snap, ...list]; + const next = [...list]; + next[idx] = { ...snap, createdAt: list[idx].createdAt || snap.createdAt }; + return next; + }; + + const persistAll = (activeId, list) => { + setSessions(list); + sessionsRef.current = list; + activeIdRef.current = activeId; + persistSessionsStore(activeId, list); + }; + + const startNewSession = () => { + const snap = snapshotCurrent(); + const blank = blankSessionEntry(); + const list = [blank, ...upsertSessionList(snap).filter((s) => s.id !== blank.id)]; + persistAll(blank.id, list); + setActiveSessionId(blank.id); + applySessionEntry(blank); + setTab("gallery"); + setSavedMsg("Started a new session."); + }; + + const switchSession = (id) => { + if (!id || id === activeSessionId) return; + const target = sessionsRef.current.find((s) => s.id === id); + if (!target) return; + const snap = snapshotCurrent(); + const list = upsertSessionList(snap); + persistAll(id, list); + setActiveSessionId(id); + applySessionEntry(target); + setTab("gallery"); + }; + + const setSidebar = (open) => { + setSidebarOpen(open); + try { + localStorage.setItem(SIDEBAR_STORAGE_KEY, open ? "1" : "0"); + } catch { + /* ignore */ + } + }; + + // Keep the active session entry fresh for reload / switch (mock persistence). + useEffect(() => { + const snap = snapshotCurrent(); + const list = upsertSessionList(snap); + sessionsRef.current = list; + setSessions(list); + persistSessionsStore(activeSessionId, list); + // eslint-disable-next-line react-hooks/exhaustive-deps -- intentional sync of live working set + }, [ + activeSessionId, + prompt, + session, + ideas, + suggestedLoras, + suggestNote, + civitaiQuery, + result, + batchResults, + modelBrief, + pendingPlan, + pendingQuestion, + sessionLog, + ]); + + const refresh = async () => { + try { + const [s, st, g] = await Promise.all([ + api("/v1/styles"), + api("/v1/settings"), + api("/v1/gallery"), + ]); + const items = s.items || []; + setStyles(items); + setSettings(st); + setWorkerUrl(st.diffusionWorkerUrl || ""); + setGallery(g.items || []); + const featured = items[0]?.examplePrompt; + if (featured) { + setCivitaiQ((prev) => + !prev.trim() || prev === BEGINNER_CIVITAI_QUERY ? demoCivitaiQuery(featured) : prev, + ); + } + } catch (e) { + setError(e.message); + } + }; + + useEffect(() => { + refresh(); + }, []); + + const persistModels = (nextAgent, nextImage) => { + try { + localStorage.setItem( + MODELS_STORAGE_KEY, + JSON.stringify({ agentModel: nextAgent, imageModel: nextImage }), + ); + } catch { + /* ignore */ + } + }; + + const setMode = (mode) => { + if (!AUTOMATION_MODES.includes(mode)) return; + setAutomationMode(mode); + try { + localStorage.setItem(AUTOMATION_STORAGE_KEY, mode); + } catch { + /* ignore */ + } + }; + + const changeAgentModel = (id) => { + setAgentModel(id); + persistModels(id, imageModel); + }; + + const changeImageModel = (id) => { + setImageModel(id); + persistModels(agentModel, id); + }; + + const hasWorker = () => Boolean(settings?.diffusionWorkerUrl || workerUrl.trim()); + const canAutoInstall = () => Boolean(settings?.civitaiConfigured && hasWorker()); + const canCloudGenerate = () => Boolean(settings?.openRouterConfigured); + + const pinnedPayload = () => + (session.pinnedLoras || []).map((l) => ({ + name: l.name, + scale: l.scale ?? 0.8, + })); + + const isPinned = (item) => + (session.pinnedLoras || []).some((p) => loraKey(p) === loraKey(item)); + + const pinLora = (item) => { + setSession((prev) => { + if ((prev.pinnedLoras || []).some((p) => loraKey(p) === loraKey(item))) return prev; + const next = { + id: item.id, + name: item.name, + modelType: item.modelType, + downloadUrl: item.downloadUrl, + triggerWord: item.triggerWord || null, + scale: 0.8, + }; + return { + ...prev, + pinnedLoras: [...(prev.pinnedLoras || []), next], + sessionNote: item.triggerWord + ? `Pinned “${item.name}”. Trigger word “${item.triggerWord}” is optional — Freya keeps your prompt as you wrote it.` + : `Pinned “${item.name}” for this session. Your prompt stays as you wrote it.`, + }; + }); + setSavedMsg(`Pinned ${item.name} for this session.`); + }; + + const unpinLora = (item) => { + setSession((prev) => ({ + ...prev, + pinnedLoras: (prev.pinnedLoras || []).filter((p) => loraKey(p) !== loraKey(item)), + })); + }; + + const pushTurn = (text, artifactIds = []) => { + setSession((prev) => ({ + ...prev, + goal: prev.goal || text, + turns: [{ prompt: text, at: new Date().toISOString(), artifactIds }, ...(prev.turns || [])].slice( + 0, + 12, + ), + })); + }; + + const runBody = (nlPrompt) => { + const loras = pinnedPayload(); + // Pinned LoRAs only apply on the local worker — prefer local when a worker is set. + const body = { + prompt: nlPrompt, + enhance: "auto", + backend: loras.length && hasWorker() ? "local" : "auto", + loras, + automationMode, + }; + if (imageModel && imageModel !== "auto") body.model = imageModel; + return body; + }; + + const assistBody = (mode, message) => { + const body = { + mode, + message, + automationMode, + session: { + goal: session.goal || message, + pinnedLoras: session.pinnedLoras, + recentPrompts: (session.turns || []).slice(0, 5).map((t) => t.prompt), + }, + }; + if (agentModel && agentModel !== "openrouter/auto") body.model = agentModel; + return body; + }; + + const runOne = async (nlPrompt) => { + const data = await api("/v1/run", { + method: "POST", + body: JSON.stringify(runBody(nlPrompt)), + }); + return data; + }; + + const installOne = async (item) => { + const safe = (item.name || "model").replace(/[^a-zA-Z0-9._-]+/g, "_"); + const dest = + item.modelType === "LORA" || item.modelType === "LoCon" + ? `loras/${safe}.safetensors` + : `checkpoints/${safe}.safetensors`; + await api("/v1/civitai/install", { + method: "POST", + body: JSON.stringify({ + downloadUrl: item.downloadUrl, + destPath: dest, + name: item.name, + }), + }); + pinLora(item); + return dest; + }; + + const executeBatch = async (batch, goal) => { + const sessionId = activeIdRef.current; + const results = []; + for (const bp of batch) { + const data = await runOne(bp); + if (activeIdRef.current !== sessionId) return results; + results.push({ ...data, prompt: bp }); + } + if (activeIdRef.current !== sessionId) return results; + setBatchResults(results); + setResult(results[0] || null); + setModelBrief(results[0]?.enhancedPrompt || ""); + setPrompt(batch[0] || goal); + pushTurn(goal, results.map((r) => r.artifactId).filter(Boolean)); + const g = await api("/v1/gallery"); + if (activeIdRef.current !== sessionId) return results; + setGallery(g.items || []); + return results; + }; + + const executePendingInstalls = async (loras, _opts = {}) => { + const log = []; + const list = installableLoras(loras); + if (!list.length) return log; + + if (!canAutoInstall()) { + const names = list.map((l) => l.name).join(", "); + // Worker is optional — skip install and keep generating on OpenRouter when possible. + const note = hasWorker() + ? `Would install ${names} — add a Civitai key in Settings to install.` + : canCloudGenerate() + ? `LoRAs need a worker; generating with OpenRouter. (Skipped install: ${names})` + : `LoRAs need a worker URL to install (${names}). Add a worker for custom/local looks, or configure OpenRouter to generate in the cloud.`; + log.push(note); + setSavedMsg(note); + return log; + } + + for (const item of list) { + try { + const dest = await installOne(item); + log.push(`Installed “${item.name}” → ${dest}`); + } catch (e) { + log.push(`Install skipped for “${item.name}”: ${e.message}`); + } + } + return log; + }; + + const applyAssistPlan = (assist, message) => { + const goal = assist.goal || message; + const batch = + Array.isArray(assist.batchPrompts) && assist.batchPrompts.length + ? assist.batchPrompts + : [ + `${message} — wide establishing shot.`, + `${message} — closer framing.`, + `${message} — cooler, quieter mood.`, + ]; + const loras = Array.isArray(assist.loras) ? assist.loras : []; + const pendingInstalls = installableLoras(loras).slice(0, 3); + + setSession((prev) => ({ + ...prev, + goal, + sessionNote: assist.sessionNote || prev.sessionNote, + })); + setSuggestedLoras(loras); + setIdeas([]); + setSuggestNote(assist.sessionNote || ""); + setCivitaiQuery(assist.civitaiQuery || ""); + if (assist.civitaiQuery) setCivitaiQ(assist.civitaiQuery); + + return { + goal, + batchPrompts: batch, + steps: Array.isArray(assist.steps) ? assist.steps : [], + civitaiQuery: assist.civitaiQuery || "", + sessionNote: assist.sessionNote || "", + loras, + pendingInstalls, + }; + }; + + const run = async () => { + const sessionId = activeIdRef.current; + setBusy(true); + setError(""); + setBatchResults([]); + try { + const data = await runOne(prompt); + if (activeIdRef.current !== sessionId) return; + setResult(data); + setModelBrief(data.enhancedPrompt || ""); + pushTurn(prompt, data.artifactId ? [data.artifactId] : []); + const g = await api("/v1/gallery"); + if (activeIdRef.current !== sessionId) return; + setGallery(g.items || []); + } catch (e) { + if (activeIdRef.current === sessionId) setError(e.message); + } finally { + if (activeIdRef.current === sessionId) setBusy(false); + } + }; + + /** Ask Freya for NL alternatives + LoRA recommendations (never auto-installs). */ + const suggestIdeas = async () => { + setBusy(true); + setError(""); + try { + const message = prompt.trim() || examplePrompt; + if (!prompt.trim()) setPrompt(examplePrompt); + const data = await api("/v1/assist", { + method: "POST", + body: JSON.stringify(assistBody("suggest", message)), + }); + const nextIdeas = Array.isArray(data.ideas) + ? data.ideas + : typeof data.text === "string" + ? data.text + .split("\n") + .map((l) => l.replace(/^\d+\.\s*/, "").trim()) + .filter(Boolean) + : []; + setIdeas(nextIdeas); + setSuggestedLoras(Array.isArray(data.loras) ? data.loras : []); + setSuggestNote(data.sessionNote || ""); + setCivitaiQuery(data.civitaiQuery || ""); + if (data.civitaiQuery) setCivitaiQ(data.civitaiQuery); + if (data.sessionNote) { + setSession((prev) => ({ ...prev, sessionNote: data.sessionNote })); + } + if (!settings?.civitaiConfigured && (!data.loras || data.loras.length === 0)) { + setSavedMsg( + "LoRA suggestions need a Civitai key — add any non-empty value in Settings (mock).", + ); + } + } catch (e) { + setError(e.message); + } finally { + setBusy(false); + } + }; + + const fetchSessionPlan = async () => { + const message = prompt.trim() || session.goal || examplePrompt; + if (!prompt.trim() && !session.goal) setPrompt(examplePrompt); + const assist = await api("/v1/assist", { + method: "POST", + body: JSON.stringify(assistBody("session", message)), + }); + return applyAssistPlan(assist, message); + }; + + /** Detect Auto-mode questions (ambiguous / high-impact). */ + const detectAutoQuestion = (plan) => { + if (!prompt.trim() && !session.goal) { + return { + kind: "goal", + text: "Your goal is still vague — use the style example, or type a clearer scene before Freya generates?", + choices: [ + { id: "example", label: "Use example", value: examplePrompt }, + { id: "as-is", label: "Continue with current text", value: plan.goal }, + ], + }; + } + // Only ask about installs when a worker can actually receive them. + if (plan.pendingInstalls?.length > 1 && canAutoInstall()) { + return { + kind: "lora", + text: "Several LoRAs match — which should Freya install before generating?", + choices: [ + ...plan.pendingInstalls.map((l) => ({ + id: loraKey(l), + label: `Install “${l.name}”`, + value: l, + })), + { id: "none", label: "Skip installs — generate only", value: null }, + { + id: "all", + label: `Install all ${plan.pendingInstalls.length}`, + value: "all", + }, + ], + }; + } + return null; + }; + + const executePlan = async (plan, { installs = null, yolo = false } = {}) => { + const log = []; + if (plan.civitaiQuery) { + log.push(`Searched Civitai for “${plan.civitaiQuery}”`); + } + + let toInstall = []; + if (installs === "all") toInstall = plan.pendingInstalls || []; + else if (Array.isArray(installs)) toInstall = installs; + else if (installs && typeof installs === "object") toInstall = [installs]; + else if (yolo) toInstall = plan.pendingInstalls || []; + + if (toInstall.length) { + const installLog = await executePendingInstalls(toInstall); + log.push(...installLog); + } else if ((plan.pendingInstalls || []).length) { + log.push( + yolo + ? `Skipped LoRA installs (${plan.pendingInstalls.map((l) => l.name).join(", ")})` + : `LoRA installs left for you (${plan.pendingInstalls.map((l) => l.name).join(", ")})`, + ); + } + + log.push(`Generating ${plan.batchPrompts.length} variations…`); + await executeBatch(plan.batchPrompts, plan.goal); + log.push(`Generated ${plan.batchPrompts.length} images for “${plan.goal}”.`); + if (agentModel && agentModel !== "openrouter/auto") { + log.push(`Agent model: ${modelLabel(AGENT_MODELS, agentModel)}`); + } + if (imageModel && imageModel !== "auto") { + log.push(`Image model: ${modelLabel(IMAGE_MODELS, imageModel)}`); + } + setSessionLog(log); + setPendingPlan(null); + setPendingQuestion(null); + setSuggestNote( + yolo + ? plan.sessionNote || "YOLO session complete — Freya ran without pausing." + : plan.sessionNote || "Session complete. Pin a LoRA or tweak a prompt to iterate.", + ); + }; + + /** Agentic session — gated by Plan / Auto / YOLO. */ + const runSession = async () => { + const sessionId = activeIdRef.current; + setBusy(true); + setError(""); + setBatchResults([]); + setSessionLog([]); + setPendingQuestion(null); + try { + const plan = await fetchSessionPlan(); + if (activeIdRef.current !== sessionId) return; + + if (automationMode === "plan") { + setPendingPlan({ ...plan, status: "plan" }); + setSuggestNote( + plan.sessionNote || + "Plan ready — no generate or install. Run pieces manually, or switch to Auto/YOLO and Run session again.", + ); + setSavedMsg("Plan mode — nothing executed yet."); + return; + } + + if (automationMode === "auto") { + const q = detectAutoQuestion(plan); + if (q) { + setPendingPlan({ ...plan, status: "auto" }); + setPendingQuestion(q); + setSuggestNote(plan.sessionNote || "Freya paused — answer below to continue."); + setSavedMsg("Auto mode — waiting on your answer."); + return; + } + setPendingPlan(null); + await executePlan(plan, { + installs: (plan.pendingInstalls || []).length === 1 ? plan.pendingInstalls : [], + yolo: false, + }); + return; + } + + // YOLO + setPendingPlan(null); + await executePlan(plan, { installs: "all", yolo: true }); + } catch (e) { + if (activeIdRef.current === sessionId) setError(e.message); + } finally { + if (activeIdRef.current === sessionId) setBusy(false); + } + }; + + const answerQuestion = async (choice) => { + if (!pendingPlan || !pendingQuestion) return; + + if (choice.value === "settings") { + setTab("settings"); + setSavedMsg("Add a worker URL (and Civitai key) for LoRA installs — OpenRouter still generates without one."); + return; + } + + setBusy(true); + setError(""); + try { + let plan = pendingPlan; + if (pendingQuestion.kind === "goal" && choice.id === "example") { + setPrompt(examplePrompt); + plan = { ...plan, goal: examplePrompt }; + } + + let installs = []; + if (pendingQuestion.kind === "lora") { + if (choice.value === "all") installs = "all"; + else if (choice.value == null) installs = []; + else installs = [choice.value]; + } else if (pendingQuestion.kind === "config") { + installs = []; + } else if ((plan.pendingInstalls || []).length === 1 && canAutoInstall()) { + installs = plan.pendingInstalls; + } + + await executePlan(plan, { installs, yolo: false }); + setSavedMsg("Continued after your answer."); + } catch (e) { + setError(e.message); + } finally { + setBusy(false); + } + }; + + const dismissPending = () => { + setPendingPlan(null); + setPendingQuestion(null); + setSavedMsg("Dismissed."); + }; + + const saveSettings = async () => { + setBusy(true); + setError(""); + setSavedMsg(""); + try { + const body = { diffusionWorkerUrl: workerUrl }; + if (civitaiKey.trim()) body.civitaiApiKey = civitaiKey.trim(); + if (openrouterKey.trim()) body.openrouterApiKey = openrouterKey.trim(); + const st = await api("/v1/settings", { + method: "PUT", + body: JSON.stringify(body), + }); + setSettings(st); + setCivitaiKey(""); + setOpenrouterKey(""); + setSavedMsg( + mock + ? "Mock settings saved in-memory (reload resets unless you keep this tab open)." + : "Settings saved. Keys are stored for this Freya API instance.", + ); + } catch (e) { + setError(e.message); + } finally { + setBusy(false); + } + }; + + const searchCivitai = async () => { + setBusy(true); + setError(""); + try { + const data = await api(`/v1/civitai/search?q=${encodeURIComponent(civitaiQ)}&limit=12`); + setCivitaiItems(data.items || []); + } catch (e) { + setError(e.message); + } finally { + setBusy(false); + } + }; + + const installCivitai = async (item) => { + if (!item.downloadUrl) { + setError("No download URL on this card"); + return; + } + if (!hasWorker()) { + pinLora(item); + setSavedMsg( + `Pinned “${item.name}” for later — Install needs a diffusion worker. Cloud Generate still works via OpenRouter.`, + ); + return; + } + if (!settings?.civitaiConfigured) { + setError("Add a Civitai API key in Settings to install LoRAs onto your worker."); + return; + } + setBusy(true); + setError(""); + try { + const dest = await installOne(item); + setSavedMsg(`Queued install of ${item.name} → ${dest} on the diffusion worker. Pinned for session.`); + } catch (e) { + setError(e.message); + } finally { + setBusy(false); + } + }; + + const gallerySrc = (g) => g.url || `/v1/gallery/${g.id}/image`; + + const leaveMock = () => { + localStorage.removeItem("freya.mock"); + const u = new URL(window.location.href); + u.searchParams.delete("mock"); + window.location.href = u.toString(); + }; + + const stayInMock = () => { + localStorage.setItem("freya.mock", "1"); + }; + + const clearSuggestions = () => { + setIdeas([]); + setSuggestedLoras([]); + setSuggestNote(""); + setCivitaiQuery(""); + }; + + const useStyleExample = () => { + setPrompt(examplePrompt); + setTab("gallery"); + }; + + const chronologicalTurns = [...(session.turns || [])].reverse(); + + // Keep the newest history in view above the pinned composer. + useEffect(() => { + const el = timelineRef.current; + if (el) el.scrollTop = el.scrollHeight; + }, [ + activeSessionId, + chronologicalTurns.length, + sessionLog.length, + ideas.length, + pendingPlan, + pendingQuestion, + ]); + + const hasTimeline = + Boolean(session.goal) || + chronologicalTurns.length > 0 || + (session.pinnedLoras || []).length > 0 || + Boolean(session.sessionNote); + + const renderLoraCard = (item, { compact = false } = {}) => { + const pinned = isPinned(item); + return ( +
+
+

{item.name}

+

+ {item.modelType || "LORA"} + {item.triggerWord ? ` · trigger: ${item.triggerWord}` : ""} +

+
+
+ + +
+
+ ); + }; + + const showAssistPanel = + ideas.length > 0 || suggestedLoras.length > 0 || suggestNote || civitaiQuery; + + const modeOptions = AUTOMATION_MODES.map((id) => ({ + id, + label: AUTOMATION_LABELS[id], + })); + + return ( +
+ {mock && ( +
+ Mock + + In-memory atelier — Suggest, pin LoRAs, and Run session without a live API. + +
+ + {mockLocked ? ( + + Dev mock (restart without VITE_FREYA_MOCK to use live API) + + ) : ( + + )} +
+
+ )} + +
+
+ + + Freya. + + agentic image studio +
+
+ + {mock && mock} + {settings && ( + + + OpenRouter + + Civitai + + Worker + + )} + {AUTOMATION_LABELS[automationMode]} +
+
+ +
+ + +
+
+
+
+

Session

+ + {chronologicalTurns.length + ? `${chronologicalTurns.length} turn${chronologicalTurns.length === 1 ? "" : "s"}` + : "no turns yet"} + + +
+ + {!hasTimeline && !pendingPlan && !pendingQuestion && sessionLog.length === 0 && ( +

+ Your goals, plans, questions and turns will collect here. Try the featured example, + then Suggest ideas or Run session. +

+ )} + + {session.goal && ( +
+ Goal +

{session.goal}

+
+ )} + + {(session.pinnedLoras || []).length > 0 && ( +
+ Pinned LoRAs +
    + {(session.pinnedLoras || []).map((l) => ( +
  • + + {l.name} + {l.triggerWord ? ` · ${l.triggerWord}` : ""} + + +
  • + ))} +
+
+ )} + + {chronologicalTurns.map((t, i) => ( +
+
+ Turn {i + 1} + {t.at && ( + + )} + {t.artifactIds?.length > 0 && ( + + {t.artifactIds.length} image{t.artifactIds.length === 1 ? "" : "s"} → + + )} +
+ +
+ ))} + + {session.sessionNote && ( +
+ Session note +

{session.sessionNote}

+
+ )} + + {pendingPlan && pendingPlan.status === "plan" && ( + + )} + + {pendingQuestion && ( + + )} + + {sessionLog.length > 0 && ( + + )} + + {showAssistPanel && ( + + )} +
+ +
+
+ + {!prompt.trim() && ( + + )} +
+