A high-performance inference engine for AI models
Bindings migration 4/n (#364)
Aleksei Savin0653bfca0689
diff --git a/Cargo.lock b/Cargo.lockindex 22747da7f..573b3aa96 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8,6 +8,17 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"+[[package]]+name = "aes"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"+dependencies = [+ "cfg-if 1.0.4",+ "cipher",+ "cpufeatures 0.2.17",+]+[[package]]name = "ahash"version = "0.8.12"@@ -229,6 +240,30 @@ dependencies = ["winnow 0.7.15",]+[[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-channel"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"+dependencies = [+ "concurrent-queue",+ "event-listener-strategy",+ "futures-core",+ "pin-project-lite",+]+[[package]]name = "async-fetcher"version = "0.12.0"@@ -256,6 +291,35 @@ dependencies = ["tokio",]+[[package]]+name = "async-io"+version = "2.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"+dependencies = [+ "autocfg",+ "cfg-if 1.0.4",+ "concurrent-queue",+ "futures-io",+ "futures-lite",+ "parking",+ "polling",+ "rustix",+ "slab",+ "windows-sys 0.61.2",+]++[[package]]+name = "async-lock"+version = "3.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"+dependencies = [+ "event-listener",+ "event-listener-strategy",+ "pin-project-lite",+]+[[package]]name = "async-openai"version = "0.35.0"@@ -296,12 +360,59 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "async-process"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"+dependencies = [+ "async-channel",+ "async-io",+ "async-lock",+ "async-signal",+ "async-task",+ "blocking",+ "cfg-if 1.0.4",+ "event-listener",+ "futures-lite",+ "rustix",+]++[[package]]+name = "async-recursion"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "async-shutdown"version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f13fa00d3d9ba01f4c6ee77a73d784281cfa3340a9e1d43948e439921d24e934"+[[package]]+name = "async-signal"+version = "0.2.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"+dependencies = [+ "async-io",+ "async-lock",+ "atomic-waker",+ "cfg-if 1.0.4",+ "futures-core",+ "futures-io",+ "rustix",+ "signal-hook-registry",+ "slab",+ "windows-sys 0.61.2",+]+[[package]]name = "async-stream"version = "0.3.6"@@ -324,6 +435,12 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "async-task"+version = "4.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"+[[package]]name = "async-trait"version = "0.1.89"@@ -668,10 +785,10 @@ checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"name = "benchmarks"version = "0.1.9"dependencies = [+ "backend-uzu","mach2","serde","sysinfo",- "uzu",][[package]]@@ -795,6 +912,15 @@ dependencies = ["generic-array",]+[[package]]+name = "block-padding"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"+dependencies = [+ "generic-array",+]+[[package]]name = "block2"version = "0.6.2"@@ -804,6 +930,19 @@ dependencies = ["objc2",]+[[package]]+name = "blocking"+version = "1.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"+dependencies = [+ "async-channel",+ "async-task",+ "futures-io",+ "futures-lite",+ "piper",+]+[[package]]name = "borrow-or-share"version = "0.2.4"@@ -930,6 +1069,15 @@ dependencies = ["rustversion",]+[[package]]+name = "cbc"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"+dependencies = [+ "cipher",+]+[[package]]name = "cbindgen"version = "0.29.2"@@ -1046,6 +1194,16 @@ dependencies = ["half",]+[[package]]+name = "cipher"+version = "0.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"+dependencies = [+ "crypto-common",+ "inout",+]+[[package]]name = "clang-ast"version = "0.1.35"@@ -1111,6 +1269,7 @@ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"name = "cli"version = "0.1.9"dependencies = [+ "backend-uzu","benchmarks","clap","comfy-table",@@ -1123,7 +1282,18 @@ dependencies = ["serde_json","tokio","uuid",- "uzu",+]++[[package]]+name = "cli-release"+version = "0.1.9"+dependencies = [+ "clap",+ "heck",+ "ignore",+ "regex",+ "serde_json",+ "thiserror 2.0.18",][[package]]@@ -1209,6 +1379,15 @@ dependencies = ["static_assertions",]+[[package]]+name = "concurrent-queue"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"+dependencies = [+ "crossbeam-utils",+]+[[package]]name = "console"version = "0.16.3"@@ -1718,6 +1897,35 @@ version = "2.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea"+[[package]]+name = "dbus"+version = "0.9.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b942602992bb7acfd1f51c49811c58a610ef9181b6e66f3e519d79b540a3bf73"+dependencies = [+ "libc",+ "libdbus-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "dbus-secret-service"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6"+dependencies = [+ "aes",+ "block-padding",+ "cbc",+ "dbus",+ "fastrand",+ "hkdf",+ "num",+ "once_cell",+ "sha2",+ "zeroize",+]+[[package]]name = "deltae"version = "0.3.2"@@ -1870,6 +2078,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = ["block-buffer","crypto-common",+ "subtle",][[package]]@@ -2029,6 +2238,33 @@ dependencies = ["cfg-if 1.0.4",]+[[package]]+name = "endi"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"++[[package]]+name = "enumflags2"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"+dependencies = [+ "enumflags2_derive",+ "serde",+]++[[package]]+name = "enumflags2_derive"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "env_logger"version = "0.9.3"@@ -2096,6 +2332,27 @@ dependencies = ["num-traits",]+[[package]]+name = "event-listener"+version = "5.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab"+dependencies = [+ "concurrent-queue",+ "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 = "eventsource-stream"version = "0.2.3"@@ -2390,6 +2647,19 @@ version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"+[[package]]+name = "futures-lite"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"+dependencies = [+ "fastrand",+ "futures-core",+ "futures-io",+ "parking",+ "pin-project-lite",+]+[[package]]name = "futures-macro"version = "0.3.32"@@ -2534,6 +2804,19 @@ version = "0.3.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"+[[package]]+name = "globset"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52dfc19153a48bde0cbd630453615c8151bce3a5adfac7a0aebfbf0a1e1f57e3"+dependencies = [+ "aho-corasick",+ "bstr",+ "log",+ "regex-automata",+ "regex-syntax 0.8.10",+]+[[package]]name = "gloo-utils"version = "0.2.0"@@ -2712,6 +2995,30 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "hkdf"+version = "0.12.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"+dependencies = [+ "hmac",+]++[[package]]+name = "hmac"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"+dependencies = [+ "digest",+]++[[package]]+name = "hound"+version = "3.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f"+[[package]]name = "http"version = "0.2.12"@@ -3037,6 +3344,22 @@ dependencies = ["nix 0.8.1",]+[[package]]+name = "ignore"+version = "0.4.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3d782a365a015e0f5c04902246139249abf769125006fbe7649e2ee88169b4a"+dependencies = [+ "crossbeam-deque",+ "globset",+ "log",+ "memchr",+ "regex-automata",+ "same-file",+ "walkdir",+ "winapi-util",+]+[[package]]name = "image"version = "0.25.10"@@ -3134,6 +3457,16 @@ version = "0.1.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb"+[[package]]+name = "inout"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"+dependencies = [+ "block-padding",+ "generic-array",+]+[[package]]name = "inquire"version = "0.9.4"@@ -3181,6 +3514,15 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "inventory"+version = "0.3.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b"+dependencies = [+ "rustversion",+]+[[package]]name = "ipnet"version = "2.12.0"@@ -3387,6 +3729,23 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "keyring"+version = "3.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"+dependencies = [+ "byteorder",+ "dbus-secret-service",+ "linux-keyutils",+ "log",+ "secret-service",+ "security-framework 2.11.1",+ "security-framework 3.7.0",+ "windows-sys 0.60.2",+ "zeroize",+]+[[package]]name = "lab"version = "0.11.0"@@ -3417,6 +3776,15 @@ version = "0.2.185"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f"+[[package]]+name = "libdbus-sys"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"+dependencies = [+ "pkg-config",+]+[[package]]name = "libfuzzer-sys"version = "0.4.12"@@ -3483,6 +3851,16 @@ dependencies = ["cc",]+[[package]]+name = "linux-keyutils"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83270a18e9f90d0707c41e9f35efada77b64c0e6f3f1810e71c8368a864d5590"+dependencies = [+ "bitflags 2.11.1",+ "libc",+]+[[package]]name = "linux-raw-sys"version = "0.12.1"@@ -3881,17 +4259,27 @@ dependencies = [name = "nagare"version = "0.1.9"dependencies = [+ "bindings","futures","hanashi","indexmap 2.14.0",+ "napi",+ "napi-build",+ "napi-derive",+ "pyo3","reqwest 0.13.2","serde",+ "serde-wasm-bindgen","serde_json","shoji","thiserror 2.0.18","tokio","tokio-stream","tokio-util",+ "tsify",+ "uniffi",+ "wasm-bindgen",+ "wasm-bindgen-futures",][[package]]@@ -3908,6 +4296,7 @@ dependencies = ["napi-sys","nohash-hasher","rustc-hash 2.1.2",+ "tokio",][[package]]@@ -3964,7 +4353,7 @@ dependencies = ["openssl-probe","openssl-sys","schannel",- "security-framework",+ "security-framework 3.7.0","security-framework-sys","tempfile",]@@ -4416,6 +4805,16 @@ dependencies = ["num-traits",]+[[package]]+name = "ordered-stream"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"+dependencies = [+ "futures-core",+ "pin-project-lite",+]+[[package]]name = "outref"version = "0.5.2"@@ -4432,6 +4831,12 @@ dependencies = ["winapi",]+[[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"@@ -4606,6 +5011,17 @@ version = "0.2.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"+[[package]]+name = "piper"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"+dependencies = [+ "atomic-waker",+ "fastrand",+ "futures-io",+]+[[package]]name = "pkg-config"version = "0.3.33"@@ -4659,6 +5075,20 @@ dependencies = ["miniz_oxide",]+[[package]]+name = "polling"+version = "3.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"+dependencies = [+ "cfg-if 1.0.4",+ "concurrent-queue",+ "hermit-abi 0.5.2",+ "pin-project-lite",+ "rustix",+ "windows-sys 0.61.2",+]+[[package]]name = "poolshark"version = "0.2.7"@@ -4733,6 +5163,15 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "proc-macro-crate"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"+dependencies = [+ "toml_edit 0.25.11+spec-1.1.0",+]+[[package]]name = "proc-macro-error"version = "1.0.4"@@ -4829,6 +5268,7 @@ version = "0.28.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "91fd8e38a3b50ed1167fb981cd6fd60147e091784c427b8f7183a7ee32c31c12"dependencies = [+ "inventory","libc","once_cell","portable-atomic",@@ -5687,7 +6127,7 @@ dependencies = ["openssl-probe","rustls-pki-types","schannel",- "security-framework",+ "security-framework 3.7.0",][[package]]@@ -5715,7 +6155,7 @@ dependencies = ["rustls-native-certs","rustls-platform-verifier-android","rustls-webpki",- "security-framework",+ "security-framework 3.7.0","security-framework-sys","webpki-root-certs","windows-sys 0.61.2",@@ -5866,6 +6306,38 @@ dependencies = ["zeroize",]+[[package]]+name = "secret-service"+version = "4.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4"+dependencies = [+ "aes",+ "cbc",+ "futures-util",+ "generic-array",+ "hkdf",+ "num",+ "once_cell",+ "rand 0.8.5",+ "serde",+ "sha2",+ "zbus",+]++[[package]]+name = "security-framework"+version = "2.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"+dependencies = [+ "bitflags 2.11.1",+ "core-foundation 0.9.4",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]+[[package]]name = "security-framework"version = "3.7.0"@@ -5976,6 +6448,17 @@ dependencies = ["serde",]+[[package]]+name = "serde_repr"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "serde_spanned"version = "0.6.9"@@ -6086,6 +6569,7 @@ version = "0.1.9"dependencies = ["bindings","futures",+ "hound","indexmap 2.14.0","napi","napi-build",@@ -6763,7 +7247,7 @@ dependencies = ["serde","serde_spanned 0.6.9","toml_datetime 0.6.11",- "toml_edit",+ "toml_edit 0.22.27",][[package]]@@ -6799,6 +7283,15 @@ dependencies = ["serde_core",]+[[package]]+name = "toml_datetime"+version = "1.1.1+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"+dependencies = [+ "serde_core",+]+[[package]]name = "toml_edit"version = "0.22.27"@@ -6813,6 +7306,18 @@ dependencies = ["winnow 0.7.15",]+[[package]]+name = "toml_edit"+version = "0.25.11+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b"+dependencies = [+ "indexmap 2.14.0",+ "toml_datetime 1.1.1+spec-1.1.0",+ "toml_parser",+ "winnow 1.0.1",+]+[[package]]name = "toml_parser"version = "1.1.2+spec-1.1.0"@@ -7027,6 +7532,17 @@ version = "0.1.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"+[[package]]+name = "uds_windows"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"+dependencies = [+ "memoffset",+ "tempfile",+ "windows-sys 0.61.2",+]+[[package]]name = "unarray"version = "0.1.4"@@ -7348,6 +7864,7 @@ dependencies = ["futures-util","indexmap 2.14.0","indicatif",+ "keyring","nagare","napi","napi-build",@@ -7890,6 +8407,24 @@ dependencies = ["windows-targets 0.52.6",]+[[package]]+name = "windows-sys"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"+dependencies = [+ "windows-targets 0.53.5",+]+[[package]]name = "windows-sys"version = "0.61.2"@@ -7938,13 +8473,30 @@ dependencies = ["windows_aarch64_gnullvm 0.52.6","windows_aarch64_msvc 0.52.6","windows_i686_gnu 0.52.6",- "windows_i686_gnullvm",+ "windows_i686_gnullvm 0.52.6","windows_i686_msvc 0.52.6","windows_x86_64_gnu 0.52.6","windows_x86_64_gnullvm 0.52.6","windows_x86_64_msvc 0.52.6",]+[[package]]+name = "windows-targets"+version = "0.53.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"+dependencies = [+ "windows-link",+ "windows_aarch64_gnullvm 0.53.1",+ "windows_aarch64_msvc 0.53.1",+ "windows_i686_gnu 0.53.1",+ "windows_i686_gnullvm 0.53.1",+ "windows_i686_msvc 0.53.1",+ "windows_x86_64_gnu 0.53.1",+ "windows_x86_64_gnullvm 0.53.1",+ "windows_x86_64_msvc 0.53.1",+]+[[package]]name = "windows-threading"version = "0.2.1"@@ -7972,6 +8524,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"+[[package]]+name = "windows_aarch64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"+[[package]]name = "windows_aarch64_msvc"version = "0.42.2"@@ -7990,6 +8548,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"+[[package]]+name = "windows_aarch64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"+[[package]]name = "windows_i686_gnu"version = "0.42.2"@@ -8008,12 +8572,24 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"+[[package]]+name = "windows_i686_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"+[[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_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"+[[package]]name = "windows_i686_msvc"version = "0.42.2"@@ -8032,6 +8608,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"+[[package]]+name = "windows_i686_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"+[[package]]name = "windows_x86_64_gnu"version = "0.42.2"@@ -8050,6 +8632,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"+[[package]]+name = "windows_x86_64_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"+[[package]]name = "windows_x86_64_gnullvm"version = "0.42.2"@@ -8068,6 +8656,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"+[[package]]+name = "windows_x86_64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"+[[package]]name = "windows_x86_64_msvc"version = "0.42.2"@@ -8086,6 +8680,12 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"+[[package]]+name = "windows_x86_64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"+[[package]]name = "winnow"version = "0.7.15"@@ -8100,6 +8700,9 @@ name = "winnow"version = "1.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09dac053f1cd375980747450bfc7250c264eaae0583872e845c0c7cd578872b5"+dependencies = [+ "memchr",+][[package]]name = "wit-bindgen"@@ -8195,6 +8798,16 @@ version = "0.6.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"+[[package]]+name = "xdg-home"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6"+dependencies = [+ "libc",+ "windows-sys 0.59.0",+]+[[package]]name = "xgrammar-rs"version = "0.1.32"@@ -8255,6 +8868,62 @@ dependencies = ["synstructure",]+[[package]]+name = "zbus"+version = "4.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725"+dependencies = [+ "async-broadcast",+ "async-process",+ "async-recursion",+ "async-trait",+ "enumflags2",+ "event-listener",+ "futures-core",+ "futures-sink",+ "futures-util",+ "hex",+ "nix 0.29.0",+ "ordered-stream",+ "rand 0.8.5",+ "serde",+ "serde_repr",+ "sha1",+ "static_assertions",+ "tracing",+ "uds_windows",+ "windows-sys 0.52.0",+ "xdg-home",+ "zbus_macros",+ "zbus_names",+ "zvariant",+]++[[package]]+name = "zbus_macros"+version = "4.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+ "zvariant_utils",+]++[[package]]+name = "zbus_names"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c"+dependencies = [+ "serde",+ "static_assertions",+ "zvariant",+]+[[package]]name = "zerocopy"version = "0.8.48"@@ -8301,6 +8970,20 @@ name = "zeroize"version = "1.8.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"+dependencies = [+ "zeroize_derive",+]++[[package]]+name = "zeroize_derive"+version = "1.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+][[package]]name = "zerotrie"@@ -8364,3 +9047,40 @@ checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"dependencies = ["zune-core",]++[[package]]+name = "zvariant"+version = "4.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe"+dependencies = [+ "endi",+ "enumflags2",+ "serde",+ "static_assertions",+ "zvariant_derive",+]++[[package]]+name = "zvariant_derive"+version = "4.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+ "zvariant_utils",+]++[[package]]+name = "zvariant_utils"+version = "2.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]diff --git a/Cargo.toml b/Cargo.tomlindex 3eb8f5043..8ddbd743a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -14,6 +14,7 @@ members = ["crates/benchmarks","crates/cli","crates/cli-storage",+ "crates/cli-release",]resolver = "3"@@ -128,10 +129,19 @@ base64 = "0.22.1"chrono = { version = "0.4.42", features = ["serde"] }jsonschema = "0.46.0"uniffi = "0.31.0"-napi = { version = "3.8.3", features = ["napi10", "object_indexmap"] }+napi = { version = "3.8.3", features = [+ "napi10",+ "object_indexmap",+ "tokio_rt",+] }napi-derive = "3.5.2"napi-build = "2.3.1"-pyo3 = { version = "0.28.2", features = ["extension-module", "abi3-py38"] }+pyo3 = { version = "0.28.2", features = [+ "extension-module",+ "abi3-py38",+ "experimental-async",+ "multiple-pymethods",+] }wasm-bindgen = { version = "0.2.114", features = ["serde-serialize"] }serde-wasm-bindgen = "0.6.5"wasm-bindgen-futures = "0.4.64"@@ -141,7 +151,21 @@ dirs = "6.0.0"dotenvy = "0.15.7"ratatui = "0.30.0"crossterm = "0.29.0"-async-openai = { version = "0.35.0", features = ["chat-completion", "model", "byot", "responses"] }+async-openai = { version = "0.35.0", features = [+ "chat-completion",+ "model",+ "byot",+ "responses",+] }+hound = "3.5.1"+ignore = "0.4.25"+heck = "0.5.0"+keyring = { version = "3.6.3", features = [+ "apple-native",+ "windows-native",+ "linux-native-sync-persistent",+ "crypto-rust",+] }[profile.dev.build-override]opt-level = 3diff --git a/README.md b/README.mdindex 53f221b85..bce00f5e0 100644--- a/README.md+++ b/README.md@@ -103,27 +103,29 @@ uzu = { git = "https://github.com/trymirai/uzu", branch = "main", package = "uzuThen, create an inference `Session` with a specific model and configuration:```rust-use std::path::PathBuf;--use uzu::session::{- Session,- config::{DecodingConfig, RunConfig},- types::{Input, Output},+use uzu::{+ engine::{Engine, EngineConfig},+ types::session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},};-fn main() -> Result<(), Box<dyn std::error::Error>> {- let model_path = PathBuf::from("MODEL_PATH");- let mut session = Session::new(model_path, DecodingConfig::default())?;-- let input = Input::Text(String::from("Tell about London"));- let output = session.run(- input,- RunConfig::default().tokens_limit(128),- Some(|_: Output| {- return true;- }),- )?;- println!("{}", output.text.original);+#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let config = EngineConfig::default();+ let engine = Engine::new(config).await?;++ let model = engine.model("alibaba:qwen3:0.6b".to_string()).await?.ok_or("Model not found")?;+ while let Some(update) = engine.download(&model).await?.next().await {+ println!("Downloading: {}", update.progress());+ }++ let session = engine.chat(model, ChatConfig::default()).await?;+ let outputs = session+ .reply(vec![ChatMessage::user().with_text("Tell about London".to_string())], ChatReplyConfig::default())+ .await?;+ for output in outputs {+ println!("{}", output.message.text().unwrap_or_default());+ }+Ok(())}```diff --git a/bindings/ts-napi/.gitignore b/bindings/ts-napi/.gitignorenew file mode 100644index 000000000..40b878db5--- /dev/null+++ b/bindings/ts-napi/.gitignore@@ -0,0 +1 @@+node_modules/\ No newline at end of filediff --git a/bindings/ts-napi/.node-version b/bindings/ts-napi/.node-versionnew file mode 100644index 000000000..2edeafb09--- /dev/null+++ b/bindings/ts-napi/.node-version@@ -0,0 +1 @@+20\ No newline at end of filediff --git a/bindings/ts-napi/package.json b/bindings/ts-napi/package.jsonnew file mode 100644index 000000000..a3526a46a--- /dev/null+++ b/bindings/ts-napi/package.json@@ -0,0 +1,28 @@+{+ "name": "@trymirai/uzu-napi",+ "version": "0.0.0",+ "private": false,+ "main": "uzu.node",+ "types": "uzu.d.ts",+ "packageManager": "[email protected]",+ "devDependencies": {+ "@napi-rs/cli": "3.1.2",+ "@types/node": "24.2.0",+ "ts-node": "10.9.2",+ "typescript": "5.9.2"+ },+ "napi": {+ "binaryName": "uzu"+ },+ "os": [+ "darwin"+ ],+ "cpu": [+ "arm64"+ ],+ "files": [+ "uzu.node",+ "uzu.d.ts",+ "package.json"+ ]+}\ No newline at end of filediff --git a/bindings/ts-napi/pnpm-lock.yaml b/bindings/ts-napi/pnpm-lock.yamlnew file mode 100644index 000000000..2dd0fd99b--- /dev/null+++ b/bindings/ts-napi/pnpm-lock.yaml@@ -0,0 +1,1400 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++importers:++ .:+ devDependencies:+ '@napi-rs/cli':+ specifier: 3.1.2+ version: 3.1.2(@emnapi/[email protected])(@types/[email protected])+ '@types/node':+ specifier: 24.2.0+ version: 24.2.0+ ts-node:+ specifier: 10.9.2+ version: 10.9.2(@types/[email protected])([email protected])+ typescript:+ specifier: 5.9.2+ version: 5.9.2++packages:++ '@cspotcode/[email protected]':+ resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}+ engines: {node: '>=12'}++ '@emnapi/[email protected]':+ resolution: {integrity: sha512-XsLw1dEOpkSX/WucdqUhPWP7hDxSvZiY+fsUC14h+FtQ2Ifni4znbBt8punRX+Uj2JG/uDb8nEHVKvrVlvdZ5Q==}++ '@emnapi/[email protected]':+ resolution: {integrity: sha512-++LApOtY0pEEz1zrd9vy1/zXVaVJJ/EbAF3u0fXIzPJEDtnITsBGbbK0EkM72amhl/R5b+5xx0Y/QhcVOpuulg==}++ '@emnapi/[email protected]':+ resolution: {integrity: sha512-PJR+bOmMOPH8AtcTGAyYNiuJ3/Fcoj2XN/gBEWzDIKh254XO+mM9XoXHk5GNEhodxeMznbg7BlRojVbKN+gC6g==}++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-fdSw07FLJEU5vbpOPzXo5c6xmMGDzbZE2+niuDHX5N6mc6V0Ebso/q3xiHra4D73+PMsC8MJmcaZKuAAoaQsSA==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-5yR4IBfe0kXe59r1YCTG8WXkUbl7Z35HK87Sw+WUyGD8wNUx7JvY7laahzeytyE1oLn74bQnL7hstctQxisQ8Q==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-8xrp836RZvKkpNbVvgWUlxjT4CraKk2q+I3Ksy+seI2zkcE+y6wNs1BVhgcv8VyImFecUhdQrYLdW32pAjwBdA==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-wst31XT8DnGOSS4nNJDIklGKnf+8shuauVrWzgKegWUe28zfCftcWZ2vktGdzJgcylWSS2SrDnYUb6alZcwnCQ==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-PSqy9VmJx/VbE3CT453yOfNa+PykpKg/0SYP7odez1/NWBGuDXgPhp4AeGYYKjhLn5lUUavVS/JbeYMPdH50Mw==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-lGPVU3yO9ZNqA7vTYz26jny41lE7yoQansmqdMLBEfqaGsmdg7V3W9mK9Pvb5IL4EVZ9GnSDGMO/cJXud5dMaw==}+ engines: {node: '>=18'}++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-tVC+O1rBl0lJpoUZv4xY+WGWY8V5b0zxU1XDsMsIHYregdh7bN5X5QnIONNBAl0K765FYlAfNHS2Bhn7SSOVow==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-GcvGHkyIgfZgVnnimURdOueMk0CztycfC8NZTiIY9arIAkeOgt6zG57G+7vC59Jns3UX27LMkPKnKWAOF5xEYg==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-DJolTnNeZ00E1+1TW+8614F7rOJJCM4y4BAGQ3Gq6kQIG+OJ4zr3GLjIjVVJCbKsk2jmkmv6v2kQuN/vriHdZA==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-JHwGbQ6wjf1dxxnalDYpZwZxUEosT+6CPGD9Zh4sm9WXdtUp9XODCQD3NjSTmu+0OAyxWXNOqf0spjIymJa2Tw==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-R5qMyGJqtDdi4Ht521iAkNqyB6p2UPuZUbMifakg1sWtu24gc2Z8CJuw8rP081OckNDMgtDCuLe42Q2Kr3BolA==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-PMk1+O/WBcYJDq2H7foV0aAZSmDdkzZB9Mw2v/DmONRJopwA/128cS9M/TXWLKKdEQKZnKwBzqu2G4x/2Nqx8Q==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-Gfl/5sqOF5vS/LIrSndFgOh7jgoe0UXEizDqahFRkq5aJBLegZ6WjuMh/hVEJwlFQjyLq1z9fRtvUMkb7jM1LA==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@inquirer/[email protected]':+ resolution: {integrity: sha512-lg9Whz8onIHRthWaN1Q9EGLa/0LFJjyM8mEUbL1eTi6yMGvBf8gvyDLtxSXztQsxMvhxxNpJYrwa1YHdq+w4Jw==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/node': '>=18'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}+ engines: {node: '>=6.0.0'}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-VT2+G1VQs/9oz078bLrYbecdZKs912zQlkelYpuf+SXF+QvZDYJlbx/LSx+meSAwdDFnF8FVXW92AVjjkVmgFw==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==}++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-i0HT3Ja83Bzy+OtLd2eG7MI6E83+z/iwwzrdCjJ3ZiSpT3uE/xpVrLuZPd3MT5dJ9LAxCPN+P0tAPF32pRErUg==}+ engines: {node: '>= 16'}+ hasBin: true+ peerDependencies:+ '@emnapi/runtime': ^1.1.0+ emnapi: ^1.1.0+ peerDependenciesMeta:+ '@emnapi/runtime':+ optional: true+ emnapi:+ optional: true++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-5Ha9SkZC8NjLB4Xe6C9v+3c+Oraz9FdbuN2L4d/mh1kTK8Y/zGt5geM/U+sboAP3HoK2aRWRnx4GK0eV3oPoUQ==}+ peerDependencies:+ '@napi-rs/cross-toolchain-arm64-target-aarch64': ^1.0.0+ '@napi-rs/cross-toolchain-arm64-target-armv7': ^1.0.0+ '@napi-rs/cross-toolchain-arm64-target-x86_64': ^1.0.0+ '@napi-rs/cross-toolchain-x64-target-aarch64': ^1.0.0+ '@napi-rs/cross-toolchain-x64-target-armv7': ^1.0.0+ '@napi-rs/cross-toolchain-x64-target-x86_64': ^1.0.0+ peerDependenciesMeta:+ '@napi-rs/cross-toolchain-arm64-target-aarch64':+ optional: true+ '@napi-rs/cross-toolchain-arm64-target-armv7':+ optional: true+ '@napi-rs/cross-toolchain-arm64-target-x86_64':+ optional: true+ '@napi-rs/cross-toolchain-x64-target-aarch64':+ optional: true+ '@napi-rs/cross-toolchain-x64-target-armv7':+ optional: true+ '@napi-rs/cross-toolchain-x64-target-x86_64':+ optional: true++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-smZtN41ebtYw+vxn1q3IXhns1hUzFNUcgHxknZKFQSKaybYZ4KxMiiBIw5UqJ9rw1dkaHqokcC1YeAfu8vfG2A==}+ engines: {node: '>= 10'}+ cpu: [arm]+ os: [android]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-s+h9bM3Z31FL0IPfWF4kBCebWxJBtpFvje6ikzmeUg1/jjWAP81IJC5j75zz5TEWt+Zf3Bip0uVlQhCZmqlpKA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [android]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-aF5wxA0SFlRalxeyz7TpmFuztHlG9D0qew+1gz0tiRs4gituT3CCsR0PSBZ2LbalTY/7RqmYP4ssLQus+p8tqg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-80gD9kvXPPBz6V4C7SXcPo0o7ySlneDVRpebAHN1DubIEwhdrMFuqmtaATwT5MTraZSrQ4CHF275MQuwiHtlGw==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-wd+jwYQRIzkGtUvInYLWSrqRtDatIvwNm/w9k43f+oABBsnP4veJkyKGGm4SQQa35Ki8IXVzYdGTa4eSTi+Org==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [freebsd]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-KiMgBugjFQfgeZTebuBVHL8ta/nZ2cfzd0Jge0e0y/WX/p7ZkVyCox/TTu9EU2H9OeBAFKTRmIDoqhHlBbkqyA==}+ engines: {node: '>= 10'}+ cpu: [arm]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-l0T2fKeDqnczeNFqFsE8W2+J7386BGaHCbD409sDGOUW3Fhn9FlHkkC4qAnWhieaLqCdnorj+LQAzYM371IXrQ==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-rm43dqf5pw5HV3EineWl4IBbzg3Iwuiucl614AyhLHmSHTf6/AJJID7rqwM8Qbhe2abM+9NT+2WI9HRM1ZtkJA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-QzNVcCdq6j4LYOtLUDEyE9wg8tY8kmbQ6TZrqjYQUD2nebTW24lmzFhdeI3xzUzVN5rRt4js1UnL1cPCT5HrSw==}+ engines: {node: '>= 10'}+ cpu: [ppc64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-7jpyKpBX0LpklkmGBzz1cQJ/QRN+E6h1xSZVeN6KCtLBrCd6LCX3owZMRzSYmdpI6Zr30DrWo0HOUZiKMzgzBg==}+ engines: {node: '>= 10'}+ cpu: [riscv64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-ngUxVZIytn2UHY92RnijtT11VhWO32mfa1LFX03GWMWdQl50bV/IqcZR0WYRWlBCd7DZrOf16AY2IR/lwovE7A==}+ engines: {node: '>= 10'}+ cpu: [s390x]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-mUGH8hpWJU4FXhn61cD7sHTUEBiWU5JYOhh6ErCIZ0BOoBH/0kYPptfqvJA6G9EfVIcfbtYKxJYYtFC5sbf+eA==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-ysM4mYSfWGO2h8YZVn0GH7zMZX42hU0h7IomC4/oBJmAk5BIlOGnRB8XQmyz1A7neSi6aByjAlZmW4CrZlI9Uw==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-MyDIU8a6jJqhK4L1ISFrb9OeKaGlI3FptCo2JFoEWYaenWHRwEepFqkyuECeIe34xtU2jtJcpXhEtpnCxuAE1Q==}+ engines: {node: '>=14.0.0'}+ cpu: [wasm32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-GqoJu7iL7OTqkBQGLps7rXQHZ5sdcZF7tOY06rlYO03ZNkUCjhNpmkuUsPXVnGstqgoGwzMNW6TcSsO/YWotEw==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-cnExNqWKl0JkLcKlFVuqUrTuQsYP8nstWGT3fz7mPhgqHFOgGmd1l9tDFhqgul7Kt0QTddZRbKl6jlkV7DjSQw==}+ engines: {node: '>= 10'}+ cpu: [ia32]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-15SoQgMgktF73ZnLQPkzCwtxyQ+4VuD8n5Puis1H48QRjUNnXXpqTGFyWdLPdd14vcxbndgcYvJtSjOXTfNHiw==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-C53oqFQESm5XkjFKJpXtBXYm2ZiwvrQrsgM1K+/itmSXyQYa4NpB7m0W/peF8riXpxHUt6ycOeMK9rp2enTchQ==}+ engines: {node: '>= 10'}++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-oEntU16IkWykPJnSwv/VIICzIt2SwEsz45z2Ab+EXOas10EB+pu0z31AiSNI5pr1CaJcadbf1JGMI9aOtbAuRQ==}+ engines: {node: '>= 10'}+ cpu: [arm]+ os: [android]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-b2X7nQ/wH2VGzzl4KhVOR/gHqxIuqrUjMY8VKJYxAGdCrmUPRfc47kersiu6DG706kSv9T+BxeeUQvwqnXZRXQ==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [android]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-m1Ug1452/DOUbJGSuJuHRTUCBQOXY0arGqXCHuSiaQhBQQjgBhlbHWCv291gV8CytFYd5lvSyiG2gFUU26Qd7A==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-1RiC53g1y4pxX7P2L9sbZcqsw6dfXvGnTNwXHDjg4ATZncZa7uoPUWa7aHAGcQm8ZBO4P0ICt2SHOepstDWWTg==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-uLaYn+eO3ZY2ojbohdlRFcuqYP+j2alovtuLdFvCzzsArg4DSnmcJvEQ+I4l99lfyThYB1c8GA64oxSOfmn/UA==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [freebsd]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-PhGIaT45i1Fj5iY6NiWYTLPUOHb7rXiwnqKhco+IXOeIclaGcEVoAbhrLiLGQrfv9viLdyhzAxECoOr+zKnApw==}+ engines: {node: '>= 10'}+ cpu: [arm]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-syDburynsi2WxhD0hVUfNDpRowG+3Luiv2BKiYOUEwMZy6E/By1vQCn2NbLAqoPxaE9N/4Cp3xcW+Hn+CZ2EFA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-KlrlAxNaZbWvGKgr4g4Cm5dRdwlogBaF3fvysaqR0kT8pA4ODBHtjsbx+ErhrQNDfg6QZIEfmFn3lrsTG/lqUA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-IbB4I8RFcvKI/zGsboUQPmlKoXfXgNOMiJw7Cbe7T1OBeYzDy6n/yEUEaG4zIbocxqjRVsF4ElrW1V/0Ihlqzg==}+ engines: {node: '>= 10'}+ cpu: [ppc64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-Tl4HSo07u3TLsNQ4KEVfYKdHVNfF/k0o5KQlyGnePiO34Kb+NfaqSKMspjSkrmXKEc0PjB+u9af3BZdTUwml4Q==}+ engines: {node: '>= 10'}+ cpu: [s390x]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-Xe57Yz4MKSeG6HGECiIHuBKFwAuqs2fzwblTdMd1CoSgaaUc/K/dKTDWZwPtjC0Hh5pM86K0WZuwggbsjmFGNg==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-VA4RXspXyelNAtaFEf2ZLnTYXRILVlH20OGV0oqzuUcQzpwEwK2cJbYtYHK+yCYpxrNbEGsAwN+12LYJMW+NlA==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-yPMq3jMldKOi6rbbhKp+7zfaRsA2toIfRV7TbqSzwz64S5euiMrsZQcrq3F9oTtFu4wCSLo83IsNdgoVuiy44g==}+ engines: {node: '>=14.0.0'}+ cpu: [wasm32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-VdUjZK8jh6mvGRiurK3ms6Yt2hbBbtYjzKCn78Mnme2KGC585Kx1jXl7HShvreCgqh3r0162OSygoE7d/I0Jlw==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-8d/4iRXROPXLoe+4FEqXkpgP2KD9A45VUf76WfT6nXZwzQuoh+9WCJNRPVs5vfXV1SMnG9Z32WNc2ivCq0+HZw==}+ engines: {node: '>= 10'}+ cpu: [ia32]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-HHtL1g0niVa4xDvyfi9wQtCTDDKkhDlaOb3bmayTqWs29mk+pcVHBST3OdXaaViSaduqdG9meosU5sOj5iKQAQ==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-4sE8bFyOQFKcjWwBoBMtB+YIgKTqQFOFQZWKJP54jENpFulw8cieBaYoA3bbKCCFxXl2jCFulFKDtDErPWULTg==}+ engines: {node: '>= 10'}++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-KVlQ/jgywZpixGCKMNwxStmmbYEMyokZpCf2YuIChhfJA2uqfAKNEM8INz7zzTo55iEXfBhIIs3VqYyqzDLj8g==}++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-Ks0hplmrYatIjSi8XeTObCi0x13AOQD41IQXpBjrz+UK71gDkbxyLWO7B/ckuels3mC1DW3OCQCv+q0lPnaG/A==}+ engines: {node: '>= 10'}+ cpu: [arm]+ os: [android]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-Ppu1/YGLSC/ohkOA8R5YfDh1dCuCHWJObu/BTorAY55YDXIiWy400CoungbYwoRT53K+ixNrg8/zRHnpuqwkRg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [android]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-EUU7NvmmKASMLecu7hUHhv9XN2Thf8j+2/zCCMuFuAAlY+eZiOVfrajbZ/RE8CZ4oyfkb0bWFg/CQcmcXAatTw==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-hlX21sqy0AEnmn2abarmCXV3fpyIQN+fKqeHNuawti9ZpaJCL6gZCtUGqpUxURjXNjXSI8rywInJE2YmeVQSJQ==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-T9SOSfIgrdEGQzzquKMOfD3PF6TxG5hL2o5voZtLUALA0yjO+GnpFyv8tAcxKYd7ngWzzK5Uwk7e1z9PcsQZMg==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [freebsd]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-qHNLY0GLTZK8M/cQOy2OAaRDfk3YOlWAwlAO4KSIAseuXHAaGya3Ay//kbmwzzs8h6TKf/eAeXDwcGxze5ecxw==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-54BWWTg5I9n77PRUKErBe3BKqkmbjm0GRpUKJgGdlcessC9Oxa/yVDy2BPtmJP1pQR3VabkXR63H+ZGaH5qKxw==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-wpRkiy0QBM/zpaGAn5I1HfddQul0vGrdlindT2UHtOYK1zvam524M6LJXBtmhBkXS5a4F2HZiZXns8Wuc7dq4w==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-Ua94ruWB18uKyIz/nj+by2ZxfBbFzbqiiD564ocBHGbrUffpR6Us74uVwxO7rImc/WvCfJqap9ezqmaTvmK7SA==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-gWVdt1UK575VKTnFRcYTe0qMZA5bFV2w69qDAhX8hG6tajjxbVyvu4jgsYvv/bJrBrxFsNbXMlEU1d0X7iWziA==}+ engines: {node: '>=14.0.0'}+ cpu: [wasm32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-1kv+DM7z6c9OLcjMtO1/kfdxS5hwXtW1OLIHBU41dtKz5jD3quapYrCjB7AVEZh/JVM765UaLOl31huVucJjRw==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-OwcyXtU2Zi3YVHYjmomM3u7jRNPY1j+IPehqCVEqd60jOTOXRZNPGoAvOC7Lw6HX/RGzOJnIcJZbVfKrz5WN1g==}+ engines: {node: '>= 10'}+ cpu: [ia32]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-xat6gnp/G/WCe6U6HKzawotz9zpqsM5a+Dx+S0MPX4AKP7+oztC2/6tkp8KtOPT2bMRMekNntXadHKk0XqW61Q==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-GL43zmDN6AFmomd7eTJOdZkXDvocucjqJcBs/IY51ZTxHvBeb1SXTM0/rI2VJ7C3FTiyATTt2D8chonCi0UTgw==}+ engines: {node: '>= 10'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-oNXsh2ywth5aowwIa7RKtawnkdH6LgU1ztfP9AIUCQCvzysB+WeU8o2kyyosDPwBZutPpjZDKPQGIzzrfTWweQ==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-hoYicJZaqISMAI3JfaDr1qMNi48OctWuOih1m80bkYow/ayPw6Jj52tqWJ6GEoFTk1gBqfanSoI1iY99Z5+ekQ==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-j1nQNU1ZxNFx2ZtKmL4sMrs4egy5h65OMDmSbVyuCzjOcwsHq6EaYjOTGXPQxgfiN8dJ4CriYHk6zF050WEULg==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-idsIggNXUKkk0+BExUn1dQ92sfysJrje03Q0bv0e+KPLrvyqZF8MnBpFz8UNfYDwB3Ie7Z0TByjWfzxt7vseaA==}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-q9iQGlZlxAVNRN2jDNskJW/Cafy7/XE52wjZ5TTvyhyOD904Cvx//DNyoO3J/MXJ0ve3rPoNWKEg5iZrisQSuw==}+ engines: {node: '>= 20'}+ peerDependencies:+ '@octokit/core': '>=6'++ '@octokit/[email protected]':+ resolution: {integrity: sha512-UkOzeEN3W91/eBq9sPZNQ7sUBvYCqYbrrD8gTbBuGtHEuycE4/awMXcYvx6sVYo7LypPhmQwwpUe4Yyu4QZN5Q==}+ engines: {node: '>= 20'}+ peerDependencies:+ '@octokit/core': '>=6'++ '@octokit/[email protected]':+ resolution: {integrity: sha512-kJVUQk6/dx/gRNLWUnAWKFs1kVPn5O5CYZyssyEoNYaFedqZxsfYs7DwI3d67hGz4qOwaJ1dpm07hOAD1BXx6g==}+ engines: {node: '>= 20'}+ peerDependencies:+ '@octokit/core': '>=6'++ '@octokit/[email protected]':+ resolution: {integrity: sha512-KRA7VTGdVyJlh0cP5Tf94hTiYVVqmt2f3I6mnimmaVz4UG3gQV/k4mDJlJv3X67iX6rmN7gSHCF8ssqeMnmhZg==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-V6jhKokg35vk098iBqp2FBKunk3kMTXlmq+PtbV9Gl3TfskWlebSofU9uunVKhUN7xl+0+i5vt0TGTG8/p/7HA==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-z6tmTu9BTnw51jYGulxrlernpsQYXpui1RK21vmXn8yF5bp6iX16yfTtJYGK5Mh1qDkvDOmp2n8sRMcQmR8jiA==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-1y6DgTy8Jomcpu33N+p5w58l6xyt55Ar2I91RPiIA0xCJBXyUAhXCcmZaDWSANiha7R9a6qJJ2CRomGPZ6f46g==}++ '@tsconfig/[email protected]':+ resolution: {integrity: sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==}++ '@tsconfig/[email protected]':+ resolution: {integrity: sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==}++ '@tsconfig/[email protected]':+ resolution: {integrity: sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==}++ '@tsconfig/[email protected]':+ resolution: {integrity: sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==}++ '@tybys/[email protected]':+ resolution: {integrity: sha512-VyyPYFlOMNylG45GoAe0xDoLwWuowvf92F9kySqzYh8vmYm7D2u4iUJKa1tOUpS70Ku13ASrOkS4ScXFsTaCNQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-3xyG3pMCq3oYCNg7/ZP+E1ooTaGB4cG8JWRsqqOYQdbWNY4zbaV0Ennrd7stjiJEFZCaybcIgpTjJWHRfBSIDw==}++ resolution: {integrity: sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==}+ engines: {node: '>=0.4.0'}++ resolution: {integrity: sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==}+ engines: {node: '>=0.4.0'}+ hasBin: true++ resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==}++ resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}++ resolution: {integrity: sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==}++ resolution: {integrity: sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==}++ resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==}+ engines: {node: '>= 12'}++ resolution: {integrity: sha512-CXkMQxU6s9GklO/1f714dkKBMu1lopS1WFF0B8o4AxPykR1hpozxSiUZ5ZUeBjfPgCWqbcNOtZVFhB8Lkfp1+Q==}+ peerDependencies:+ typanion: '*'++ resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}+ engines: {node: '>=7.0.0'}++ resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}++ resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==}++ resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==}++ resolution: {integrity: sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==}+ engines: {node: '>=6.0'}+ peerDependencies:+ supports-color: '*'+ peerDependenciesMeta:+ supports-color:+ optional: true++ resolution: {integrity: sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==}+ engines: {node: '>=0.3.1'}++ resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}++ resolution: {integrity: sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==}+ engines: {node: '>=4'}++ resolution: {integrity: sha512-ZvLdcY8P+N8mGQJahJV5G4U88CSvT1rP8ApL6uETe88MBXrBHAkZlSEySdUlyztF7ccb+Znos3TFqaepHxdhBg==}++ resolution: {integrity: sha512-YyZM99iHrqLKjmt4LJDj58KI+fYyufRLBSYcqycxf//KpBk9FoewoGX0450m9nB44qrZnovzC2oeP5hUibxc/g==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==}+ hasBin: true++ resolution: {integrity: sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==}++ resolution: {integrity: sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==}++ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}++ resolution: {integrity: sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA==}+ engines: {node: ^18.17.0 || >=20.5.0}++ resolution: {integrity: sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}++ resolution: {integrity: sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==}+ engines: {node: '>=10'}+ hasBin: true++ resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}+ engines: {node: '>=14'}++ resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==}+ engines: {node: '>=0.6.0'}++ resolution: {integrity: sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==}+ hasBin: true+ peerDependencies:+ '@swc/core': '>=1.2.50'+ '@swc/wasm': '>=1.2.50'+ '@types/node': '*'+ typescript: '>=2.7'+ peerDependenciesMeta:+ '@swc/core':+ optional: true+ '@swc/wasm':+ optional: true++ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}++ resolution: {integrity: sha512-ZW/lVMRabETuYCd9O9ZvMhAh8GslSqaUjxmK/JLPCh6l73CvLBiuXswj/+7LdnWOgYsQ130FqLzFz5aGT4I3Ug==}++ resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==}+ engines: {node: '>=14.17'}+ hasBin: true++ resolution: {integrity: sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag==}++ resolution: {integrity: sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A==}++ resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==}++ resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-AyeEbWOu/TAXdxlV9wmGcR0+yh2j3vYPGOECcIj2S7MkrLyC7ne+oye2BKTItt0ii2PHk4cDy+95+LshzbXnGg==}+ engines: {node: '>=12.20'}++ resolution: {integrity: sha512-cYVsTjKl8b+FrnidjibDWskAv7UKOfcwaVZdp/it9n1s9fU3IkgDbhdIRKCW4JDsAlECJY0ytoVPT3sK6kideA==}+ engines: {node: '>=18'}++snapshots:++ '@cspotcode/[email protected]':+ dependencies:+ '@jridgewell/trace-mapping': 0.3.9++ '@emnapi/[email protected]':+ dependencies:+ '@emnapi/wasi-threads': 1.0.4+ tslib: 2.8.1+ optional: true++ '@emnapi/[email protected]':+ dependencies:+ tslib: 2.8.1+ optional: true++ '@emnapi/[email protected]':+ dependencies:+ tslib: 2.8.1+ optional: true++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/core': 10.1.15(@types/[email protected])+ '@inquirer/figures': 1.0.13+ '@inquirer/type': 3.0.8(@types/[email protected])+ ansi-escapes: 4.3.2+ yoctocolors-cjs: 2.1.2+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/core': 10.1.15(@types/[email protected])+ '@inquirer/type': 3.0.8(@types/[email protected])+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/figures': 1.0.13+ '@inquirer/type': 3.0.8(@types/[email protected])+ ansi-escapes: 4.3.2+ cli-width: 4.1.0+ mute-stream: 2.0.0+ signal-exit: 4.1.0+ wrap-ansi: 6.2.0+ yoctocolors-cjs: 2.1.2+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/core': 10.1.15(@types/[email protected])+ '@inquirer/type': 3.0.8(@types/[email protected])+ external-editor: 3.1.0+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/core': 10.1.15(@types/[email protected])+ '@inquirer/type': 3.0.8(@types/[email protected])+ yoctocolors-cjs: 2.1.2+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected]': {}++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/core': 10.1.15(@types/[email protected])+ '@inquirer/type': 3.0.8(@types/[email protected])+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/core': 10.1.15(@types/[email protected])+ '@inquirer/type': 3.0.8(@types/[email protected])+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/core': 10.1.15(@types/[email protected])+ '@inquirer/type': 3.0.8(@types/[email protected])+ ansi-escapes: 4.3.2+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/checkbox': 4.2.0(@types/[email protected])+ '@inquirer/confirm': 5.1.14(@types/[email protected])+ '@inquirer/editor': 4.2.15(@types/[email protected])+ '@inquirer/expand': 4.0.17(@types/[email protected])+ '@inquirer/input': 4.2.1(@types/[email protected])+ '@inquirer/number': 3.0.17(@types/[email protected])+ '@inquirer/password': 4.0.17(@types/[email protected])+ '@inquirer/rawlist': 4.1.5(@types/[email protected])+ '@inquirer/search': 3.1.0(@types/[email protected])+ '@inquirer/select': 4.3.1(@types/[email protected])+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/core': 10.1.15(@types/[email protected])+ '@inquirer/type': 3.0.8(@types/[email protected])+ yoctocolors-cjs: 2.1.2+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/core': 10.1.15(@types/[email protected])+ '@inquirer/figures': 1.0.13+ '@inquirer/type': 3.0.8(@types/[email protected])+ yoctocolors-cjs: 2.1.2+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/core': 10.1.15(@types/[email protected])+ '@inquirer/figures': 1.0.13+ '@inquirer/type': 3.0.8(@types/[email protected])+ ansi-escapes: 4.3.2+ yoctocolors-cjs: 2.1.2+ optionalDependencies:+ '@types/node': 24.2.0++ '@inquirer/[email protected](@types/[email protected])':+ optionalDependencies:+ '@types/node': 24.2.0++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/resolve-uri': 3.1.2+ '@jridgewell/sourcemap-codec': 1.5.4++ dependencies:+ '@inquirer/prompts': 7.8.0(@types/[email protected])+ '@napi-rs/cross-toolchain': 1.0.0+ '@napi-rs/wasm-tools': 1.0.0+ '@octokit/rest': 22.0.0+ clipanion: 4.0.0-rc.4([email protected])+ colorette: 2.0.20+ debug: 4.4.1+ find-up: 7.0.0+ js-yaml: 4.1.0+ lodash-es: 4.17.21+ semver: 7.7.2+ typanion: 3.14.0+ optionalDependencies:+ '@emnapi/runtime': 1.4.5+ transitivePeerDependencies:+ - '@napi-rs/cross-toolchain-arm64-target-aarch64'+ - '@napi-rs/cross-toolchain-arm64-target-armv7'+ - '@napi-rs/cross-toolchain-arm64-target-x86_64'+ - '@napi-rs/cross-toolchain-x64-target-aarch64'+ - '@napi-rs/cross-toolchain-x64-target-armv7'+ - '@napi-rs/cross-toolchain-x64-target-x86_64'+ - '@types/node'+ - supports-color++ '@napi-rs/[email protected]':+ dependencies:+ '@napi-rs/lzma': 1.4.4+ '@napi-rs/tar': 1.0.0+ debug: 4.4.1+ transitivePeerDependencies:+ - supports-color++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ dependencies:+ '@napi-rs/wasm-runtime': 1.0.1+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optionalDependencies:+ '@napi-rs/lzma-android-arm-eabi': 1.4.4+ '@napi-rs/lzma-android-arm64': 1.4.4+ '@napi-rs/lzma-darwin-arm64': 1.4.4+ '@napi-rs/lzma-darwin-x64': 1.4.4+ '@napi-rs/lzma-freebsd-x64': 1.4.4+ '@napi-rs/lzma-linux-arm-gnueabihf': 1.4.4+ '@napi-rs/lzma-linux-arm64-gnu': 1.4.4+ '@napi-rs/lzma-linux-arm64-musl': 1.4.4+ '@napi-rs/lzma-linux-ppc64-gnu': 1.4.4+ '@napi-rs/lzma-linux-riscv64-gnu': 1.4.4+ '@napi-rs/lzma-linux-s390x-gnu': 1.4.4+ '@napi-rs/lzma-linux-x64-gnu': 1.4.4+ '@napi-rs/lzma-linux-x64-musl': 1.4.4+ '@napi-rs/lzma-wasm32-wasi': 1.4.4+ '@napi-rs/lzma-win32-arm64-msvc': 1.4.4+ '@napi-rs/lzma-win32-ia32-msvc': 1.4.4+ '@napi-rs/lzma-win32-x64-msvc': 1.4.4++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ dependencies:+ '@napi-rs/wasm-runtime': 1.0.1+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optionalDependencies:+ '@napi-rs/tar-android-arm-eabi': 1.0.0+ '@napi-rs/tar-android-arm64': 1.0.0+ '@napi-rs/tar-darwin-arm64': 1.0.0+ '@napi-rs/tar-darwin-x64': 1.0.0+ '@napi-rs/tar-freebsd-x64': 1.0.0+ '@napi-rs/tar-linux-arm-gnueabihf': 1.0.0+ '@napi-rs/tar-linux-arm64-gnu': 1.0.0+ '@napi-rs/tar-linux-arm64-musl': 1.0.0+ '@napi-rs/tar-linux-ppc64-gnu': 1.0.0+ '@napi-rs/tar-linux-s390x-gnu': 1.0.0+ '@napi-rs/tar-linux-x64-gnu': 1.0.0+ '@napi-rs/tar-linux-x64-musl': 1.0.0+ '@napi-rs/tar-wasm32-wasi': 1.0.0+ '@napi-rs/tar-win32-arm64-msvc': 1.0.0+ '@napi-rs/tar-win32-ia32-msvc': 1.0.0+ '@napi-rs/tar-win32-x64-msvc': 1.0.0++ '@napi-rs/[email protected]':+ dependencies:+ '@emnapi/core': 1.4.5+ '@emnapi/runtime': 1.4.5+ '@tybys/wasm-util': 0.10.0+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ dependencies:+ '@napi-rs/wasm-runtime': 1.0.1+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optionalDependencies:+ '@napi-rs/wasm-tools-android-arm-eabi': 1.0.0+ '@napi-rs/wasm-tools-android-arm64': 1.0.0+ '@napi-rs/wasm-tools-darwin-arm64': 1.0.0+ '@napi-rs/wasm-tools-darwin-x64': 1.0.0+ '@napi-rs/wasm-tools-freebsd-x64': 1.0.0+ '@napi-rs/wasm-tools-linux-arm64-gnu': 1.0.0+ '@napi-rs/wasm-tools-linux-arm64-musl': 1.0.0+ '@napi-rs/wasm-tools-linux-x64-gnu': 1.0.0+ '@napi-rs/wasm-tools-linux-x64-musl': 1.0.0+ '@napi-rs/wasm-tools-wasm32-wasi': 1.0.0+ '@napi-rs/wasm-tools-win32-arm64-msvc': 1.0.0+ '@napi-rs/wasm-tools-win32-ia32-msvc': 1.0.0+ '@napi-rs/wasm-tools-win32-x64-msvc': 1.0.0++ '@octokit/[email protected]': {}++ '@octokit/[email protected]':+ dependencies:+ '@octokit/auth-token': 6.0.0+ '@octokit/graphql': 9.0.1+ '@octokit/request': 10.0.3+ '@octokit/request-error': 7.0.0+ '@octokit/types': 14.1.0+ before-after-hook: 4.0.0+ universal-user-agent: 7.0.3++ '@octokit/[email protected]':+ dependencies:+ '@octokit/types': 14.1.0+ universal-user-agent: 7.0.3++ '@octokit/[email protected]':+ dependencies:+ '@octokit/request': 10.0.3+ '@octokit/types': 14.1.0+ universal-user-agent: 7.0.3++ '@octokit/[email protected]': {}++ '@octokit/[email protected](@octokit/[email protected])':+ dependencies:+ '@octokit/core': 7.0.3+ '@octokit/types': 14.1.0++ '@octokit/[email protected](@octokit/[email protected])':+ dependencies:+ '@octokit/core': 7.0.3++ '@octokit/[email protected](@octokit/[email protected])':+ dependencies:+ '@octokit/core': 7.0.3+ '@octokit/types': 14.1.0++ '@octokit/[email protected]':+ dependencies:+ '@octokit/types': 14.1.0++ '@octokit/[email protected]':+ dependencies:+ '@octokit/endpoint': 11.0.0+ '@octokit/request-error': 7.0.0+ '@octokit/types': 14.1.0+ fast-content-type-parse: 3.0.0+ universal-user-agent: 7.0.3++ '@octokit/[email protected]':+ dependencies:+ '@octokit/core': 7.0.3+ '@octokit/plugin-paginate-rest': 13.1.1(@octokit/[email protected])+ '@octokit/plugin-request-log': 6.0.0(@octokit/[email protected])+ '@octokit/plugin-rest-endpoint-methods': 16.0.0(@octokit/[email protected])++ '@octokit/[email protected]':+ dependencies:+ '@octokit/openapi-types': 25.1.0++ '@tsconfig/[email protected]': {}++ '@tsconfig/[email protected]': {}++ '@tsconfig/[email protected]': {}++ '@tsconfig/[email protected]': {}++ '@tybys/[email protected]':+ dependencies:+ tslib: 2.8.1+ optional: true++ '@types/[email protected]':+ dependencies:+ undici-types: 7.10.0++ dependencies:+ acorn: 8.15.0++ [email protected]: {}++ dependencies:+ type-fest: 0.21.3++ [email protected]: {}++ dependencies:+ color-convert: 2.0.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ typanion: 3.14.0++ dependencies:+ color-name: 1.1.4++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ ms: 2.1.3++ [email protected]: {}++ [email protected]: {}++ dependencies:+ chardet: 0.7.0+ iconv-lite: 0.4.24+ tmp: 0.0.33++ [email protected]: {}++ dependencies:+ locate-path: 7.2.0+ path-exists: 5.0.0+ unicorn-magic: 0.1.0++ dependencies:+ safer-buffer: 2.1.2++ [email protected]: {}++ dependencies:+ argparse: 2.0.1++ dependencies:+ p-locate: 6.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ yocto-queue: 1.2.1++ dependencies:+ p-limit: 4.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ emoji-regex: 8.0.0+ is-fullwidth-code-point: 3.0.0+ strip-ansi: 6.0.1++ dependencies:+ ansi-regex: 5.0.1++ dependencies:+ os-tmpdir: 1.0.2++ dependencies:+ '@cspotcode/source-map-support': 0.8.1+ '@tsconfig/node10': 1.0.11+ '@tsconfig/node12': 1.0.11+ '@tsconfig/node14': 1.0.3+ '@tsconfig/node16': 1.0.4+ '@types/node': 24.2.0+ acorn: 8.15.0+ acorn-walk: 8.3.4+ arg: 4.1.3+ create-require: 1.1.1+ diff: 4.0.2+ make-error: 1.3.6+ typescript: 5.9.2+ v8-compile-cache-lib: 3.0.1+ yn: 3.1.1++ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ ansi-styles: 4.3.0+ string-width: 4.2.3+ strip-ansi: 6.0.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}diff --git a/bindings/ts-napi/tsconfig.json b/bindings/ts-napi/tsconfig.jsonnew file mode 100644index 000000000..e2fd5a394--- /dev/null+++ b/bindings/ts-napi/tsconfig.json@@ -0,0 +1,13 @@+{+ "compilerOptions": {+ "target": "es2020",+ "module": "commonjs",+ "moduleResolution": "node",+ "strict": true,+ "esModuleInterop": true,+ "outDir": "dist",+ "types": [+ "node"+ ]+ }+}\ No newline at end of filediff --git a/crates/backend-remote/src/openai/bridging/chat/api_stream.rs b/crates/backend-remote/src/openai/bridging/chat/api_stream.rsindex 4c35a9aa2..39f2f4cdd 100644--- a/crates/backend-remote/src/openai/bridging/chat/api_stream.rs+++ b/crates/backend-remote/src/openai/bridging/chat/api_stream.rs@@ -4,7 +4,7 @@ use async_openai::{Client, config::OpenAIConfig};use futures::{FutureExt, Stream, StreamExt, stream};use shoji::{traits::backend::{Error as BackendError, chat_message::Output},- types::{encoding::Message, session::chat::StreamConfig},+ types::session::chat::{ChatMessage, ChatReplyConfig},};use tokio_util::sync::CancellationToken;@@ -24,8 +24,8 @@ impl bridging::ApiStream for ApiStream {&self,client: Arc<Client<OpenAIConfig>>,model: String,- config: StreamConfig,- messages: Vec<Message>,+ config: ChatReplyConfig,+ messages: Vec<ChatMessage>,cancel: CancellationToken,) -> Pin<Box<dyn Stream<Item = Result<Output, BackendError>> + Send>> {let stream = async move {diff --git a/crates/backend-remote/src/openai/bridging/chat/finish_reason.rs b/crates/backend-remote/src/openai/bridging/chat/finish_reason.rsindex 74e673661..4590e1c2b 100644--- a/crates/backend-remote/src/openai/bridging/chat/finish_reason.rs+++ b/crates/backend-remote/src/openai/bridging/chat/finish_reason.rs@@ -1,12 +1,12 @@-use async_openai::types::chat::FinishReason as ChatFinishReason;-use shoji::types::session::chat::FinishReason;+use async_openai::types::chat::FinishReason as OpenAiFinishReason;+use shoji::types::session::chat::ChatReplyFinishReason;-pub fn build(reason: ChatFinishReason) -> FinishReason {+pub fn build(reason: OpenAiFinishReason) -> ChatReplyFinishReason {match reason {- ChatFinishReason::Stop => FinishReason::Stop,- ChatFinishReason::Length => FinishReason::Length,- ChatFinishReason::ToolCalls => FinishReason::ToolCalls,- ChatFinishReason::ContentFilter => FinishReason::Rejected,- ChatFinishReason::FunctionCall => FinishReason::ToolCalls,+ OpenAiFinishReason::Stop => ChatReplyFinishReason::Stop,+ OpenAiFinishReason::Length => ChatReplyFinishReason::Length,+ OpenAiFinishReason::ToolCalls => ChatReplyFinishReason::ToolCalls,+ OpenAiFinishReason::ContentFilter => ChatReplyFinishReason::Rejected,+ OpenAiFinishReason::FunctionCall => ChatReplyFinishReason::ToolCalls,}}diff --git a/crates/backend-remote/src/openai/bridging/chat/message.rs b/crates/backend-remote/src/openai/bridging/chat/message.rsindex 309cca8bf..2182cef19 100644--- a/crates/backend-remote/src/openai/bridging/chat/message.rs+++ b/crates/backend-remote/src/openai/bridging/chat/message.rs@@ -5,7 +5,7 @@ use async_openai::types::chat::{ChatCompletionRequestToolMessageContent, ChatCompletionRequestUserMessage, ChatCompletionRequestUserMessageContent,FunctionCall,};-use shoji::types::encoding::{Message, Role};+use shoji::types::session::chat::{ChatMessage, ChatRole};use crate::openai::Error;@@ -16,12 +16,12 @@ enum ResolvedRole {Tool,}-pub fn build(message: &Message) -> Result<ChatCompletionRequestMessage, Error> {+pub fn build(message: &ChatMessage) -> Result<ChatCompletionRequestMessage, Error> {let (role, content, tool_calls, tool_call_id) = match message.role {- Role::System {} => (ResolvedRole::System, message.text(), None, None),- Role::User {} => (ResolvedRole::User, message.text(), None, None),- Role::Assistant {} => (ResolvedRole::Assistant, message.text(), Some(message.tool_calls()), None),- Role::Tool {} => {+ ChatRole::System {} => (ResolvedRole::System, message.text(), None, None),+ ChatRole::User {} => (ResolvedRole::User, message.text(), None, None),+ ChatRole::Assistant {} => (ResolvedRole::Assistant, message.text(), Some(message.tool_calls()), None),+ ChatRole::Tool {} => {let tool_call_results = message.tool_call_results();if tool_call_results.len() != 1 {return Err(Error::ToolCallResultRequired);@@ -30,10 +30,10 @@ pub fn build(message: &Message) -> Result<ChatCompletionRequestMessage, Error> {let content = serde_json::to_string(&value).map_err(|error| Error::Serialization {message: error.to_string(),})?;- (ResolvedRole::Tool, content, None, tool_call_id.clone())+ (ResolvedRole::Tool, Some(content), None, tool_call_id.clone())},- Role::Developer {}- | Role::Custom {+ ChatRole::Developer {}+ | ChatRole::Custom {..} => return Err(Error::UnsupportedRole),};@@ -54,19 +54,25 @@ pub fn build(message: &Message) -> Result<ChatCompletionRequestMessage, Error> {});Ok(match role {- ResolvedRole::System => ChatCompletionRequestMessage::System(ChatCompletionRequestSystemMessage {- content: ChatCompletionRequestSystemMessageContent::Text(content),- name: None,+ ResolvedRole::System => ChatCompletionRequestMessage::System({+ let content = content.ok_or(Error::ContentRequired)?;+ ChatCompletionRequestSystemMessage {+ content: ChatCompletionRequestSystemMessageContent::Text(content),+ name: None,+ }}),- ResolvedRole::User => ChatCompletionRequestMessage::User(ChatCompletionRequestUserMessage {- content: ChatCompletionRequestUserMessageContent::Text(content),- name: None,+ ResolvedRole::User => ChatCompletionRequestMessage::User({+ let content = content.ok_or(Error::ContentRequired)?;+ ChatCompletionRequestUserMessage {+ content: ChatCompletionRequestUserMessageContent::Text(content),+ name: None,+ }}),ResolvedRole::Assistant => {- let text_content = if content.is_empty() {- None- } else {+ let text_content = if let Some(content) = content {Some(ChatCompletionRequestAssistantMessageContent::Text(content))+ } else {+ None};#[allow(deprecated)]ChatCompletionRequestMessage::Assistant(ChatCompletionRequestAssistantMessage {@@ -78,9 +84,12 @@ pub fn build(message: &Message) -> Result<ChatCompletionRequestMessage, Error> {function_call: None,})},- ResolvedRole::Tool => ChatCompletionRequestMessage::Tool(ChatCompletionRequestToolMessage {- content: ChatCompletionRequestToolMessageContent::Text(content),- tool_call_id: tool_call_id.unwrap_or_default(),+ ResolvedRole::Tool => ChatCompletionRequestMessage::Tool({+ let content = content.ok_or(Error::ContentRequired)?;+ ChatCompletionRequestToolMessage {+ content: ChatCompletionRequestToolMessageContent::Text(content),+ tool_call_id: tool_call_id.unwrap_or_default(),+ }}),})}diff --git a/crates/backend-remote/src/openai/bridging/chat/request.rs b/crates/backend-remote/src/openai/bridging/chat/request.rsindex dfdefdec0..91c596bf0 100644--- a/crates/backend-remote/src/openai/bridging/chat/request.rs+++ b/crates/backend-remote/src/openai/bridging/chat/request.rs@@ -3,8 +3,7 @@ use async_openai::types::chat::{};use shoji::types::{basic::{SamplingMethod, SamplingPolicy},- encoding::{Message, MessageList},- session::chat::StreamConfig,+ session::chat::{ChatMessage, ChatMessageList, ChatReplyConfig},};use crate::openai::{@@ -14,8 +13,8 @@ use crate::openai::{pub fn build(model: &str,- config: &StreamConfig,- messages: Vec<Message>,+ config: &ChatReplyConfig,+ messages: Vec<ChatMessage>,) -> Result<CreateChatCompletionRequest, Error> {let completion_messages = messages.iter().map(chat::message::build).collect::<Result<Vec<_>, _>>()?;diff --git a/crates/backend-remote/src/openai/bridging/chat/tool.rs b/crates/backend-remote/src/openai/bridging/chat/tool.rsindex 555b1bfdd..479b079af 100644--- a/crates/backend-remote/src/openai/bridging/chat/tool.rs+++ b/crates/backend-remote/src/openai/bridging/chat/tool.rs@@ -1,11 +1,11 @@use async_openai::types::chat::{ChatCompletionTool, ChatCompletionTools, FunctionObject};-use shoji::types::encoding::ToolDescription;+use shoji::types::basic::ToolDescription;use crate::openai::Error;pub fn build(description: ToolDescription) -> Result<ChatCompletionTools, Error> {let ToolDescription::Function {- function,+ tool_function: function,} = description;let parameters = match function.parameters {Some(value) => {diff --git a/crates/backend-remote/src/openai/bridging/mod.rs b/crates/backend-remote/src/openai/bridging/mod.rsindex 0af2cf9d7..422396fe6 100644--- a/crates/backend-remote/src/openai/bridging/mod.rs+++ b/crates/backend-remote/src/openai/bridging/mod.rs@@ -8,7 +8,7 @@ use async_openai::{Client, config::OpenAIConfig};use futures::Stream;use shoji::{traits::backend::{Error as BackendError, chat_message::Output},- types::{encoding::Message, session::chat::StreamConfig},+ types::session::chat::{ChatMessage, ChatReplyConfig},};use tokio_util::sync::CancellationToken;@@ -17,8 +17,8 @@ pub trait ApiStream: Send + Sync {&self,client: Arc<Client<OpenAIConfig>>,model: String,- config: StreamConfig,- messages: Vec<Message>,+ config: ChatReplyConfig,+ messages: Vec<ChatMessage>,cancel: CancellationToken,) -> Pin<Box<dyn Stream<Item = Result<Output, BackendError>> + Send>>;}diff --git a/crates/backend-remote/src/openai/bridging/reasoning_effort.rs b/crates/backend-remote/src/openai/bridging/reasoning_effort.rsindex bbaa5d96d..535672429 100644--- a/crates/backend-remote/src/openai/bridging/reasoning_effort.rs+++ b/crates/backend-remote/src/openai/bridging/reasoning_effort.rs@@ -1,5 +1,5 @@use async_openai::types::chat::ReasoningEffort as OpenAIReasoningEffort;-use shoji::types::encoding::ReasoningEffort;+use shoji::types::basic::ReasoningEffort;pub fn build(effort: ReasoningEffort) -> OpenAIReasoningEffort {match effort {diff --git a/crates/backend-remote/src/openai/bridging/responses/api_stream.rs b/crates/backend-remote/src/openai/bridging/responses/api_stream.rsindex 1b7ab79b5..309a21660 100644--- a/crates/backend-remote/src/openai/bridging/responses/api_stream.rs+++ b/crates/backend-remote/src/openai/bridging/responses/api_stream.rs@@ -4,7 +4,7 @@ use async_openai::{Client, config::OpenAIConfig};use futures::{FutureExt, Stream, StreamExt, stream};use shoji::{traits::backend::{Error as BackendError, chat_message::Output},- types::{encoding::Message, session::chat::StreamConfig},+ types::session::chat::{ChatMessage, ChatReplyConfig},};use tokio_util::sync::CancellationToken;@@ -24,8 +24,8 @@ impl bridging::ApiStream for ApiStream {&self,client: Arc<Client<OpenAIConfig>>,model: String,- config: StreamConfig,- messages: Vec<Message>,+ config: ChatReplyConfig,+ messages: Vec<ChatMessage>,cancel: CancellationToken,) -> Pin<Box<dyn Stream<Item = Result<Output, BackendError>> + Send>> {let stream = async move {diff --git a/crates/backend-remote/src/openai/bridging/responses/finish_reason.rs b/crates/backend-remote/src/openai/bridging/responses/finish_reason.rsindex 564137639..200836065 100644--- a/crates/backend-remote/src/openai/bridging/responses/finish_reason.rs+++ b/crates/backend-remote/src/openai/bridging/responses/finish_reason.rs@@ -1,10 +1,10 @@use async_openai::types::responses::Status;-use shoji::types::session::chat::FinishReason;+use shoji::types::session::chat::ChatReplyFinishReason;-pub fn build(status: &Status) -> Option<FinishReason> {+pub fn build(status: &Status) -> Option<ChatReplyFinishReason> {match status {- Status::Completed | Status::Failed => Some(FinishReason::Stop),- Status::Cancelled => Some(FinishReason::Cancelled),+ Status::Completed | Status::Failed => Some(ChatReplyFinishReason::Stop),+ Status::Cancelled => Some(ChatReplyFinishReason::Cancelled),_ => None,}}diff --git a/crates/backend-remote/src/openai/bridging/responses/message.rs b/crates/backend-remote/src/openai/bridging/responses/message.rsindex da95db218..051da1710 100644--- a/crates/backend-remote/src/openai/bridging/responses/message.rs+++ b/crates/backend-remote/src/openai/bridging/responses/message.rs@@ -2,23 +2,23 @@ use async_openai::types::responses::{EasyInputContent, EasyInputMessage, FunctionCallOutput, FunctionCallOutputItemParam, FunctionToolCall, InputItem,Item, MessageType, Role as ResponseRole,};-use shoji::types::encoding::{Message, Role};+use shoji::types::session::chat::{ChatMessage, ChatRole};use crate::openai::Error;-pub fn build(message: &Message) -> Result<Vec<InputItem>, Error> {+pub fn build(message: &ChatMessage) -> Result<Vec<InputItem>, Error> {let mut items = Vec::new();match message.role {- Role::System {} | Role::Developer {} | Role::User {} | Role::Assistant {} => {+ ChatRole::System {} | ChatRole::Developer {} | ChatRole::User {} | ChatRole::Assistant {} => {let role = match message.role {- Role::System {} => ResponseRole::System,- Role::Developer {} => ResponseRole::Developer,- Role::User {} => ResponseRole::User,- Role::Assistant {} => ResponseRole::Assistant,+ ChatRole::System {} => ResponseRole::System,+ ChatRole::Developer {} => ResponseRole::Developer,+ ChatRole::User {} => ResponseRole::User,+ ChatRole::Assistant {} => ResponseRole::Assistant,_ => return Err(Error::UnsupportedRole),};let text = message.text();- if !text.is_empty() {+ if let Some(text) = text {items.push(InputItem::EasyMessage(EasyInputMessage {r#type: MessageType::default(),role,@@ -26,7 +26,7 @@ pub fn build(message: &Message) -> Result<Vec<InputItem>, Error> {phase: None,}));}- if matches!(message.role, Role::Assistant {}) {+ if matches!(message.role, ChatRole::Assistant {}) {for tool_call in message.tool_calls() {items.push(InputItem::Item(Item::FunctionCall(FunctionToolCall {arguments: tool_call.arguments.json.clone(),@@ -39,7 +39,7 @@ pub fn build(message: &Message) -> Result<Vec<InputItem>, Error> {}}},- Role::Tool {} => {+ ChatRole::Tool {} => {for (call_id, _name, value) in message.tool_call_results() {let content = serde_json::to_string(&value).map_err(|error| Error::Serialization {message: error.to_string(),@@ -52,7 +52,7 @@ pub fn build(message: &Message) -> Result<Vec<InputItem>, Error> {})));}},- Role::Custom {+ ChatRole::Custom {..} => return Err(Error::UnsupportedRole),}diff --git a/crates/backend-remote/src/openai/bridging/responses/request.rs b/crates/backend-remote/src/openai/bridging/responses/request.rsindex 44bf6533e..2ef924de6 100644--- a/crates/backend-remote/src/openai/bridging/responses/request.rs+++ b/crates/backend-remote/src/openai/bridging/responses/request.rs@@ -3,8 +3,7 @@ use async_openai::types::responses::{};use shoji::types::{basic::{SamplingMethod, SamplingPolicy},- encoding::{Message, MessageList},- session::chat::StreamConfig,+ session::chat::{ChatMessage, ChatMessageList, ChatReplyConfig},};use crate::openai::{@@ -14,8 +13,8 @@ use crate::openai::{pub fn build(model: &str,- config: &StreamConfig,- messages: Vec<Message>,+ config: &ChatReplyConfig,+ messages: Vec<ChatMessage>,) -> Result<CreateResponse, Error> {let input_items = messages.iter()diff --git a/crates/backend-remote/src/openai/bridging/responses/tool.rs b/crates/backend-remote/src/openai/bridging/responses/tool.rsindex a068cd9e6..07464f38b 100644--- a/crates/backend-remote/src/openai/bridging/responses/tool.rs+++ b/crates/backend-remote/src/openai/bridging/responses/tool.rs@@ -1,11 +1,11 @@use async_openai::types::responses::{FunctionTool, Tool};-use shoji::types::encoding::ToolDescription;+use shoji::types::basic::ToolDescription;use crate::openai::Error;pub fn build(description: ToolDescription) -> Result<Tool, Error> {let ToolDescription::Function {- function,+ tool_function: function,} = description;let parameters = match function.parameters {Some(value) => {diff --git a/crates/backend-remote/src/openai/error.rs b/crates/backend-remote/src/openai/error.rsindex 16c62ba98..a744a6f74 100644--- a/crates/backend-remote/src/openai/error.rs+++ b/crates/backend-remote/src/openai/error.rs@@ -16,4 +16,6 @@ pub enum Error {UnsupportedRole,#[error("Tool call result is required")]ToolCallResultRequired,+ #[error("Content is required")]+ ContentRequired,}diff --git a/crates/backend-remote/src/openai/instance.rs b/crates/backend-remote/src/openai/instance.rsindex 12be33fe7..3d0c0a56c 100644--- a/crates/backend-remote/src/openai/instance.rs+++ b/crates/backend-remote/src/openai/instance.rs@@ -10,7 +10,7 @@ use shoji::{chat_message::{StreamInput, StreamOutput},},},- types::session::chat::StreamConfig,+ types::session::chat::ChatReplyConfig,};use tokio_util::sync::CancellationToken;@@ -53,7 +53,7 @@ impl Instance {}impl InstanceTrait for Instance {- type StreamConfig = StreamConfig;+ type StreamConfig = ChatReplyConfig;type StreamInput = StreamInput;type StreamOutput = StreamOutput;diff --git a/crates/backend-remote/src/openai/mod.rs b/crates/backend-remote/src/openai/mod.rsindex da932284a..143a367f9 100644--- a/crates/backend-remote/src/openai/mod.rs+++ b/crates/backend-remote/src/openai/mod.rs@@ -16,7 +16,7 @@ use shoji::{Backend as BackendTrait,backend::{Error as BackendError, chat_message},},- types::session::chat::Config as ChatConfig,+ types::session::chat::ChatConfig,};pub struct Backend {diff --git a/crates/backend-remote/src/openai/stream_state.rs b/crates/backend-remote/src/openai/stream_state.rsindex b1cf8bc82..5be7b8c4d 100644--- a/crates/backend-remote/src/openai/stream_state.rs+++ b/crates/backend-remote/src/openai/stream_state.rs@@ -3,7 +3,7 @@ use std::time::Instant;use indexmap::IndexMap;use shoji::{traits::backend::chat_message::Output,- types::session::chat::{FinishReason, Stats},+ types::session::chat::{ChatReplyFinishReason, ChatReplyStats},};use crate::openai::tool_call_state::ToolCallState;@@ -21,7 +21,7 @@ pub struct StreamChunk {pub content: Option<String>,pub reasoning: Option<String>,pub tool_calls: Vec<ToolCallChunk>,- pub finish_reason: Option<FinishReason>,+ pub finish_reason: Option<ChatReplyFinishReason>,pub tokens_input: Option<u32>,pub tokens_output: Option<u32>,}@@ -31,7 +31,7 @@ pub struct StreamState {text: Option<String>,reasoning: Option<String>,tool_calls: IndexMap<u32, ToolCallState>,- finish_reason: Option<FinishReason>,+ finish_reason: Option<ChatReplyFinishReason>,start_moment: Instant,first_token_moment: Option<Instant>,tokens_input: Option<u32>,@@ -113,7 +113,7 @@ impl StreamState {}}- fn stats(&self) -> Stats {+ fn stats(&self) -> ChatReplyStats {let duration = self.start_moment.elapsed().as_secs_f64();let time_to_first_token =self.first_token_moment.map(|first| first.duration_since(self.start_moment).as_secs_f64());@@ -131,7 +131,7 @@ impl StreamState {},_ => None,};- Stats {+ ChatReplyStats {duration,time_to_first_token,prefill_tokens_per_second,diff --git a/crates/backend-remote/src/openai/tool_call_state.rs b/crates/backend-remote/src/openai/tool_call_state.rsindex ad3f557b2..991783046 100644--- a/crates/backend-remote/src/openai/tool_call_state.rs+++ b/crates/backend-remote/src/openai/tool_call_state.rs@@ -1,6 +1,6 @@use shoji::{traits::backend::chat_message::ToolCallState as OutputToolCallState,- types::{basic::Value, encoding::ToolCall},+ types::basic::{ToolCall, Value},};use crate::openai::stream_state::ToolCallChunk;diff --git a/crates/backend-uzu/src/inference/chat/bridging.rs b/crates/backend-uzu/src/inference/chat/bridging.rsnew file mode 100644index 000000000..6cec0db3d--- /dev/null+++ b/crates/backend-uzu/src/inference/chat/bridging.rs@@ -0,0 +1,200 @@+use std::{path::Path, sync::Arc};++use shoji::{+ traits::backend::chat_message::Output as ChatMessageOutput,+ types::{+ basic::{+ ContextLength as ShojiContextLength, Grammar as ShojiGrammar, ReasoningEffort,+ SamplingMethod as ShojiSamplingMethod, SamplingPolicy as ShojiSamplingPolicy,+ SamplingSeed as ShojiSamplingSeed,+ },+ session::chat::{+ ChatConfig as ShojiChatConfig, ChatMessage as ShojiMessage, ChatMessageList, ChatReplyConfig,+ ChatReplyFinishReason as ShojiFinishReason, ChatReplyStats as ShojiStats, ChatRole as ShojiRole,+ ChatSpeculationPreset as ShojiSpeculationPreset,+ },+ },+};+use tokenizers::Tokenizer;++use crate::{+ inference::Error,+ session::{+ config::{DecodingConfig, GrammarConfig, RunConfig, SpeculatorConfig},+ parameter::{ContextLength, SamplingMethod, SamplingPolicy, SamplingProcessingOrder, SamplingSeed},+ types::{FinishReason, Input, Message, Output, Role, Stats},+ },+ speculators::{fixed_token_speculator::FixedTokensSpeculator, prompt_lookup_speculator::PromptLookupSpeculator},+};++pub fn build_decoding_config(+ config: &ShojiChatConfig,+ model_path: &Path,+) -> Result<DecodingConfig, Error> {+ let context_length = match &config.context_length {+ ShojiContextLength::Default {} => ContextLength::Default,+ ShojiContextLength::Maximal {} => ContextLength::Maximal,+ ShojiContextLength::Custom {+ length,+ } => ContextLength::Custom((*length).max(0) as usize),+ };+ let sampling_seed = match &config.sampling_seed {+ ShojiSamplingSeed::Default {} => SamplingSeed::Default,+ ShojiSamplingSeed::Custom {+ seed,+ } => SamplingSeed::Custom(*seed as u64),+ };+ let speculator_config: SpeculatorConfig = match &config.speculation_preset {+ Some(ShojiSpeculationPreset::GeneralChat {+ ..+ }) => SpeculatorConfig::default(),+ Some(ShojiSpeculationPreset::Summarization {+ ..+ }) => {+ let number_of_speculated_tokens = 16 - 1;+ let speculator = PromptLookupSpeculator::new_with_params(3);+ SpeculatorConfig::new(number_of_speculated_tokens, Arc::new(speculator))+ },+ Some(ShojiSpeculationPreset::Classification {+ feature,+ }) => {+ let tokenizer =+ Tokenizer::from_file(model_path.join("tokenizer.json")).map_err(|_| Error::UnableToLoadTokenizer)?;+ let proposals: Vec<Vec<u64>> = feature+ .values+ .iter()+ .map(|value| {+ let encoding = tokenizer.encode(value.as_str(), false).map_err(|error| Error::Runtime {+ message: error.to_string(),+ })?;+ Ok(encoding.get_ids().iter().map(|&id| id as u64).collect::<Vec<_>>())+ })+ .collect::<Result<Vec<Vec<u64>>, Error>>()?;+ let speculator = FixedTokensSpeculator::new(proposals);+ SpeculatorConfig::new(speculator.max_trie_nodes(), Arc::new(speculator))+ },+ None => SpeculatorConfig::default(),+ };+ Ok(DecodingConfig::default()+ .with_context_length(context_length)+ .with_sampling_seed(sampling_seed)+ .with_speculator_config(speculator_config))+}++pub fn build_input_and_run_config(+ messages: &Vec<ShojiMessage>,+ config: &ChatReplyConfig,+) -> (Input, RunConfig) {+ let input_messages = messages.iter().filter_map(build_message).collect();+ let input = Input::Messages(input_messages);+ let run_config = build_run_config(messages, config);+ (input, run_config)+}++pub fn build_output(output: &Output) -> ChatMessageOutput {+ let text = output.text.parsed.response.clone();+ let reasoning = output.text.parsed.chain_of_thought.clone();+ let finish_reason = output.finish_reason.as_ref().map(build_finish_reason);+ let stats = build_stats(&output.stats);+ ChatMessageOutput {+ reasoning,+ text,+ tool_calls: vec![],+ finish_reason,+ stats,+ }+}++fn build_message(message: &ShojiMessage) -> Option<Message> {+ let role = match &message.role {+ ShojiRole::System {} => Role::System,+ ShojiRole::User {} => Role::User,+ ShojiRole::Assistant {} => Role::Assistant,+ ShojiRole::Developer {}+ | ShojiRole::Tool {}+ | ShojiRole::Custom {+ ..+ } => return None,+ };++ let content = message.text().unwrap_or_default();+ let reasoning_content = message.reasoning();+ Some(Message {+ role,+ content,+ reasoning_content,+ })+}++fn build_run_config(+ messages: &Vec<ShojiMessage>,+ config: &ChatReplyConfig,+) -> RunConfig {+ let sampling_policy = build_sampling_policy(&config.sampling_policy);+ let grammar_config = build_grammar(&config.grammar);+ let tokens_limit = config.token_limit.map(|value| value as u64).unwrap_or(2048);+ let enable_thinking =+ messages.reasoning_effort().map(|effort| !matches!(effort, ReasoningEffort::Disabled)).unwrap_or(true);+ RunConfig::new(tokens_limit, enable_thinking, sampling_policy, grammar_config)+}++fn build_sampling_policy(sampling_policy: &ShojiSamplingPolicy) -> SamplingPolicy {+ match sampling_policy {+ ShojiSamplingPolicy::Default {} => SamplingPolicy::Default,+ ShojiSamplingPolicy::Custom {+ method,+ } => SamplingPolicy::Custom {+ value: match method {+ ShojiSamplingMethod::Greedy {} => SamplingMethod::Greedy,+ ShojiSamplingMethod::Stochastic {+ temperature,+ top_k,+ top_p,+ min_p,+ } => SamplingMethod::Stochastic {+ temperature: temperature.map(|value| value as f32),+ top_k: top_k.map(|value| value.max(0) as u32),+ top_p: top_p.map(|value| value as f32),+ min_p: min_p.map(|value| value as f32),+ processing_order: SamplingProcessingOrder::TemperatureThenFilters,+ },+ },+ },+ }+}++fn build_grammar(grammar: &Option<ShojiGrammar>) -> Option<GrammarConfig> {+ match grammar {+ Some(ShojiGrammar::JsonAny {}) => Some(GrammarConfig::builtin_json()),+ Some(ShojiGrammar::JsonSchema {+ schema,+ }) => Some(GrammarConfig::json_schema_simple(schema.clone())),+ Some(ShojiGrammar::Regex {+ pattern,+ }) => Some(GrammarConfig::regex(pattern.clone(), false)),+ None => None,+ }+}++fn build_finish_reason(reason: &FinishReason) -> ShojiFinishReason {+ match reason {+ FinishReason::Stop => ShojiFinishReason::Stop,+ FinishReason::Length => ShojiFinishReason::Length,+ FinishReason::Cancelled => ShojiFinishReason::Cancelled,+ FinishReason::ContextLimitReached => ShojiFinishReason::ContextLimitReached,+ }+}++fn build_stats(stats: &Stats) -> ShojiStats {+ let time_to_first_token = Some(stats.prefill_stats.duration);+ let prefill_tokens_per_second = Some(stats.prefill_stats.processed_tokens_per_second);+ let generate_tokens_per_second = stats.generate_stats.as_ref().map(|step| step.tokens_per_second);+ ShojiStats {+ duration: stats.total_stats.duration,+ time_to_first_token,+ prefill_tokens_per_second,+ generate_tokens_per_second,+ tokens_count_input: Some(stats.total_stats.tokens_count_input as u32),+ tokens_count_output: Some(stats.total_stats.tokens_count_output as u32),+ }+}diff --git a/crates/backend-uzu/src/inference/chat/mod.rs b/crates/backend-uzu/src/inference/chat/mod.rsnew file mode 100644index 000000000..32ffb0ea0--- /dev/null+++ b/crates/backend-uzu/src/inference/chat/mod.rs@@ -0,0 +1,127 @@+mod bridging;+mod state;++use std::{path::PathBuf, pin::Pin};++use bridging::{build_decoding_config, build_input_and_run_config, build_output};+use futures::{+ Stream, StreamExt,+ channel::mpsc::{self, UnboundedSender},+};+use shoji::{+ traits::{+ Instance as InstanceTrait, State as StateTrait,+ backend::{+ Error as BackendError,+ chat_message::{Output as ChatMessageOutput, StreamInput, StreamOutput},+ },+ },+ types::session::chat::{ChatConfig, ChatReplyConfig},+};+use state::State;+use tokio_util::sync::CancellationToken;++use crate::{+ inference::{Container, Error},+ session::{+ ChatSession,+ config::RunConfig,+ types::{Input, Output},+ },+};++pub struct Instance {+ session_container: Container<ChatSession>,+}++impl Instance {+ pub fn new(+ reference: String,+ config: ChatConfig,+ ) -> Result<Self, Error> {+ let model_path = PathBuf::from(reference.clone());+ let decoding_config = build_decoding_config(&config, &model_path)?;+ let session = ChatSession::new(model_path, decoding_config).map_err(Error::from)?;+ let container = Container::new(session);+ Ok(Self {+ session_container: container,+ })+ }+}++impl InstanceTrait for Instance {+ type StreamConfig = ChatReplyConfig;+ type StreamInput = StreamInput;+ type StreamOutput = StreamOutput;++ fn state(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn StateTrait>, BackendError>> + Send + '_>> {+ let result: Result<(), Error> = self+ .session_container+ .value+ .lock()+ .map_err(|error| Error::Runtime {+ message: error.to_string(),+ })+ .and_then(|mut session| session.reset().map_err(Error::from));+ Box::pin(async move {+ result.map_err(|error| Box::new(error) as BackendError)?;+ Ok(Box::new(State) as Box<dyn StateTrait>)+ })+ }++ fn stream<'a>(+ &'a self,+ input: &'a Self::StreamInput,+ _state: &'a mut dyn StateTrait,+ config: Self::StreamConfig,+ cancel_token: CancellationToken,+ ) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {+ let session = self.session_container.clone();+ let messages = input.clone();+ let cancel_token_for_run = cancel_token.clone();++ let (sender, receiver) = mpsc::unbounded::<Result<ChatMessageOutput, BackendError>>();+ let (input, run_config) = build_input_and_run_config(&messages, &config);+ std::thread::spawn(move || {+ run(session, input, run_config, cancel_token_for_run, sender);+ });+ Box::pin(receiver.take_until(cancel_token.cancelled_owned()))+ }+}++fn run(+ session_container: Container<ChatSession>,+ uzu_input: Input,+ run_config: RunConfig,+ cancel_token: CancellationToken,+ sender: UnboundedSender<Result<ChatMessageOutput, BackendError>>,+) {+ let progress = {+ let sender = sender.clone();+ let cancel_token = cancel_token.clone();+ move |output: Output| -> bool {+ let chat_output = build_output(&output);+ let _ = sender.unbounded_send(Ok(chat_output));+ !cancel_token.is_cancelled()+ }+ };++ let result = {+ let mut session = match session_container.value.lock() {+ Ok(session) => session,+ Err(error) => {+ let _ = sender.unbounded_send(Err(Box::new(Error::Runtime {+ message: error.to_string(),+ }) as BackendError));+ return;+ },+ };+ session.run(uzu_input, run_config, Some(progress))+ };++ let result = match result {+ Ok(output) => Ok(build_output(&output)),+ Err(error) => Err(Box::new(Error::from(error)) as BackendError),+ };+ let _ = sender.unbounded_send(result);+}diff --git a/crates/backend-uzu/src/inference/chat/state.rs b/crates/backend-uzu/src/inference/chat/state.rsnew file mode 100644index 000000000..9dbbe80a4--- /dev/null+++ b/crates/backend-uzu/src/inference/chat/state.rs@@ -0,0 +1,10 @@+use shoji::traits::State as StateTrait;++#[derive(Debug, Clone)]+pub struct State;++impl StateTrait for State {+ fn clone_boxed(&self) -> Box<dyn StateTrait> {+ Box::new(self.clone())+ }+}diff --git a/crates/backend-uzu/src/inference/classification/bridging.rs b/crates/backend-uzu/src/inference/classification/bridging.rsnew file mode 100644index 000000000..4cd65003a--- /dev/null+++ b/crates/backend-uzu/src/inference/classification/bridging.rs@@ -0,0 +1,54 @@+use std::collections::HashMap;++use shoji::types::session::classification::{+ ClassificationMessage as ShojiMessage, ClassificationOutput as ShojiOutput,+ ClassificationOutputProbabilities as ShojiOutputProbabilities, ClassificationRole as ShojiRole,+ ClassificationStats as ShojiStats,+};++use crate::{+ classifier::ClassificationOutput,+ session::types::{Input, Message, Role},+};++pub fn build_input(messages: &[ShojiMessage]) -> Input {+ let input_messages: Vec<Message> = messages+ .iter()+ .map(|message| {+ let role = match message.role {+ ShojiRole::User => Role::User,+ ShojiRole::Assistant => Role::Assistant,+ };+ Message {+ role,+ content: message.content.clone(),+ reasoning_content: None,+ }+ })+ .collect();+ Input::Messages(input_messages)+}++pub fn build_output(output: &ClassificationOutput) -> ShojiOutput {+ let logits = output.logits.iter().map(|value| *value as f64).collect();+ let probabilities: HashMap<String, f64> =+ output.probabilities.iter().map(|(label, value)| (label.clone(), *value as f64)).collect();+ let probabilities = ShojiOutputProbabilities {+ values: probabilities,+ };+ let stats = ShojiStats {+ preprocessing_duration: output.stats.preprocessing_duration,+ forward_pass_duration: output.stats.forward_pass_duration,+ postprocessing_duration: output.stats.postprocessing_duration,+ total_duration: output.stats.total_duration,+ tokens_count: output.stats.tokens_count as i64,+ tokens_per_second: output.stats.tokens_per_second,+ predicted_label: output.stats.predicted_label.clone(),+ confidence: output.stats.confidence as f64,+ };+ ShojiOutput {+ logits,+ probabilities,+ stats,+ }+}diff --git a/crates/backend-uzu/src/inference/classification/mod.rs b/crates/backend-uzu/src/inference/classification/mod.rsnew file mode 100644index 000000000..073045065--- /dev/null+++ b/crates/backend-uzu/src/inference/classification/mod.rs@@ -0,0 +1,94 @@+mod bridging;+mod state;++use std::{path::PathBuf, pin::Pin};++use bridging::{build_input, build_output};+use futures::{+ Stream, StreamExt,+ channel::mpsc::{self, UnboundedSender},+};+use shoji::{+ traits::{+ Instance as InstanceTrait, State as StateTrait,+ backend::{+ Error as BackendError,+ classification::{StreamInput, StreamOutput},+ },+ },+ types::session::classification::ClassificationOutput as ShojiOutput,+};+use state::State;+use tokio_util::sync::CancellationToken;++use crate::{+ inference::{Container, Error},+ session::{ClassificationSession, types::Input},+};++pub struct Instance {+ session_container: Container<ClassificationSession>,+}++impl Instance {+ pub fn new(reference: String) -> Result<Self, Error> {+ let model_path = PathBuf::from(reference);+ let session = ClassificationSession::new(model_path).map_err(Error::from)?;+ let container = Container::new(session);+ Ok(Self {+ session_container: container,+ })+ }+}++impl InstanceTrait for Instance {+ type StreamConfig = ();+ type StreamInput = StreamInput;+ type StreamOutput = StreamOutput;++ fn state(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn StateTrait>, BackendError>> + Send + '_>> {+ Box::pin(async move { Ok(Box::new(State) as Box<dyn StateTrait>) })+ }++ fn stream<'a>(+ &'a self,+ input: &'a Self::StreamInput,+ _state: &'a mut dyn StateTrait,+ _config: Self::StreamConfig,+ cancel_token: CancellationToken,+ ) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {+ let input = build_input(input);+ let session_container = self.session_container.clone();+ let (sender, receiver) = mpsc::unbounded::<Result<ShojiOutput, BackendError>>();++ std::thread::spawn(move || {+ run(session_container, input, sender);+ });++ Box::pin(receiver.take_until(cancel_token.cancelled_owned()))+ }+}++fn run(+ session_container: Container<ClassificationSession>,+ input: Input,+ sender: UnboundedSender<Result<ShojiOutput, BackendError>>,+) {+ let result = {+ let mut session = match session_container.value.lock() {+ Ok(guard) => guard,+ Err(error) => {+ let _ = sender.unbounded_send(Err(Box::new(Error::Runtime {+ message: error.to_string(),+ }) as BackendError));+ return;+ },+ };+ session.classify(input)+ };+ let result = match result {+ Ok(output) => Ok(build_output(&output)),+ Err(error) => Err(Box::new(Error::from(error)) as BackendError),+ };+ let _ = sender.unbounded_send(result);+}diff --git a/crates/backend-uzu/src/inference/classification/state.rs b/crates/backend-uzu/src/inference/classification/state.rsnew file mode 100644index 000000000..9dbbe80a4--- /dev/null+++ b/crates/backend-uzu/src/inference/classification/state.rs@@ -0,0 +1,10 @@+use shoji::traits::State as StateTrait;++#[derive(Debug, Clone)]+pub struct State;++impl StateTrait for State {+ fn clone_boxed(&self) -> Box<dyn StateTrait> {+ Box::new(self.clone())+ }+}diff --git a/crates/backend-uzu/src/inference/container.rs b/crates/backend-uzu/src/inference/container.rsnew file mode 100644index 000000000..032b1d4d6--- /dev/null+++ b/crates/backend-uzu/src/inference/container.rs@@ -0,0 +1,24 @@+use std::sync::{Arc, Mutex};++pub struct Container<T> {+ pub value: Arc<Mutex<T>>,+}++unsafe impl<T> Send for Container<T> {}+unsafe impl<T> Sync for Container<T> {}++impl<T> Container<T> {+ pub fn new(value: T) -> Self {+ Self {+ value: Arc::new(Mutex::new(value)),+ }+ }+}++impl<T> Clone for Container<T> {+ fn clone(&self) -> Self {+ Self {+ value: self.value.clone(),+ }+ }+}diff --git a/crates/backend-uzu/src/inference/error.rs b/crates/backend-uzu/src/inference/error.rsnew file mode 100644index 000000000..dfc8f2b21--- /dev/null+++ b/crates/backend-uzu/src/inference/error.rs@@ -0,0 +1,23 @@+use crate::session::types::Error as ChatSessionError;++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error("Runtime error: {message}")]+ Runtime {+ message: String,+ },+ #[error("Session error: {message}")]+ Session {+ message: String,+ },+ #[error("Unable to load tokenizer")]+ UnableToLoadTokenizer,+}++impl From<ChatSessionError> for Error {+ fn from(error: ChatSessionError) -> Self {+ Error::Session {+ message: error.to_string(),+ }+ }+}diff --git a/crates/backend-uzu/src/inference/mod.rs b/crates/backend-uzu/src/inference/mod.rsnew file mode 100644index 000000000..87d6bea05--- /dev/null+++ b/crates/backend-uzu/src/inference/mod.rs@@ -0,0 +1,96 @@+mod chat;+mod classification;+mod container;+mod error;+mod model_metadata;+mod text_to_speech;++use std::pin::Pin;++pub use chat::Instance as ChatInstance;+pub use classification::Instance as ClassificationInstance;+pub use container::Container;+pub use error::Error;+pub use model_metadata::{ModelMetadata, resolve_model_metadata};+use shoji::{+ traits::{+ Backend as BackendTrait,+ backend::{+ Error as BackendError, chat_message as chat_message_trait, classification as classification_trait,+ text_to_speech as text_to_speech_trait,+ },+ },+ types::session::chat::ChatConfig as ShojiChatConfig,+};+pub use text_to_speech::Instance as TextToSpeechInstance;++use crate::TOOLCHAIN_VERSION;++pub struct Backend;++impl Backend {+ pub fn new() -> Self {+ Self+ }+}++impl BackendTrait for Backend {+ fn identifier(&self) -> String {+ "uzu".to_string()+ }++ fn version(&self) -> String {+ TOOLCHAIN_VERSION.to_string()+ }++ fn as_chat_via_message_capable(&self) -> Option<&dyn chat_message_trait::Backend> {+ Some(self)+ }++ fn as_classification_capable(&self) -> Option<&dyn classification_trait::Backend> {+ Some(self)+ }++ fn as_text_to_speech_capable(&self) -> Option<&dyn text_to_speech_trait::Backend> {+ Some(self)+ }+}++impl chat_message_trait::Backend for Backend {+ fn instance(+ &self,+ reference: String,+ config: ShojiChatConfig,+ ) -> Pin<Box<dyn Future<Output = Result<Box<dyn chat_message_trait::Instance>, BackendError>> + Send + '_>> {+ Box::pin(async move {+ let instance = ChatInstance::new(reference, config).map_err(|error| Box::new(error) as BackendError)?;+ Ok(Box::new(instance) as Box<dyn chat_message_trait::Instance>)+ })+ }+}++impl classification_trait::Backend for Backend {+ fn instance(+ &self,+ reference: String,+ _config: classification_trait::Config,+ ) -> Pin<Box<dyn Future<Output = Result<Box<dyn classification_trait::Instance>, BackendError>> + Send + '_>> {+ Box::pin(async move {+ let instance = ClassificationInstance::new(reference).map_err(|error| Box::new(error) as BackendError)?;+ Ok(Box::new(instance) as Box<dyn classification_trait::Instance>)+ })+ }+}++impl text_to_speech_trait::Backend for Backend {+ fn instance(+ &self,+ reference: String,+ _config: text_to_speech_trait::Config,+ ) -> Pin<Box<dyn Future<Output = Result<Box<dyn text_to_speech_trait::Instance>, BackendError>> + Send + '_>> {+ Box::pin(async move {+ let instance = TextToSpeechInstance::new(reference).map_err(|error| Box::new(error) as BackendError)?;+ Ok(Box::new(instance) as Box<dyn text_to_speech_trait::Instance>)+ })+ }+}diff --git a/crates/backend-uzu/src/inference/model_metadata.rs b/crates/backend-uzu/src/inference/model_metadata.rsnew file mode 100644index 000000000..29d5e1175--- /dev/null+++ b/crates/backend-uzu/src/inference/model_metadata.rs@@ -0,0 +1,25 @@+use std::{fs::File, io::BufReader, path::Path};++use shoji::types::model::ModelSpecialization;++use crate::config::{ModelMetadata as InnerModelMetadata, ModelType};++pub struct ModelMetadata {+ pub toolchain_version: String,+ pub specialization: ModelSpecialization,+}++pub fn resolve_model_metadata(model_path: &Path) -> Option<ModelMetadata> {+ let config_path = model_path.join("config.json");+ let file = File::open(&config_path).ok()?;+ let metadata: InnerModelMetadata = serde_json::from_reader(BufReader::new(file)).ok()?;+ let specialization = match metadata.model_type {+ ModelType::LanguageModel => ModelSpecialization::Chat {},+ ModelType::ClassifierModel => ModelSpecialization::Classification {},+ ModelType::TtsModel => ModelSpecialization::TextToSpeech {},+ };+ Some(ModelMetadata {+ toolchain_version: metadata.toolchain_version,+ specialization,+ })+}diff --git a/crates/backend-uzu/src/inference/text_to_speech/bridging.rs b/crates/backend-uzu/src/inference/text_to_speech/bridging.rsnew file mode 100644index 000000000..acb609440--- /dev/null+++ b/crates/backend-uzu/src/inference/text_to_speech/bridging.rs@@ -0,0 +1,16 @@+use shoji::types::basic::PcmBatch as ShojiPcmBatch;++use crate::{audio::AudioPcmBatch, session::types::Input};++pub fn build_input(input: &str) -> Input {+ Input::Text(input.to_string())+}++pub fn build_pcm_batch(pcm: &AudioPcmBatch) -> ShojiPcmBatch {+ ShojiPcmBatch {+ samples: pcm.samples().iter().map(|value| *value as f64).collect(),+ sample_rate: pcm.sample_rate(),+ channels: pcm.channels() as u32,+ lengths: pcm.lengths().iter().map(|value| *value as u32).collect(),+ }+}diff --git a/crates/backend-uzu/src/inference/text_to_speech/mod.rs b/crates/backend-uzu/src/inference/text_to_speech/mod.rsnew file mode 100644index 000000000..c28518346--- /dev/null+++ b/crates/backend-uzu/src/inference/text_to_speech/mod.rs@@ -0,0 +1,136 @@+#[cfg(metal_backend)]+mod bridging;+mod state;++use std::pin::Pin;++#[cfg(metal_backend)]+use bridging::{build_input, build_pcm_batch};+use futures::Stream;+#[cfg(not(metal_backend))]+use futures::stream;+#[cfg(metal_backend)]+use futures::{+ StreamExt,+ channel::mpsc::{self, UnboundedSender},+};+#[cfg(metal_backend)]+use rand::prelude::*;+use shoji::traits::{+ Instance as InstanceTrait, State as StateTrait,+ backend::{+ Error as BackendError,+ text_to_speech::{StreamInput, StreamOutput},+ },+};+#[cfg(metal_backend)]+use shoji::types::basic::PcmBatch as ShojiPcmBatch;+use state::State;+use tokio_util::sync::CancellationToken;++use crate::inference::Error;+#[cfg(metal_backend)]+use crate::{+ backends::metal::Metal,+ inference::Container,+ session::{TtsSession, config::TtsRunConfig, types::Input},+};++#[cfg(metal_backend)]+type UzuTtsSession = TtsSession<Metal>;++pub struct Instance {+ #[cfg(metal_backend)]+ session_container: Container<UzuTtsSession>,+}++impl Instance {+ #[cfg(metal_backend)]+ pub fn new(reference: String) -> Result<Self, Error> {+ let model_path = std::path::PathBuf::from(reference);+ let session = UzuTtsSession::new(model_path).map_err(Error::from)?;+ Ok(Self {+ session_container: Container::new(session),+ })+ }++ #[cfg(not(metal_backend))]+ pub fn new(_reference: String) -> Result<Self, Error> {+ Err(Error::Runtime {+ message: "Text-to-speech requires the metal backend".to_string(),+ })+ }+}++impl InstanceTrait for Instance {+ type StreamConfig = ();+ type StreamInput = StreamInput;+ type StreamOutput = StreamOutput;++ fn state(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn StateTrait>, BackendError>> + Send + '_>> {+ Box::pin(async move { Ok(Box::new(State) as Box<dyn StateTrait>) })+ }++ #[cfg(metal_backend)]+ fn stream<'a>(+ &'a self,+ input: &'a Self::StreamInput,+ _state: &'a mut dyn StateTrait,+ _config: Self::StreamConfig,+ cancel_token: CancellationToken,+ ) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {+ let input = build_input(input);+ let session_container = self.session_container.clone();+ let cancel_for_run = cancel_token.clone();+ let (sender, receiver) = mpsc::unbounded::<Result<ShojiPcmBatch, BackendError>>();++ std::thread::spawn(move || {+ run(session_container, input, cancel_for_run, sender);+ });++ Box::pin(receiver.take_until(cancel_token.cancelled_owned()))+ }++ #[cfg(not(metal_backend))]+ fn stream<'a>(+ &'a self,+ _input: &'a Self::StreamInput,+ _state: &'a mut dyn StateTrait,+ _config: Self::StreamConfig,+ _cancel_token: CancellationToken,+ ) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {+ Box::pin(stream::once(async {+ Err(Box::new(Error::Runtime {+ message: "Text-to-speech requires the metal backend".to_string(),+ }) as BackendError)+ }))+ }+}++#[cfg(metal_backend)]+fn run(+ session_container: Container<UzuTtsSession>,+ input: Input,+ _cancel_token: CancellationToken,+ sender: UnboundedSender<Result<ShojiPcmBatch, BackendError>>,+) {+ let result = {+ let mut session = match session_container.value.lock() {+ Ok(session) => session,+ Err(error) => {+ let _ = sender.unbounded_send(Err(Box::new(Error::Runtime {+ message: error.to_string(),+ }) as BackendError));+ return;+ },+ };+ let seed = rand::rng().random::<u64>();+ let config = TtsRunConfig::default();+ session.synthesize_with_seed_and_config(input, seed, &config)+ };+ let result = match result {+ Ok(pcm) => Ok(build_pcm_batch(&pcm)),+ Err(error) => Err(Box::new(Error::from(error)) as BackendError),+ };+ let _ = sender.unbounded_send(result);+}diff --git a/crates/backend-uzu/src/inference/text_to_speech/state.rs b/crates/backend-uzu/src/inference/text_to_speech/state.rsnew file mode 100644index 000000000..9dbbe80a4--- /dev/null+++ b/crates/backend-uzu/src/inference/text_to_speech/state.rs@@ -0,0 +1,10 @@+use shoji::traits::State as StateTrait;++#[derive(Debug, Clone)]+pub struct State;++impl StateTrait for State {+ fn clone_boxed(&self) -> Box<dyn StateTrait> {+ Box::new(self.clone())+ }+}diff --git a/crates/backend-uzu/src/inference_backend.rs b/crates/backend-uzu/src/inference_backend.rsdeleted file mode 100644index 6d1bb5482..000000000--- a/crates/backend-uzu/src/inference_backend.rs+++ /dev/null@@ -1,115 +0,0 @@-use std::{- path::PathBuf,- pin::Pin,- sync::{Arc, Mutex},-};--use futures::{Stream, stream};-use shoji::{- traits::{- Backend as BackendTrait, Instance as InstanceTrait, State as StateTrait,- backend::{- Error as BackendError,- chat_token::{self, StreamInput, StreamOutput},- },- },- types::session::chat::{Config, StreamConfig},-};-use tokio_util::sync::CancellationToken;--use crate::{- TOOLCHAIN_VERSION,- session::{ChatSession, config::DecodingConfig},-};--#[derive(Debug, thiserror::Error)]-pub enum Error {- #[error("Unable to load model")]- UnableToLoad,- #[error("Unable to create state")]- UnableToCreateState,- #[error("Stream failed")]- StreamFailed,-}--pub struct Backend;--impl Backend {- pub fn new() -> Result<Self, Error> {- Ok(Self)- }-}--impl BackendTrait for Backend {- fn identifier(&self) -> String {- "uzu".to_string()- }-- fn version(&self) -> String {- TOOLCHAIN_VERSION.to_string()- }-- fn as_chat_via_token_capable(&self) -> Option<&dyn chat_token::Backend> {- Some(self)- }-}--impl chat_token::Backend for Backend {- fn instance(- &self,- reference: String,- _config: Config,- ) -> Pin<Box<dyn Future<Output = Result<Box<dyn chat_token::Instance>, BackendError>> + Send + '_>> {- Box::pin(async move {- let path = PathBuf::from(&reference);- let session = ChatSession::new(path, DecodingConfig::default())- .map_err(|_| Box::new(Error::UnableToLoad) as BackendError)?;- Ok(Box::new(Instance {- session: Arc::new(Mutex::new(session)),- }) as Box<dyn chat_token::Instance>)- })- }-}--pub struct Instance {- session: Arc<Mutex<ChatSession>>,-}-unsafe impl Send for Instance {}-unsafe impl Sync for Instance {}--#[derive(Debug, Clone)]-pub struct State;--impl StateTrait for State {- fn clone_boxed(&self) -> Box<dyn StateTrait> {- Box::new(self.clone())- }-}--impl InstanceTrait for Instance {- type StreamConfig = StreamConfig;- type StreamInput = StreamInput;- type StreamOutput = StreamOutput;-- fn state(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn StateTrait>, BackendError>> + Send + '_>> {- let reset = self- .session- .lock()- .map_err(|_| Error::UnableToCreateState)- .and_then(|mut guard| guard.reset().map_err(|_| Error::UnableToCreateState));- Box::pin(async move {- reset.map_err(|error| Box::new(error) as BackendError)?;- Ok(Box::new(State) as Box<dyn StateTrait>)- })- }-- fn stream<'a>(- &'a self,- _input: &'a Self::StreamInput,- _state: &'a mut dyn StateTrait,- _config: Self::StreamConfig,- _cancel_token: CancellationToken,- ) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {- Box::pin(stream::once(async { Err(Box::new(Error::StreamFailed) as BackendError) }))- }-}diff --git a/crates/backend-uzu/src/lib.rs b/crates/backend-uzu/src/lib.rsindex ebd122ad6..736ba013d 100644--- a/crates/backend-uzu/src/lib.rs+++ b/crates/backend-uzu/src/lib.rs@@ -8,7 +8,7 @@ mod config;mod data_type;mod encodable_block;mod forward_pass;-pub mod inference_backend;+pub mod inference;mod language_model;mod parameters;mod speculators;diff --git a/crates/backend-uzu/src/utils/version.rs b/crates/backend-uzu/src/utils/version.rsindex aacab5d53..9a87fe686 100644--- a/crates/backend-uzu/src/utils/version.rs+++ b/crates/backend-uzu/src/utils/version.rs@@ -1,2 +1,2 @@pub const VERSION: &str = env!("CARGO_PKG_VERSION");-pub const TOOLCHAIN_VERSION: &str = "0.6.12";+pub const TOOLCHAIN_VERSION: &str = "0.6.13";diff --git a/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rs b/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rsindex c278e8b7d..f481101f7 100644--- a/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rs+++ b/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rs@@ -11,7 +11,7 @@ use backend_uzu::{types::{Input, Message, Output},},};-use shoji::types::session::chat::Feature;+use shoji::types::basic::Feature;use test_tag::tag;use tokenizers::Tokenizer;diff --git a/crates/benchmarks/Cargo.toml b/crates/benchmarks/Cargo.tomlindex db37005d9..17193d91f 100644--- a/crates/benchmarks/Cargo.toml+++ b/crates/benchmarks/Cargo.toml@@ -8,7 +8,7 @@ authors.workspace = truerepository.workspace = true[dependencies]-uzu.workspace = true+backend-uzu.workspace = trueserde.workspace = truesysinfo.workspace = true@@ -18,4 +18,4 @@ mach2.workspace = true[features]default = ["metal"]-metal = ["uzu/metal"]+metal = ["backend-uzu/metal"]diff --git a/crates/benchmarks/src/runner/runner.rs b/crates/benchmarks/src/runner/runner.rsindex 81371ca74..272d6c64e 100644--- a/crates/benchmarks/src/runner/runner.rs+++ b/crates/benchmarks/src/runner/runner.rs@@ -3,8 +3,7 @@ use std::{time::{SystemTime, UNIX_EPOCH},};-use sysinfo::System;-use uzu::{+use backend_uzu::{VERSION,session::{ChatSession,@@ -13,6 +12,7 @@ use uzu::{types::{Input, Output},},};+use sysinfo::System;use crate::runner::{helpers::get_memory_usage,diff --git a/crates/benchmarks/src/runner/types/result.rs b/crates/benchmarks/src/runner/types/result.rsindex c25082c87..7f90530f2 100644--- a/crates/benchmarks/src/runner/types/result.rs+++ b/crates/benchmarks/src/runner/types/result.rs@@ -1,5 +1,5 @@+use backend_uzu::ConfigDataType;use serde::{Deserialize, Serialize};-use uzu::ConfigDataType;use crate::runner::types::{Device, Task};diff --git a/crates/benchmarks/src/runner/types/task.rs b/crates/benchmarks/src/runner/types/task.rsindex 4c9844e96..0d64e52cc 100644--- a/crates/benchmarks/src/runner/types/task.rs+++ b/crates/benchmarks/src/runner/types/task.rs@@ -1,5 +1,5 @@+use backend_uzu::session::types::Message;use serde::{Deserialize, Serialize};-use uzu::session::types::Message;#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Task {diff --git a/crates/bindings/src/lib.rs b/crates/bindings/src/lib.rsindex 1c877c90b..a957e8aa5 100644--- a/crates/bindings/src/lib.rs+++ b/crates/bindings/src/lib.rs@@ -1,22 +1,42 @@+mod napi;+mod pyo3;+mod uniffi;+mod wasm;+use proc_macro::TokenStream;use quote::quote;use syn::{- Ident, LitStr, Token,+ Attribute, Ident, ImplItem, ItemImpl, Token,parse::{Parse, ParseStream},parse_macro_input,};-enum BindingKind {+pub(crate) enum BindingKind {Enum,Struct,Class,- Impl,+ ClassCloneable,+ Alias,+ Implementation,+ Method,+ Constructor,+ Factory,+ FactoryWithCallback,+ Getter,+ Setter,Error,}+pub(crate) enum MethodFlavor {+ Plain,+ Constructor,+ Factory,+ Getter,+ Setter,+}+struct ExportArguments {kind: BindingKind,- name: Option<LitStr>,}impl Parse for ExportArguments {@@ -26,44 +46,29 @@ impl Parse for ExportArguments {"Enum" => BindingKind::Enum,"Struct" => BindingKind::Struct,"Class" => BindingKind::Class,- "Impl" => BindingKind::Impl,+ "ClassCloneable" => BindingKind::ClassCloneable,+ "Alias" => BindingKind::Alias,+ "Implementation" => BindingKind::Implementation,+ "Method" => BindingKind::Method,+ "Constructor" => BindingKind::Constructor,+ "Factory" => BindingKind::Factory,+ "FactoryWithCallback" => BindingKind::FactoryWithCallback,+ "Getter" => BindingKind::Getter,+ "Setter" => BindingKind::Setter,"Error" => BindingKind::Error,other => {return Err(syn::Error::new(identifier.span(), format!("Unknown binding kind: {other}")));},};-- let name = if input.peek(Token![,]) {- input.parse::<Token![,]>()?;- let key: Ident = input.parse()?;- if key != "name" {- return Err(syn::Error::new(key.span(), format!("Unknown parameter: {key}, expected 'name'")));- }- if matches!(kind, BindingKind::Impl) {- return Err(syn::Error::new(key.span(), "'name' parameter is not supported for Impl"));- }- input.parse::<Token![=]>()?;- Some(input.parse::<LitStr>()?)- } else {- None- };-+ if input.peek(Token![,]) {+ return Err(input.error("bindings::export accepts a single kind argument"));+ }Ok(ExportArguments {kind,- name,})}}-fn uniffi_name_attribute(name: &Option<LitStr>) -> proc_macro2::TokenStream {- match name {- Some(name) => quote! {- #[cfg_attr(feature = "bindings-uniffi", uniffi(name = #name))]- },- None => quote! {},- }-}-#[proc_macro_attribute]pub fn export(arguments: TokenStream,@@ -71,84 +76,270 @@ pub fn export() -> TokenStream {let ExportArguments {kind,- name,} = parse_macro_input!(arguments as ExportArguments);- let item = parse_macro_input!(item as syn::Item);- let uniffi_name = uniffi_name_attribute(&name);-- let attributes = match kind {- BindingKind::Enum => quote! {- #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Enum))]- #[cfg_attr(feature = "bindings-napi", napi_derive::napi)]- #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass(eq, from_py_object))]- #[cfg_attr(feature = "bindings-wasm", derive(tsify::Tsify))]- #[cfg_attr(feature = "bindings-wasm", tsify(into_wasm_abi, from_wasm_abi))]- #uniffi_name++ match kind {+ BindingKind::Enum => {+ let item = parse_macro_input!(item as syn::Item);+ let item_enum = match &item {+ syn::Item::Enum(item_enum) => item_enum,+ _ => {+ return syn::Error::new_spanned(&item, "bindings::export(Enum) must be applied to an enum")+ .to_compile_error()+ .into();+ },+ };++ let mut has_unit_fields = false;+ let mut has_named_fields = false;+ for variant in &item_enum.variants {+ match variant.fields {+ syn::Fields::Unit => has_unit_fields = true,+ syn::Fields::Named(_) => has_named_fields = true,+ syn::Fields::Unnamed(_) => {+ return syn::Error::new_spanned(+ &variant.fields,+ "bindings::export(Enum) variants must use named fields (use `{}` for empty variants), tuple variants are not supported",+ )+ .to_compile_error()+ .into();+ },+ }+ }+ if has_unit_fields && has_named_fields {+ return syn::Error::new_spanned(+ &item_enum.ident,+ "bindings::export(Enum) variants must all be unit (e.g. `Foo`) or all be named (e.g. `Foo {}`, `Foo { x: i64 }`), mixing is not supported",+ )+ .to_compile_error()+ .into();+ }++ let enum_is_data = has_named_fields;+ let uniffi = uniffi::attributes(&kind);+ let pyo3 = pyo3::attributes(&kind);+ let wasm = wasm::attributes(&kind);++ if enum_is_data {+ let variant_classes = napi::enum_variant_classes(&item_enum.ident, &item_enum.variants);+ quote! {+ #uniffi+ #pyo3+ #wasm+ #item+ #variant_classes+ }+ .into()+ } else {+ let napi = napi::attributes(&kind);+ quote! {+ #napi+ #uniffi+ #pyo3+ #wasm+ #item+ }+ .into()+ }},- BindingKind::Struct => quote! {- #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Record))]- #[cfg_attr(feature = "bindings-napi", napi_derive::napi(object))]- #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass(get_all, from_py_object))]- #[cfg_attr(feature = "bindings-wasm", derive(tsify::Tsify))]- #[cfg_attr(feature = "bindings-wasm", tsify(into_wasm_abi, from_wasm_abi))]- #uniffi_name+ BindingKind::Struct | BindingKind::Class | BindingKind::ClassCloneable => {+ let item = parse_macro_input!(item as syn::Item);+ let type_name = match &item {+ syn::Item::Struct(item_struct) => Some(&item_struct.ident),+ _ => None,+ };+ let napi = napi::attributes(&kind);+ let uniffi = uniffi::attributes(&kind);+ let pyo3 = pyo3::attributes(&kind);+ let wasm = wasm::attributes(&kind);+ let napi_value = match (&kind, type_name) {+ (BindingKind::Struct, Some(ident)) => napi::struct_value_implementations(ident),+ (BindingKind::ClassCloneable, Some(ident)) => napi::class_value_implementations(ident),+ _ => quote! {},+ };+ quote! {+ #napi+ #uniffi+ #pyo3+ #wasm+ #item+ #napi_value+ }+ .into()},- BindingKind::Class => quote! {- #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Object))]- #[cfg_attr(feature = "bindings-napi", napi_derive::napi)]- #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass)]- #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen)]- #uniffi_name+ BindingKind::Alias => {+ let item = parse_macro_input!(item as syn::ItemType);+ let napi = napi::attributes(&kind);+ let uniffi = uniffi::attributes(&kind);+ let pyo3 = pyo3::attributes(&kind);+ let wasm = wasm::attributes(&kind);+ quote! {+ #napi+ #uniffi+ #pyo3+ #wasm+ #item+ }+ .into()+ },+ BindingKind::Implementation => {+ let mut item_implementation = match syn::parse::<ItemImpl>(item) {+ Ok(item_implementation) => item_implementation,+ Err(error) => return error.to_compile_error().into(),+ };+ let self_type = item_implementation.self_ty.clone();++ let mut callback_factories: Vec<syn::ImplItemFn> = Vec::new();+ item_implementation.items.retain(|item| match item {+ ImplItem::Fn(method) if method_has_factory_with_callback(method) => {+ callback_factories.push(method.clone());+ false+ },+ _ => true,+ });++ for item in &mut item_implementation.items {+ if let ImplItem::Fn(method) = item {+ rewrite_method_attributes(&mut method.attrs);+ }+ }++ let callback_expansions: Vec<proc_macro2::TokenStream> = callback_factories+ .iter()+ .map(|method| {+ let napi_expansion = napi::factory_with_callback(&self_type, method);+ let uniffi_expansion = uniffi::factory_with_callback(&self_type, method);+ quote! {+ #napi_expansion+ #uniffi_expansion+ }+ })+ .collect();++ let napi = napi::attributes(&kind);+ let uniffi = uniffi::attributes(&kind);+ let pyo3 = pyo3::attributes(&kind);+ let wasm = wasm::attributes(&kind);+ quote! {+ #napi+ #uniffi+ #pyo3+ #wasm+ #item_implementation+ #( #callback_expansions )*+ }+ .into()},- BindingKind::Impl => quote! {- #[cfg_attr(feature = "bindings-uniffi", uniffi::export)]- #[cfg_attr(feature = "bindings-napi", napi_derive::napi)]- #[cfg_attr(feature = "bindings-pyo3", pyo3::pymethods)]- #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen)]+ BindingKind::Method+ | BindingKind::Constructor+ | BindingKind::Factory+ | BindingKind::FactoryWithCallback+ | BindingKind::Getter+ | BindingKind::Setter => {+ let tokens = proc_macro2::TokenStream::from(item);+ quote! { #tokens }.into()},BindingKind::Error => {- let type_name = match &item {- syn::Item::Enum(item_enum) => &item_enum.ident,+ let item = parse_macro_input!(item as syn::Item);+ let item_enum = match &item {+ syn::Item::Enum(item_enum) => item_enum,_ => {return syn::Error::new_spanned(&item, "Error can only be applied to enums").to_compile_error().into();},};-- return quote! {- #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Error))]- #uniffi_name+ let type_name = &item_enum.ident;+ let all_unit_variants =+ item_enum.variants.iter().all(|variant| matches!(variant.fields, syn::Fields::Unit));+ let napi_attribute = if all_unit_variants {+ quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi(string_enum))]+ }+ } else {+ quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi)]+ }+ };+ let napi_value = if all_unit_variants {+ quote! {}+ } else {+ napi::struct_value_implementations(type_name)+ };+ let uniffi = uniffi::error_attribute();+ let napi_implementations = napi::error_implementations(type_name);+ let pyo3_implementations = pyo3::error_implementations(type_name);+ let wasm_implementations = wasm::error_implementations(type_name);+ quote! {+ #napi_attribute+ #uniffi#item+ #napi_value+ #napi_implementations+ #pyo3_implementations+ #wasm_implementations+ }+ .into()+ },+ }+}- #[cfg(feature = "bindings-napi")]- impl From<#type_name> for napi::Error {- fn from(error: #type_name) -> Self {- napi::Error::from_reason(error.to_string())- }+fn rewrite_method_attributes(attributes: &mut Vec<Attribute>) {+ let mut rewritten_attributes: Vec<Attribute> = Vec::with_capacity(attributes.len());+ for attribute in attributes.drain(..) {+ match method_flavor(&attribute) {+ Some(flavor) => {+ rewritten_attributes.push(napi::method_attribute(&flavor));+ if let Some(attribute) = uniffi::method_attribute(&flavor) {+ rewritten_attributes.push(attribute);}-- #[cfg(feature = "bindings-pyo3")]- impl From<#type_name> for pyo3::PyErr {- fn from(error: #type_name) -> Self {- pyo3::exceptions::PyRuntimeError::new_err(error.to_string())- }+ if let Some(attribute) = pyo3::method_attribute(&flavor) {+ rewritten_attributes.push(attribute);}+ },+ None => rewritten_attributes.push(attribute),+ }+ }+ *attributes = rewritten_attributes;+}- #[cfg(feature = "bindings-wasm")]- impl From<#type_name> for wasm_bindgen::JsValue {- fn from(error: #type_name) -> Self {- wasm_bindgen::JsValue::from_str(&error.to_string())- }- }- }- .into();- },- };+fn method_flavor(attribute: &Attribute) -> Option<MethodFlavor> {+ if !is_exportable_attribute(attribute) {+ return None;+ }+ let arguments: ExportArguments = attribute.parse_args().ok()?;+ match arguments.kind {+ BindingKind::Method => Some(MethodFlavor::Plain),+ BindingKind::Constructor => Some(MethodFlavor::Constructor),+ BindingKind::Factory => Some(MethodFlavor::Factory),+ BindingKind::Getter => Some(MethodFlavor::Getter),+ BindingKind::Setter => Some(MethodFlavor::Setter),+ _ => None,+ }+}- quote! {- #attributes- #item+fn method_has_factory_with_callback(method: &syn::ImplItemFn) -> bool {+ method.attrs.iter().any(|attribute| {+ if !is_exportable_attribute(attribute) {+ return false;+ }+ let Ok(arguments): syn::Result<ExportArguments> = attribute.parse_args() else {+ return false;+ };+ matches!(arguments.kind, BindingKind::FactoryWithCallback)+ })+}++fn is_exportable_attribute(attribute: &Attribute) -> bool {+ let path = attribute.path();+ let Some(last) = path.segments.last() else {+ return false;+ };+ if last.ident != "export" {+ return false;+ }+ match path.segments.first() {+ Some(first) if first.ident == "bindings" || first.ident == "export" => true,+ _ => false,}- .into()}diff --git a/crates/bindings/src/napi.rs b/crates/bindings/src/napi.rsnew file mode 100644index 000000000..abfe1a720--- /dev/null+++ b/crates/bindings/src/napi.rs@@ -0,0 +1,371 @@+use quote::{format_ident, quote};+use syn::{Attribute, Ident, Token, Variant, parse_quote, punctuated::Punctuated};++use crate::{BindingKind, MethodFlavor};++pub fn attributes(kind: &BindingKind) -> proc_macro2::TokenStream {+ match kind {+ BindingKind::Enum => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi(string_enum))]+ },+ BindingKind::Class => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi)]+ },+ BindingKind::ClassCloneable => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi(constructor))]+ },+ BindingKind::Struct => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi(object))]+ },+ BindingKind::Implementation => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi)]+ },+ BindingKind::Alias => quote! {+ #[cfg_attr(feature = "bindings-napi", napi_derive::napi)]+ },+ _ => quote! {},+ }+}++pub fn method_attribute(flavor: &MethodFlavor) -> Attribute {+ match flavor {+ MethodFlavor::Plain => parse_quote! {+ #[cfg_attr(feature = "bindings-napi", napi)]+ },+ MethodFlavor::Constructor => parse_quote! {+ #[cfg_attr(feature = "bindings-napi", napi(constructor))]+ },+ MethodFlavor::Factory => parse_quote! {+ #[cfg_attr(feature = "bindings-napi", napi(factory))]+ },+ MethodFlavor::Getter => parse_quote! {+ #[cfg_attr(feature = "bindings-napi", napi(getter))]+ },+ MethodFlavor::Setter => parse_quote! {+ #[cfg_attr(feature = "bindings-napi", napi(setter))]+ },+ }+}++pub fn struct_value_implementations(type_name: &Ident) -> proc_macro2::TokenStream {+ quote! {+ #[cfg(feature = "bindings-napi")]+ const _: () = {+ use napi::bindgen_prelude::ToNapiValue;+ use napi::sys::{napi_env, napi_value};++ impl ToNapiValue for &#type_name {+ unsafe fn to_napi_value(env: napi_env, value: Self) -> napi::Result<napi_value> {+ let owned: #type_name = ::core::clone::Clone::clone(value);+ <#type_name as ToNapiValue>::to_napi_value(env, owned)+ }+ }++ impl ToNapiValue for &mut #type_name {+ unsafe fn to_napi_value(env: napi_env, value: Self) -> napi::Result<napi_value> {+ let owned: #type_name = ::core::clone::Clone::clone(value);+ <#type_name as ToNapiValue>::to_napi_value(env, owned)+ }+ }+ };+ }+}++pub fn class_value_implementations(type_name: &Ident) -> proc_macro2::TokenStream {+ quote! {+ #[cfg(feature = "bindings-napi")]+ const _: () = {+ use napi::bindgen_prelude::{FromNapiValue, ToNapiValue};+ use napi::sys::{napi_env, napi_value};++ impl ToNapiValue for &#type_name {+ unsafe fn to_napi_value(env: napi_env, value: Self) -> napi::Result<napi_value> {+ let owned: #type_name = ::core::clone::Clone::clone(value);+ <#type_name as ToNapiValue>::to_napi_value(env, owned)+ }+ }++ impl ToNapiValue for &mut #type_name {+ unsafe fn to_napi_value(env: napi_env, value: Self) -> napi::Result<napi_value> {+ let owned: #type_name = ::core::clone::Clone::clone(value);+ <#type_name as ToNapiValue>::to_napi_value(env, owned)+ }+ }++ impl FromNapiValue for #type_name {+ unsafe fn from_napi_value(env: napi_env, value: napi_value) -> napi::Result<Self> {+ let reference = <&#type_name as FromNapiValue>::from_napi_value(env, value)?;+ Ok(::core::clone::Clone::clone(reference))+ }+ }+ };+ }+}++pub fn enum_variant_classes(+ enum_ident: &Ident,+ variants: &Punctuated<Variant, Token![,]>,+) -> proc_macro2::TokenStream {+ let union_alias_ident = format_ident!("{}Napi", enum_ident);+ let variant_count = variants.len();+ let either_type_ident: Option<Ident> = match variant_count {+ 1 => None,+ 2 => Some(format_ident!("Either")),+ n if (3..=26).contains(&n) => Some(format_ident!("Either{n}")),+ n => {+ return syn::Error::new_spanned(+ enum_ident,+ format!("bindings::export(Enum) supports up to 26 data variants (found {n})"),+ )+ .to_compile_error();+ },+ };+ let either_variant_labels: Vec<Ident> =+ (0..variant_count).map(|index| format_ident!("{}", (b'A' + index as u8) as char)).collect();++ let mut variant_class_items = Vec::new();+ let mut from_variant_impls = Vec::new();+ let mut to_napi_match_arms = Vec::new();+ let mut from_napi_try_branches = Vec::new();+ let mut union_type_params = Vec::new();+ let mut enum_to_union_arms = Vec::new();+ let mut union_to_enum_arms = Vec::new();++ for (variant_index, variant) in variants.iter().enumerate() {+ let variant_ident = &variant.ident;+ let variant_class_ident = format_ident!("{}{}", enum_ident, variant_ident);+ let either_label = &either_variant_labels[variant_index];+ union_type_params.push(quote! { #variant_class_ident });+ let named_fields = match &variant.fields {+ syn::Fields::Named(named) => &named.named,+ _ => unreachable!("non-named variants must be rejected before reaching this function"),+ };+ let field_declarations: Vec<proc_macro2::TokenStream> = named_fields+ .iter()+ .map(|field| {+ let field_ident = field.ident.as_ref().expect("named field");+ let field_type = &field.ty;+ quote! { pub #field_ident: #field_type }+ })+ .collect();+ let field_idents: Vec<&Ident> =+ named_fields.iter().map(|field| field.ident.as_ref().expect("named field")).collect();++ let variant_class_value_impls = class_value_implementations(&variant_class_ident);+ variant_class_items.push(quote! {+ #[cfg(feature = "bindings-napi")]+ #[napi_derive::napi(constructor)]+ #[derive(Clone)]+ pub struct #variant_class_ident {+ #( #field_declarations ),*+ }++ #variant_class_value_impls+ });++ from_variant_impls.push(quote! {+ #[cfg(feature = "bindings-napi")]+ impl From<#variant_class_ident> for #enum_ident {+ fn from(value: #variant_class_ident) -> Self {+ #enum_ident::#variant_ident {+ #( #field_idents: value.#field_idents ),*+ }+ }+ }+ });++ to_napi_match_arms.push(quote! {+ #enum_ident::#variant_ident { #( #field_idents ),* } => {+ ToNapiValue::to_napi_value(+ env,+ #variant_class_ident { #( #field_idents ),* },+ )+ }+ });++ from_napi_try_branches.push(quote! {+ if let Ok(instance) =+ ClassInstance::<#variant_class_ident>::from_napi_value(env, val)+ {+ let inner: &#variant_class_ident =+ <ClassInstance<#variant_class_ident> as ::core::ops::Deref>::deref(&instance);+ return Ok(#enum_ident::#variant_ident {+ #( #field_idents: ::core::clone::Clone::clone(&inner.#field_idents) ),*+ });+ }+ });++ let wrap_expression = match &either_type_ident {+ Some(either_ident) => quote! {+ napi::bindgen_prelude::#either_ident::#either_label(+ #variant_class_ident { #( #field_idents ),* },+ )+ },+ None => quote! {+ #variant_class_ident { #( #field_idents ),* }+ },+ };+ enum_to_union_arms.push(quote! {+ #enum_ident::#variant_ident { #( #field_idents ),* } => { #wrap_expression }+ });++ let unwrap_pattern = match &either_type_ident {+ Some(either_ident) => quote! {+ napi::bindgen_prelude::#either_ident::#either_label(inner)+ },+ None => quote! { inner },+ };+ union_to_enum_arms.push(quote! {+ #unwrap_pattern => { #enum_ident::from(inner) }+ });+ }++ let expected_message = format!("Expected instance of variant class for {}", enum_ident);++ let union_js_name = enum_ident.to_string();+ let union_alias_definition = match &either_type_ident {+ Some(either_ident) => quote! {+ #[cfg(feature = "bindings-napi")]+ #[napi_derive::napi(js_name = #union_js_name)]+ pub type #union_alias_ident =+ napi::bindgen_prelude::#either_ident<#( #union_type_params ),*>;+ },+ None => {+ let single_variant_class = &union_type_params[0];+ quote! {+ #[cfg(feature = "bindings-napi")]+ #[napi_derive::napi(js_name = #union_js_name)]+ pub type #union_alias_ident = #single_variant_class;+ }+ },+ };++ let union_from_impls = if either_type_ident.is_some() {+ quote! {+ #[cfg(feature = "bindings-napi")]+ impl From<#enum_ident> for #union_alias_ident {+ fn from(value: #enum_ident) -> Self {+ match value {+ #( #enum_to_union_arms ),*+ }+ }+ }++ #[cfg(feature = "bindings-napi")]+ impl From<#union_alias_ident> for #enum_ident {+ fn from(value: #union_alias_ident) -> Self {+ match value {+ #( #union_to_enum_arms ),*+ }+ }+ }+ }+ } else {+ quote! {}+ };++ quote! {+ #( #variant_class_items )*+ #( #from_variant_impls )*++ #union_alias_definition+ #union_from_impls++ #[cfg(feature = "bindings-napi")]+ const _: () = {+ use napi::bindgen_prelude::{ClassInstance, FromNapiValue, ToNapiValue};+ use napi::sys::{napi_env, napi_value};++ impl FromNapiValue for #enum_ident {+ unsafe fn from_napi_value(+ env: napi_env,+ val: napi_value,+ ) -> napi::Result<Self> {+ #( #from_napi_try_branches )*+ Err(napi::Error::from_reason(#expected_message))+ }+ }++ impl ToNapiValue for #enum_ident {+ unsafe fn to_napi_value(+ env: napi_env,+ val: Self,+ ) -> napi::Result<napi_value> {+ match val {+ #( #to_napi_match_arms ),*+ }+ }+ }++ impl ToNapiValue for &#enum_ident {+ unsafe fn to_napi_value(+ env: napi_env,+ val: Self,+ ) -> napi::Result<napi_value> {+ let owned: #enum_ident = ::core::clone::Clone::clone(val);+ <#enum_ident as ToNapiValue>::to_napi_value(env, owned)+ }+ }++ impl ToNapiValue for &mut #enum_ident {+ unsafe fn to_napi_value(+ env: napi_env,+ val: Self,+ ) -> napi::Result<napi_value> {+ let owned: #enum_ident = ::core::clone::Clone::clone(val);+ <#enum_ident as ToNapiValue>::to_napi_value(env, owned)+ }+ }+ };+ }+}++pub fn factory_with_callback(+ self_type: &syn::Type,+ method: &syn::ImplItemFn,+) -> proc_macro2::TokenStream {+ let method_ident = &method.sig.ident;+ let body = &method.block;+ quote! {+ #[cfg(feature = "bindings-napi")]+ #[napi_derive::napi]+ impl #self_type {+ #[napi(factory)]+ pub fn #method_ident(+ callback: napi::bindgen_prelude::Function<'static, (), ()>,+ ) -> napi::Result<Self> {+ let threadsafe_function = callback+ .build_threadsafe_function()+ .callee_handled::<false>()+ .build()+ .map_err(|error| napi::Error::from_reason(error.to_string()))?;+ let callback: Box<dyn Fn() + Send + Sync> = Box::new(move || {+ let _ = threadsafe_function.call(+ (),+ napi::threadsafe_function::ThreadsafeFunctionCallMode::NonBlocking,+ );+ });+ Ok(#body)+ }+ }+ }+}++pub fn error_implementations(type_name: &Ident) -> proc_macro2::TokenStream {+ quote! {+ #[cfg(feature = "bindings-napi")]+ impl From<#type_name> for napi::Error {+ fn from(error: #type_name) -> Self {+ napi::Error::from_reason(error.to_string())+ }+ }++ #[cfg(feature = "bindings-napi")]+ impl From<#type_name> for napi::JsError {+ fn from(error: #type_name) -> Self {+ let napi_error: napi::Error = error.into();+ napi::JsError::from(napi_error)+ }+ }+ }+}diff --git a/crates/bindings/src/pyo3.rs b/crates/bindings/src/pyo3.rsnew file mode 100644index 000000000..a1ea43984--- /dev/null+++ b/crates/bindings/src/pyo3.rs@@ -0,0 +1,45 @@+use quote::quote;+use syn::{Attribute, Ident, parse_quote};++use crate::{BindingKind, MethodFlavor};++pub fn attributes(kind: &BindingKind) -> proc_macro2::TokenStream {+ match kind {+ BindingKind::Enum => quote! {+ #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass(eq, from_py_object))]+ },+ BindingKind::Struct => quote! {+ #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass(get_all, from_py_object))]+ },+ BindingKind::Class | BindingKind::ClassCloneable => quote! {+ #[cfg_attr(feature = "bindings-pyo3", pyo3::pyclass)]+ },+ BindingKind::Implementation => quote! {+ #[cfg_attr(feature = "bindings-pyo3", pyo3::pymethods)]+ },+ _ => quote! {},+ }+}++pub fn method_attribute(flavor: &MethodFlavor) -> Option<Attribute> {+ match flavor {+ MethodFlavor::Plain | MethodFlavor::Getter | MethodFlavor::Setter => None,+ MethodFlavor::Constructor => Some(parse_quote! {+ #[cfg_attr(feature = "bindings-pyo3", new)]+ }),+ MethodFlavor::Factory => Some(parse_quote! {+ #[cfg_attr(feature = "bindings-pyo3", staticmethod)]+ }),+ }+}++pub fn error_implementations(type_name: &Ident) -> proc_macro2::TokenStream {+ quote! {+ #[cfg(feature = "bindings-pyo3")]+ impl From<#type_name> for pyo3::PyErr {+ fn from(error: #type_name) -> Self {+ pyo3::exceptions::PyRuntimeError::new_err(error.to_string())+ }+ }+ }+}diff --git a/crates/bindings/src/uniffi.rs b/crates/bindings/src/uniffi.rsnew file mode 100644index 000000000..02885481c--- /dev/null+++ b/crates/bindings/src/uniffi.rs@@ -0,0 +1,91 @@+use quote::{format_ident, quote};+use syn::{Attribute, Ident, parse_quote};++use crate::{BindingKind, MethodFlavor};++pub fn attributes(kind: &BindingKind) -> proc_macro2::TokenStream {+ match kind {+ BindingKind::Enum => quote! {+ #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Enum))]+ },+ BindingKind::Struct => quote! {+ #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Record))]+ },+ BindingKind::Class => quote! {+ #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Object))]+ },+ BindingKind::ClassCloneable => quote! {+ #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Record))]+ },+ BindingKind::Implementation => quote! {+ #[cfg_attr(feature = "bindings-uniffi", uniffi::export)]+ },+ _ => quote! {},+ }+}++pub fn method_attribute(flavor: &MethodFlavor) -> Option<Attribute> {+ match flavor {+ MethodFlavor::Plain | MethodFlavor::Getter | MethodFlavor::Setter => None,+ MethodFlavor::Constructor | MethodFlavor::Factory => Some(parse_quote! {+ #[cfg_attr(feature = "bindings-uniffi", uniffi::constructor)]+ }),+ }+}++pub fn error_attribute() -> proc_macro2::TokenStream {+ quote! {+ #[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Error))]+ }+}++#[allow(dead_code)]+pub fn error_implementations(_type_name: &Ident) -> proc_macro2::TokenStream {+ quote! {}+}++pub fn factory_with_callback(+ self_type: &syn::Type,+ method: &syn::ImplItemFn,+) -> proc_macro2::TokenStream {+ let method_ident = &method.sig.ident;+ let body = &method.block;++ let self_ident = match self_type_ident(self_type) {+ Some(ident) => ident,+ None => {+ return syn::Error::new_spanned(+ self_type,+ "bindings::export(FactoryWithCallback) requires a named self type",+ )+ .to_compile_error();+ },+ };+ let handler_ident = format_ident!("{}Handler", self_ident);++ quote! {+ #[cfg(feature = "bindings-uniffi")]+ #[uniffi::export(callback_interface)]+ pub trait #handler_ident: Send + Sync {+ fn on_event(&self);+ }++ #[cfg(feature = "bindings-uniffi")]+ #[uniffi::export]+ impl #self_type {+ #[uniffi::constructor]+ pub fn #method_ident(handler: Box<dyn #handler_ident>) -> std::sync::Arc<Self> {+ let handler: std::sync::Arc<dyn #handler_ident> = std::sync::Arc::from(handler);+ let callback: Box<dyn Fn() + Send + Sync> = Box::new(move || handler.on_event());+ std::sync::Arc::new(#body)+ }+ }+ }+}++fn self_type_ident(self_type: &syn::Type) -> Option<Ident> {+ match self_type {+ syn::Type::Path(path) => path.path.segments.last().map(|segment| segment.ident.clone()),+ _ => None,+ }+}diff --git a/crates/bindings/src/wasm.rs b/crates/bindings/src/wasm.rsnew file mode 100644index 000000000..44d31b0c2--- /dev/null+++ b/crates/bindings/src/wasm.rs@@ -0,0 +1,28 @@+use quote::quote;+use syn::Ident;++use crate::BindingKind;++pub fn attributes(kind: &BindingKind) -> proc_macro2::TokenStream {+ match kind {+ BindingKind::Enum | BindingKind::Struct => quote! {+ #[cfg_attr(feature = "bindings-wasm", derive(tsify::Tsify))]+ #[cfg_attr(feature = "bindings-wasm", tsify(into_wasm_abi, from_wasm_abi))]+ },+ BindingKind::Class | BindingKind::ClassCloneable | BindingKind::Implementation => quote! {+ #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen)]+ },+ _ => quote! {},+ }+}++pub fn error_implementations(type_name: &Ident) -> proc_macro2::TokenStream {+ quote! {+ #[cfg(feature = "bindings-wasm")]+ impl From<#type_name> for wasm_bindgen::JsValue {+ fn from(error: #type_name) -> Self {+ wasm_bindgen::JsValue::from_str(&error.to_string())+ }+ }+ }+}diff --git a/crates/cli-release/Cargo.toml b/crates/cli-release/Cargo.tomlnew file mode 100644index 000000000..177c0c5b7--- /dev/null+++ b/crates/cli-release/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "cli-release"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+license.workspace = true+authors.workspace = true+repository.workspace = true++[[bin]]+name = "cli-release"+path = "src/main.rs"++[dependencies]+clap.workspace = true+thiserror.workspace = true+ignore.workspace = true+serde_json.workspace = true+regex.workspace = true+heck.workspace = truediff --git a/crates/cli-release/scripts/sync_into_repo.sh b/crates/cli-release/scripts/sync_into_repo.shnew file mode 100755index 000000000..a043430ed--- /dev/null+++ b/crates/cli-release/scripts/sync_into_repo.sh@@ -0,0 +1,59 @@+#!/usr/bin/env bash+# sync-into-repo.sh+# Usage:+# sync-into-repo.sh /path/to/repo RELATIVE/PATH/INSIDE/REPO /path/to/external/folder++set -euo pipefail++if [[ $# -ne 3 ]]; then+ echo "Usage: $0 <repository_path> <relative_target_path_inside_repo_or_.> <external_source_folder>" >&2+ exit 1+fi++repository_path="$1"+relative_target_path="$2"+external_source_folder="$3"++# Validate repository path+if [[ ! -d "$repository_path" ]]; then+ echo "Error: repository path not found: $repository_path" >&2+ exit 1+fi+repository_absolute_path="$(cd "$repository_path" && pwd)"++# Validate source folder+if [[ ! -d "$external_source_folder" ]]; then+ echo "Error: external source folder not found: $external_source_folder" >&2+ exit 1+fi+external_source_absolute_path="$(cd "$external_source_folder" && pwd)"++# Verify it's a Git repository+if [[ ! -d "$repository_absolute_path/.git" ]]; then+ echo "Error: $repository_absolute_path is not a Git repository (missing .git directory)." >&2+ exit 1+fi++# Ensure the target path exists inside the repository+mkdir -p "$repository_absolute_path/$relative_target_path"+target_absolute_path="$(cd "$repository_absolute_path/$relative_target_path" && pwd)"++# Confirm that the target is inside the repository+case "$target_absolute_path" in+ "$repository_absolute_path" | "$repository_absolute_path"/*) ;; # OK+ *)+ echo "Error: target path escapes the repository: $target_absolute_path" >&2+ exit 1+ ;;+esac++# Rsync all contents (including hidden files), deleting removed ones,+# but never touching any .git directory anywhere.+rsync -a --delete \+ --exclude '.git' --exclude '.git/*' --exclude '**/.git' --exclude '**/.git/*' \+ "$external_source_absolute_path"/ "$target_absolute_path"/++# Stage all resulting changes (entire repo) for commit+git -C "$repository_absolute_path" add -A++echo "✅ Synced $external_source_absolute_path → $target_absolute_path and staged all changes in $repository_absolute_path."\ No newline at end of filediff --git a/crates/cli-release/scripts/ts_build.sh b/crates/cli-release/scripts/ts_build.shnew file mode 100755index 000000000..99a579c30--- /dev/null+++ b/crates/cli-release/scripts/ts_build.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+set -euo pipefail++TS_PATH="$1"++cd $TS_PATH+pnpm i --no-frozen-lockfile+pnpm run fix+pnpm run build\ No newline at end of filediff --git a/crates/cli-release/scripts/ts_napi_build.sh b/crates/cli-release/scripts/ts_napi_build.shnew file mode 100755index 000000000..4e1f2e3a9--- /dev/null+++ b/crates/cli-release/scripts/ts_napi_build.sh@@ -0,0 +1,10 @@+#!/usr/bin/env bash+set -euo pipefail++TS_NAPI_PATH="$1"+MANIFEST_PATH="$2"+OUTPUT_PATH="$3"++cd $TS_NAPI_PATH+pnpm i --no-frozen-lockfile+pnpm exec napi build --release --features bindings-napi --manifest-path $MANIFEST_PATH --output-dir $OUTPUT_PATH\ No newline at end of filediff --git a/crates/cli-release/scripts/zip_xcframework.sh b/crates/cli-release/scripts/zip_xcframework.shnew file mode 100644index 000000000..eec71dd9f--- /dev/null+++ b/crates/cli-release/scripts/zip_xcframework.sh@@ -0,0 +1,17 @@+#!/usr/bin/env bash+set -euo pipefail++FRAMEWORK_PATH="$1"+DESTINATION_PATH="$2"+VERSION="$3"++ZIP_NAME="${VERSION}.zip"++cd $DESTINATION_PATH+mkdir $VERSION+rsync -a "$FRAMEWORK_PATH" "$VERSION/"+zip -r "$ZIP_NAME" "$VERSION"+rm -rf "$VERSION"++CHECKSUM=$(swift package compute-checksum "$ZIP_NAME")+echo $CHECKSUM\ No newline at end of filediff --git a/crates/cli-release/src/handlers/mod.rs b/crates/cli-release/src/handlers/mod.rsnew file mode 100644index 000000000..9829ab6dc--- /dev/null+++ b/crates/cli-release/src/handlers/mod.rs@@ -0,0 +1,19 @@+mod prepare_bindings_swift;+mod prepare_bindings_ts;+mod prepare_docs;+mod prepare_platform;+mod prepare_workspace_swift;+mod prepare_workspace_swift_spm;+mod prepare_workspace_ts;+mod prepare_workspace_ts_napi;+mod sync_into_repo;++pub use prepare_bindings_swift::prepare_bindings_swift;+pub use prepare_bindings_ts::prepare_bindings_ts;+pub use prepare_docs::prepare_docs;+pub use prepare_platform::prepare_platform;+pub use prepare_workspace_swift::prepare_workspace_swift;+pub use prepare_workspace_swift_spm::prepare_workspace_swift_spm;+pub use prepare_workspace_ts::prepare_workspace_ts;+pub use prepare_workspace_ts_napi::prepare_workspace_ts_napi;+pub use sync_into_repo::{SyncSource, sync_into_repo};diff --git a/crates/cli-release/src/handlers/prepare_bindings_swift.rs b/crates/cli-release/src/handlers/prepare_bindings_swift.rsnew file mode 100644index 000000000..2fc24e878--- /dev/null+++ b/crates/cli-release/src/handlers/prepare_bindings_swift.rs@@ -0,0 +1,26 @@+use std::process::{Command, Stdio};++use crate::types::{Environment, Error};++pub fn prepare_bindings_swift(environment: &Environment) -> Result<(), Error> {+ let scripts_build_path = environment.bindings().swift_build_script_path();+ if !scripts_build_path.exists() {+ return Err(Error::PathNotFound {+ path: scripts_build_path,+ });+ }++ let output = Command::new("bash")+ .arg(scripts_build_path.clone())+ .stdout(Stdio::inherit())+ .stderr(Stdio::inherit())+ .output()+ .map_err(|_| Error::UnableToPrepareBindingsSwift)?;++ let status = output.status;+ if !status.success() {+ return Err(Error::UnableToPrepareBindingsSwift);+ }++ Ok(())+}diff --git a/crates/cli-release/src/handlers/prepare_bindings_ts.rs b/crates/cli-release/src/handlers/prepare_bindings_ts.rsnew file mode 100644index 000000000..4fdc4accb--- /dev/null+++ b/crates/cli-release/src/handlers/prepare_bindings_ts.rs@@ -0,0 +1,49 @@+use std::process::{Command, Stdio};++use crate::{+ types::{Environment, Error},+ utilities::clone_dir_with_ignore_respect,+};++pub fn prepare_bindings_ts(environment: &Environment) -> Result<(), Error> {+ let scripts_build_path = environment.scripts().ts_build();+ if !scripts_build_path.exists() {+ return Err(Error::PathNotFound {+ path: scripts_build_path,+ });+ }++ let workspace_ts_napi_path = environment.workspace().ts_napi_path();+ if !workspace_ts_napi_path.exists() {+ return Err(Error::PathNotFound {+ path: workspace_ts_napi_path,+ });+ }++ let bindings_ts_path = environment.bindings().ts_path();+ let bindings_ts_src_path = bindings_ts_path.join("src");+ if !bindings_ts_src_path.exists() {+ return Err(Error::PathNotFound {+ path: bindings_ts_src_path,+ });+ }++ let bindings_ts_src_napi_path = bindings_ts_src_path.join("napi");+ clone_dir_with_ignore_respect(&workspace_ts_napi_path, &bindings_ts_src_napi_path)+ .map_err(|_| Error::UnableToPrepareBindingsTS)?;++ let output = Command::new("bash")+ .arg(scripts_build_path.clone())+ .arg(bindings_ts_path.clone())+ .stdout(Stdio::inherit())+ .stderr(Stdio::inherit())+ .output()+ .map_err(|_| Error::UnableToPrepareBindingsTS)?;++ let status = output.status;+ if !status.success() {+ return Err(Error::UnableToPrepareBindingsTS);+ }++ Ok(())+}diff --git a/crates/cli-release/src/handlers/prepare_docs.rs b/crates/cli-release/src/handlers/prepare_docs.rsnew file mode 100644index 000000000..10518c4e3--- /dev/null+++ b/crates/cli-release/src/handlers/prepare_docs.rs@@ -0,0 +1,68 @@+use std::{fs, path::PathBuf};++use crate::types::{Environment, Error, Example, Language, Snippet};++pub fn prepare_docs(+ environment: &Environment,+ version: String,+ language: Language,+ snippets: Vec<Snippet>,+ examples: Vec<Example>,+) -> Result<(), Error> {+ let snippets = [snippets, vec![dependency_snippet(language.clone(), version.clone())]].concat();++ let docs_snippets_path = environment.workspace().docs_snippets_path().join(language.clone().to_string());+ if docs_snippets_path.exists() {+ fs::remove_dir_all(docs_snippets_path.clone()).map_err(|_| Error::UnableToPrepareDocs)?;+ }+ fs::create_dir_all(docs_snippets_path.clone()).map_err(|_| Error::UnableToPrepareDocs)?;++ for snippet in snippets {+ let snippet_path = docs_snippets_path.join(format!("{}.mdx", snippet.name));+ fs::write(snippet_path, md_content(language.clone(), snippet.content))+ .map_err(|_| Error::UnableToPrepareDocs)?;+ }++ let docs_examples_path = environment.workspace().docs_examples_path().join(language.clone().to_string());+ if docs_examples_path.exists() {+ fs::remove_dir_all(docs_examples_path.clone()).map_err(|_| Error::UnableToPrepareDocs)?;+ }+ fs::create_dir_all(docs_examples_path.clone()).map_err(|_| Error::UnableToPrepareDocs)?;++ for example in examples {+ if !example.exportable {+ continue;+ }+ let example_path = docs_examples_path.join(format!("{}.mdx", example.name));+ fs::write(example_path, md_content(language.clone(), example.content))+ .map_err(|_| Error::UnableToPrepareDocs)?;+ }++ Ok(())+}++fn md_content(+ language: Language,+ content: String,+) -> String {+ format!("```{}\n{}\n```", language.to_string(), content)+}++fn dependency_snippet(+ language: Language,+ version: String,+) -> Snippet {+ let content = match language {+ Language::Swift => format!(+ "dependencies: [\n .package(url: \"https://github.com/trymirai/uzu-swift.git\", from: \"{}\")\n]",+ version+ )+ .to_string(),+ Language::TS => format!("\"dependencies\": {{\n \"@trymirai/uzu\": \"{}\"\n}}", version).to_string(),+ };+ Snippet {+ name: "dependency".to_string(),+ content,+ source_path: PathBuf::new(),+ }+}diff --git a/crates/cli-release/src/handlers/prepare_platform.rs b/crates/cli-release/src/handlers/prepare_platform.rsnew file mode 100644index 000000000..362792c1f--- /dev/null+++ b/crates/cli-release/src/handlers/prepare_platform.rs@@ -0,0 +1,25 @@+use std::fs;++use crate::types::{Environment, Error, Example, Language};++pub fn prepare_platform(+ environment: &Environment,+ language: Language,+ examples: Vec<Example>,+) -> Result<(), Error> {+ let platform_examples_path = environment.workspace().platform_path().join(language.clone().to_string());+ if platform_examples_path.exists() {+ fs::remove_dir_all(platform_examples_path.clone()).map_err(|_| Error::UnableToPreparePlatform)?;+ }+ fs::create_dir_all(platform_examples_path.clone()).map_err(|_| Error::UnableToPreparePlatform)?;++ for example in examples {+ if !example.exportable {+ continue;+ }+ let example_path = platform_examples_path.join(format!("{}.txt", example.name));+ fs::write(example_path, example.content).map_err(|_| Error::UnableToPreparePlatform)?;+ }++ Ok(())+}diff --git a/crates/cli-release/src/handlers/prepare_workspace_swift.rs b/crates/cli-release/src/handlers/prepare_workspace_swift.rsnew file mode 100644index 000000000..1869cd376--- /dev/null+++ b/crates/cli-release/src/handlers/prepare_workspace_swift.rs@@ -0,0 +1,47 @@+use std::fs;++use crate::{+ handlers::{prepare_docs, prepare_platform},+ types::{Environment, Error, Language},+ utilities::{+ clone_dir_with_ignore_respect, extract_examples, extract_snippets, update_package_swift, update_readme,+ },+};++pub fn prepare_workspace_swift(+ environment: &Environment,+ version: String,+ checksum: String,+) -> Result<(), Error> {+ let workspace = environment.workspace();+ let workspace_swift_path = workspace.swift_path();+ if workspace_swift_path.exists() {+ fs::remove_dir_all(workspace_swift_path.clone()).map_err(|_| Error::UnableToPrepareWorkspaceSwift)?;+ }+ fs::create_dir_all(workspace_swift_path.clone()).map_err(|_| Error::UnableToPrepareWorkspaceSwift)?;++ let bindings_swift_path = environment.bindings().swift_path();+ if !bindings_swift_path.exists() {+ return Err(Error::PathNotFound {+ path: bindings_swift_path,+ });+ }++ clone_dir_with_ignore_respect(&bindings_swift_path, &workspace_swift_path)?;++ let package_swift_path = workspace_swift_path.join("Package.swift");+ update_package_swift(package_swift_path.clone(), version.clone(), checksum.clone())?;++ let examples_path = workspace_swift_path.join("Sources").join("Example");+ let snippets = extract_snippets(examples_path.clone())?;+ let examples = extract_examples(examples_path.clone(), workspace_swift_path.clone())?;++ let readme_path = workspace_swift_path.join("README.md");+ update_readme(readme_path.clone(), snippets.clone(), examples.clone(), version.clone())?;++ prepare_docs(environment, version.clone(), Language::Swift, snippets.clone(), examples.clone())?;++ prepare_platform(environment, Language::Swift, examples.clone())?;++ Ok(())+}diff --git a/crates/cli-release/src/handlers/prepare_workspace_swift_spm.rs b/crates/cli-release/src/handlers/prepare_workspace_swift_spm.rsnew file mode 100644index 000000000..03514178c--- /dev/null+++ b/crates/cli-release/src/handlers/prepare_workspace_swift_spm.rs@@ -0,0 +1,52 @@+use std::{+ fs,+ process::{Command, Stdio},+};++use crate::types::{Environment, Error};++pub fn prepare_workspace_swift_spm(+ environment: &Environment,+ version: String,+) -> Result<String, Error> {+ let scripts_build_path = environment.scripts().zip_xcframework();+ if !scripts_build_path.exists() {+ return Err(Error::PathNotFound {+ path: scripts_build_path,+ });+ }++ let framework_path = environment.bindings().swift_framework_path();+ if !framework_path.exists() {+ return Err(Error::PathNotFound {+ path: framework_path,+ });+ }++ let workspace = environment.workspace();+ let workspace_swift_spm_path = workspace.swift_spm_path();+ if workspace_swift_spm_path.exists() {+ fs::remove_dir_all(workspace_swift_spm_path.clone()).map_err(|_| Error::UnableToPrepareWorkspaceSwiftSPM)?;+ }+ fs::create_dir_all(workspace_swift_spm_path.clone()).map_err(|_| Error::UnableToPrepareWorkspaceSwiftSPM)?;++ let output = Command::new("bash")+ .arg(scripts_build_path.clone())+ .arg(framework_path.clone())+ .arg(workspace_swift_spm_path.clone())+ .arg(version.clone())+ .stderr(Stdio::inherit())+ .output()+ .map_err(|_| Error::UnableToPrepareWorkspaceSwiftSPM)?;++ let status = output.status;+ if !status.success() {+ return Err(Error::UnableToPrepareWorkspaceSwiftSPM);+ }++ let result = String::from_utf8_lossy(&output.stdout);+ let checksum =+ result.lines().filter(|line| !line.trim().is_empty()).last().ok_or(Error::UnableToPrepareWorkspaceSwiftSPM)?;++ Ok(checksum.to_string())+}diff --git a/crates/cli-release/src/handlers/prepare_workspace_ts.rs b/crates/cli-release/src/handlers/prepare_workspace_ts.rsnew file mode 100644index 000000000..be4dad989--- /dev/null+++ b/crates/cli-release/src/handlers/prepare_workspace_ts.rs@@ -0,0 +1,86 @@+use std::{+ fs,+ process::{Command, Stdio},+};++use crate::{+ handlers::{prepare_docs, prepare_platform},+ types::{Environment, Error, Language},+ utilities::{+ clone_dir_with_ignore_respect, extract_examples, extract_snippets, remove_ignored_entities_from_directory,+ update_json_field, update_readme,+ },+};++pub fn prepare_workspace_ts(+ environment: &Environment,+ version: String,+) -> Result<(), Error> {+ let scripts_build_path = environment.scripts().ts_build();+ if !scripts_build_path.exists() {+ return Err(Error::PathNotFound {+ path: scripts_build_path,+ });+ }++ let workspace = environment.workspace();+ let workspace_ts_path = workspace.ts_path();+ if workspace_ts_path.exists() {+ fs::remove_dir_all(workspace_ts_path.clone()).map_err(|_| Error::UnableToPrepareWorkspaceTS)?;+ }+ fs::create_dir_all(workspace_ts_path.clone()).map_err(|_| Error::UnableToPrepareWorkspaceTS)?;++ let bindings_ts_path = environment.bindings().ts_path();+ if !bindings_ts_path.exists() {+ return Err(Error::PathNotFound {+ path: bindings_ts_path,+ });+ }++ clone_dir_with_ignore_respect(&bindings_ts_path, &workspace_ts_path)?;++ update_json_field(workspace_ts_path.join("package.json"), "version".to_string(), version.clone())?;++ update_json_field(workspace_ts_path.join("jsr.json"), "version".to_string(), version.clone())?;++ let examples_path = workspace_ts_path.join("examples");+ let snippets = extract_snippets(examples_path.clone())?;+ let examples = extract_examples(examples_path.clone(), workspace_ts_path.clone())?;++ let readme_path = workspace_ts_path.join("README.md");+ update_readme(readme_path.clone(), snippets.clone(), examples.clone(), version.clone())?;++ let output = Command::new("bash")+ .arg(scripts_build_path.clone())+ .arg(workspace_ts_path.clone())+ .stdout(Stdio::inherit())+ .stderr(Stdio::inherit())+ .output()+ .map_err(|_| Error::UnableToPrepareWorkspaceTS)?;+ let status = output.status;+ if !status.success() {+ return Err(Error::UnableToPrepareWorkspaceTS);+ }++ let workspace_ts_npm_path = workspace.ts_npm_path();+ if workspace_ts_npm_path.exists() {+ fs::remove_dir_all(workspace_ts_npm_path.clone()).map_err(|_| Error::UnableToPrepareWorkspaceTSNPM)?;+ }+ fs::create_dir_all(workspace_ts_npm_path.clone()).map_err(|_| Error::UnableToPrepareWorkspaceTSNPM)?;++ let dist_path = workspace_ts_path.join("dist");+ if !dist_path.exists() {+ return Err(Error::PathNotFound {+ path: dist_path,+ });+ }+ clone_dir_with_ignore_respect(&dist_path, &workspace_ts_npm_path)?;++ remove_ignored_entities_from_directory(workspace_ts_path.clone())?;++ prepare_docs(environment, version.clone(), Language::TS, snippets.clone(), examples.clone())?;++ prepare_platform(environment, Language::TS, examples.clone())?;++ Ok(())+}diff --git a/crates/cli-release/src/handlers/prepare_workspace_ts_napi.rs b/crates/cli-release/src/handlers/prepare_workspace_ts_napi.rsnew file mode 100644index 000000000..af7873b6a--- /dev/null+++ b/crates/cli-release/src/handlers/prepare_workspace_ts_napi.rs@@ -0,0 +1,65 @@+use std::{+ fs,+ process::{Command, Stdio},+};++use crate::types::{Environment, Error};++pub fn prepare_workspace_ts_napi(environment: &Environment) -> Result<(), Error> {+ let scripts_build_path = environment.scripts().ts_napi_build();+ if !scripts_build_path.exists() {+ return Err(Error::PathNotFound {+ path: scripts_build_path,+ });+ }++ let bindings_ts_napi_path = environment.bindings().ts_napi_path();+ if !bindings_ts_napi_path.exists() {+ return Err(Error::PathNotFound {+ path: bindings_ts_napi_path,+ });+ }++ let crates_uzu_manifest_path = environment.package_uzu().manifest_path();+ if !crates_uzu_manifest_path.exists() {+ return Err(Error::PathNotFound {+ path: crates_uzu_manifest_path,+ });+ }++ let workspace = environment.workspace();+ let workspace_ts_napi_path = workspace.ts_napi_path();+ if workspace_ts_napi_path.exists() {+ fs::remove_dir_all(workspace_ts_napi_path.clone()).map_err(|_| Error::UnableToPrepareWorkspaceTSNAPI)?;+ }+ fs::create_dir_all(workspace_ts_napi_path.clone()).map_err(|_| Error::UnableToPrepareWorkspaceTSNAPI)?;++ let output = Command::new("bash")+ .arg(scripts_build_path.clone())+ .arg(bindings_ts_napi_path.clone())+ .arg(crates_uzu_manifest_path.clone())+ .arg(workspace_ts_napi_path.clone())+ .stdout(Stdio::inherit())+ .stderr(Stdio::inherit())+ .output()+ .map_err(|_| Error::UnableToPrepareWorkspaceTSNAPI)?;++ let status = output.status;+ if !status.success() {+ return Err(Error::UnableToPrepareWorkspaceTSNAPI);+ }++ let expected_paths = vec![workspace.ts_napi_index_d_ts(), workspace.ts_napi_uzu_node()];+ for path in expected_paths {+ if !path.exists() {+ return Err(Error::PathNotFound {+ path: path,+ });+ }+ }++ fs::rename(workspace.ts_napi_index_d_ts(), workspace.ts_napi_uzu_d_ts())+ .map_err(|_| Error::UnableToPrepareWorkspaceTSNAPI)?;++ Ok(())+}diff --git a/crates/cli-release/src/handlers/sync_into_repo.rs b/crates/cli-release/src/handlers/sync_into_repo.rsnew file mode 100644index 000000000..eb2a6c9b8--- /dev/null+++ b/crates/cli-release/src/handlers/sync_into_repo.rs@@ -0,0 +1,78 @@+use std::{+ path::PathBuf,+ process::{Command, Stdio},+};++use clap::ValueEnum;++use crate::types::{Environment, Error};++#[derive(Debug, Clone, PartialEq, Eq, ValueEnum)]+pub enum SyncSource {+ Swift,+ TS,+ Docs,+}++impl SyncSource {+ pub fn relative_path(&self) -> String {+ match self {+ SyncSource::Swift => "./".to_string(),+ SyncSource::TS => "./".to_string(),+ SyncSource::Docs => "./snippets/generated".to_string(),+ }+ }++ pub fn source_path(+ &self,+ environment: &Environment,+ ) -> PathBuf {+ match self {+ SyncSource::Swift => environment.workspace().swift_path(),+ SyncSource::TS => environment.workspace().ts_path(),+ SyncSource::Docs => environment.workspace().docs_path(),+ }+ }+}++pub fn sync_into_repo(+ environment: &Environment,+ source: SyncSource,+ repo_path: PathBuf,+) -> Result<(), Error> {+ let scripts_path = environment.scripts().sync_into_repo();+ if !scripts_path.exists() {+ return Err(Error::PathNotFound {+ path: scripts_path,+ });+ }++ let source_path = source.source_path(environment);+ if !source_path.exists() {+ return Err(Error::PathNotFound {+ path: source_path,+ });+ }++ if !repo_path.exists() {+ return Err(Error::PathNotFound {+ path: repo_path,+ });+ }++ let output = Command::new("bash")+ .arg(scripts_path.clone())+ .arg(repo_path.clone())+ .arg(source.relative_path())+ .arg(source_path.clone())+ .stdout(Stdio::inherit())+ .stderr(Stdio::inherit())+ .output()+ .map_err(|_| Error::UnableToSyncIntoRepo)?;+ let status = output.status;+ if !status.success() {+ return Err(Error::UnableToSyncIntoRepo);+ }++ Ok(())+}diff --git a/crates/cli-release/src/lib.rs b/crates/cli-release/src/lib.rsnew file mode 100644index 000000000..c724138b3--- /dev/null+++ b/crates/cli-release/src/lib.rs@@ -0,0 +1,3 @@+pub mod handlers;+pub mod types;+pub mod utilities;diff --git a/crates/cli-release/src/main.rs b/crates/cli-release/src/main.rsnew file mode 100644index 000000000..47942bc47--- /dev/null+++ b/crates/cli-release/src/main.rs@@ -0,0 +1,80 @@+use std::path::PathBuf;++use clap::{CommandFactory, Parser, Subcommand};+use cli_release::{+ handlers::{+ SyncSource, prepare_bindings_swift, prepare_bindings_ts, prepare_workspace_swift, prepare_workspace_swift_spm,+ prepare_workspace_ts, prepare_workspace_ts_napi, sync_into_repo,+ },+ types::{Environment, Error},+};++#[derive(Parser)]+struct Cli {+ #[command(subcommand)]+ command: Option<Commands>,+}++#[derive(Subcommand)]+enum Commands {+ /// Prepare bindings+ PrepareBindings,+ /// Prepare workspace+ PrepareWorkspace {+ /// Package version+ version: String,+ },+ /// Sync into repo+ SyncIntoRepo {+ /// Source+ source: SyncSource,+ /// Repository path+ repo_path: PathBuf,+ },+}++fn prepare_bindings(environment: &Environment) -> Result<(), Error> {+ prepare_workspace_ts_napi(environment)?;+ prepare_bindings_ts(environment)?;+ prepare_bindings_swift(environment)?;+ Ok(())+}++fn prepare_workspace(+ environment: &Environment,+ version: String,+) -> Result<(), Error> {+ prepare_bindings(&environment)?;+ prepare_workspace_ts(environment, version.clone())?;+ let swift_spm_checksum = prepare_workspace_swift_spm(environment, version.clone())?;+ prepare_workspace_swift(environment, version.clone(), swift_spm_checksum)?;+ Ok(())+}++fn main() -> Result<(), Error> {+ let cli = Cli::parse();+ let environment = Environment::new()?;++ match cli.command {+ Some(Commands::PrepareBindings) => {+ prepare_bindings(&environment)?;+ },+ Some(Commands::PrepareWorkspace {+ version,+ }) => {+ prepare_workspace(&environment, version)?;+ },+ Some(Commands::SyncIntoRepo {+ source,+ repo_path,+ }) => {+ sync_into_repo(&environment, source, repo_path)?;+ },+ None => {+ let mut cmd = Cli::command();+ cmd.print_help().unwrap();+ },+ }++ Ok(())+}diff --git a/crates/cli-release/src/types/bindings.rs b/crates/cli-release/src/types/bindings.rsnew file mode 100644index 000000000..5dcb72c53--- /dev/null+++ b/crates/cli-release/src/types/bindings.rs@@ -0,0 +1,38 @@+use std::path::PathBuf;++#[derive(Debug)]+pub struct Bindings {+ pub root_path: PathBuf,+}++impl Bindings {+ pub fn new(root_path: PathBuf) -> Self {+ Self {+ root_path,+ }+ }+}++impl Bindings {+ pub fn ts_napi_path(&self) -> PathBuf {+ self.root_path.join("ts-napi")+ }++ pub fn ts_path(&self) -> PathBuf {+ self.root_path.join("ts")+ }+}++impl Bindings {+ pub fn swift_path(&self) -> PathBuf {+ self.root_path.join("swift")+ }++ pub fn swift_build_script_path(&self) -> PathBuf {+ self.swift_path().join("build_release_xcframework.sh")+ }++ pub fn swift_framework_path(&self) -> PathBuf {+ self.swift_path().join("uzu.xcframework")+ }+}diff --git a/crates/cli-release/src/types/environment.rs b/crates/cli-release/src/types/environment.rsnew file mode 100644index 000000000..14e55321e--- /dev/null+++ b/crates/cli-release/src/types/environment.rs@@ -0,0 +1,63 @@+use std::path::{Path, PathBuf};++use crate::types::{Bindings, Error, Package, Scripts, Workspace};++#[derive(Debug)]+pub struct Environment {+ pub root_path: PathBuf,+}++impl Environment {+ pub fn new() -> Result<Self, Error> {+ let crate_manifest_path = Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf();++ let crates_path = crate_manifest_path.parent().ok_or(Error::RootPathNotFound)?.to_path_buf();++ let root_path = crates_path.parent().ok_or(Error::RootPathNotFound)?.to_path_buf();++ let root_manifest_path = root_path.join("Cargo.toml");+ if !root_manifest_path.exists() {+ return Err(Error::RootPathNotFound);+ }++ Ok(Self {+ root_path: root_path,+ })+ }+}++impl Environment {+ pub fn crates_path(&self) -> PathBuf {+ self.root_path.join("crates")+ }++ pub fn bindings_path(&self) -> PathBuf {+ self.root_path.join("bindings")+ }++ pub fn workspace_path(&self) -> PathBuf {+ self.root_path.join("workspace").join("release")+ }+}++impl Environment {+ pub fn package_uzu(&self) -> Package {+ Package::new(self.crates_path().join("uzu"))+ }++ pub fn package_release_cli(&self) -> Package {+ Package::new(self.crates_path().join("cli-release"))+ }++ pub fn scripts(&self) -> Scripts {+ Scripts::new(self.package_release_cli().root_path.join("scripts"))+ }++ pub fn bindings(&self) -> Bindings {+ Bindings::new(self.bindings_path())+ }++ pub fn workspace(&self) -> Workspace {+ Workspace::new(self.workspace_path())+ }+}diff --git a/crates/cli-release/src/types/error.rs b/crates/cli-release/src/types/error.rsnew file mode 100644index 000000000..27c66a4e2--- /dev/null+++ b/crates/cli-release/src/types/error.rs@@ -0,0 +1,47 @@+use std::path::PathBuf;++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error("Root path not found")]+ RootPathNotFound,+ #[error("Path not found: {path}")]+ PathNotFound {+ path: PathBuf,+ },+ #[error("Unable to clone directory")]+ UnableToCloneDirectory,+ #[error("Unable to remove ignored entities")]+ UnableToRemoveIgnoredEntities,+ #[error("Unable to update JSON")]+ UnableToUpdateJSON,+ #[error("Unable to extract snippets")]+ UnableToExtractSnippets,+ #[error("Unable to extract examples")]+ UnableToExtractExamples,+ #[error("Unable to update README")]+ UnableToUpdateREADME,+ #[error("Unable to update Package.swift")]+ UnableToUpdatePackageSwift,+ #[error("Unable to prepare workspace")]+ UnableToPrepareWorkspace,+ #[error("Unable to prepare workspace/ts-napi")]+ UnableToPrepareWorkspaceTSNAPI,+ #[error("Unable to prepare bindings/swift")]+ UnableToPrepareBindingsSwift,+ #[error("Unable to prepare bindings/ts")]+ UnableToPrepareBindingsTS,+ #[error("Unable to prepare workspace/ts")]+ UnableToPrepareWorkspaceTS,+ #[error("Unable to prepare workspace/ts-npm")]+ UnableToPrepareWorkspaceTSNPM,+ #[error("Unable to prepare workspace/swift")]+ UnableToPrepareWorkspaceSwift,+ #[error("Unable to prepare workspace/swift-spm")]+ UnableToPrepareWorkspaceSwiftSPM,+ #[error("Unable to prepare docs")]+ UnableToPrepareDocs,+ #[error("Unable to prepare platform")]+ UnableToPreparePlatform,+ #[error("Unable to sync into repo")]+ UnableToSyncIntoRepo,+}diff --git a/crates/cli-release/src/types/example.rs b/crates/cli-release/src/types/example.rsnew file mode 100644index 000000000..b3be2668e--- /dev/null+++ b/crates/cli-release/src/types/example.rs@@ -0,0 +1,28 @@+use std::path::PathBuf;++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Example {+ pub name: String,+ pub relative_path: PathBuf,+ pub full_path: PathBuf,+ pub content: String,+ pub exportable: bool,+}++impl Example {+ pub fn new(+ name: String,+ relative_path: PathBuf,+ full_path: PathBuf,+ content: String,+ exportable: bool,+ ) -> Self {+ Self {+ name,+ relative_path,+ full_path,+ content: content.trim().to_string(),+ exportable,+ }+ }+}diff --git a/crates/cli-release/src/types/language.rs b/crates/cli-release/src/types/language.rsnew file mode 100644index 000000000..2db97f8ed--- /dev/null+++ b/crates/cli-release/src/types/language.rs@@ -0,0 +1,14 @@+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Language {+ Swift,+ TS,+}++impl Language {+ pub fn to_string(&self) -> String {+ match self {+ Language::Swift => "swift".to_string(),+ Language::TS => "ts".to_string(),+ }+ }+}diff --git a/crates/cli-release/src/types/mod.rs b/crates/cli-release/src/types/mod.rsnew file mode 100644index 000000000..4e31877f7--- /dev/null+++ b/crates/cli-release/src/types/mod.rs@@ -0,0 +1,19 @@+mod bindings;+mod environment;+mod error;+mod example;+mod language;+mod package;+mod scripts;+mod snippet;+mod workspace;++pub use bindings::Bindings;+pub use environment::Environment;+pub use error::Error;+pub use example::Example;+pub use language::Language;+pub use package::Package;+pub use scripts::Scripts;+pub use snippet::Snippet;+pub use workspace::Workspace;diff --git a/crates/cli-release/src/types/package.rs b/crates/cli-release/src/types/package.rsnew file mode 100644index 000000000..e74dc8ac1--- /dev/null+++ b/crates/cli-release/src/types/package.rs@@ -0,0 +1,20 @@+use std::path::PathBuf;++#[derive(Debug)]+pub struct Package {+ pub root_path: PathBuf,+}++impl Package {+ pub fn new(root_path: PathBuf) -> Self {+ Self {+ root_path,+ }+ }+}++impl Package {+ pub fn manifest_path(&self) -> PathBuf {+ self.root_path.join("Cargo.toml")+ }+}diff --git a/crates/cli-release/src/types/scripts.rs b/crates/cli-release/src/types/scripts.rsnew file mode 100644index 000000000..7bb010590--- /dev/null+++ b/crates/cli-release/src/types/scripts.rs@@ -0,0 +1,32 @@+use std::path::PathBuf;++#[derive(Debug)]+pub struct Scripts {+ pub root_path: PathBuf,+}++impl Scripts {+ pub fn new(root_path: PathBuf) -> Self {+ Self {+ root_path,+ }+ }+}++impl Scripts {+ pub fn ts_napi_build(&self) -> PathBuf {+ self.root_path.join("ts_napi_build.sh")+ }++ pub fn ts_build(&self) -> PathBuf {+ self.root_path.join("ts_build.sh")+ }++ pub fn sync_into_repo(&self) -> PathBuf {+ self.root_path.join("sync_into_repo.sh")+ }++ pub fn zip_xcframework(&self) -> PathBuf {+ self.root_path.join("zip_xcframework.sh")+ }+}diff --git a/crates/cli-release/src/types/snippet.rs b/crates/cli-release/src/types/snippet.rsnew file mode 100644index 000000000..239fc8e6d--- /dev/null+++ b/crates/cli-release/src/types/snippet.rs@@ -0,0 +1,22 @@+use std::path::PathBuf;++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Snippet {+ pub name: String,+ pub content: String,+ pub source_path: PathBuf,+}++impl Snippet {+ pub fn new(+ name: String,+ content: String,+ source_path: PathBuf,+ ) -> Self {+ Self {+ name,+ content: content.trim().to_string(),+ source_path,+ }+ }+}diff --git a/crates/cli-release/src/types/workspace.rs b/crates/cli-release/src/types/workspace.rsnew file mode 100644index 000000000..6d221d789--- /dev/null+++ b/crates/cli-release/src/types/workspace.rs@@ -0,0 +1,68 @@+use std::path::PathBuf;++#[derive(Debug)]+pub struct Workspace {+ pub root_path: PathBuf,+}++impl Workspace {+ pub fn new(root_path: PathBuf) -> Self {+ Self {+ root_path,+ }+ }+}++impl Workspace {+ pub fn ts_path(&self) -> PathBuf {+ self.root_path.join("ts")+ }++ pub fn ts_npm_path(&self) -> PathBuf {+ self.root_path.join("ts-npm")+ }++ pub fn swift_path(&self) -> PathBuf {+ self.root_path.join("swift")+ }++ pub fn swift_spm_path(&self) -> PathBuf {+ self.root_path.join("swift-spm")+ }++ pub fn platform_path(&self) -> PathBuf {+ self.root_path.join("platform")+ }+}++impl Workspace {+ pub fn docs_path(&self) -> PathBuf {+ self.root_path.join("docs")+ }++ pub fn docs_snippets_path(&self) -> PathBuf {+ self.docs_path().join("snippets")+ }++ pub fn docs_examples_path(&self) -> PathBuf {+ self.docs_path().join("examples")+ }+}++impl Workspace {+ pub fn ts_napi_path(&self) -> PathBuf {+ self.root_path.join("ts-napi")+ }++ pub fn ts_napi_index_d_ts(&self) -> PathBuf {+ self.ts_napi_path().join("index.d.ts")+ }++ pub fn ts_napi_uzu_d_ts(&self) -> PathBuf {+ self.ts_napi_path().join("uzu.d.ts")+ }++ pub fn ts_napi_uzu_node(&self) -> PathBuf {+ self.ts_napi_path().join("uzu.node")+ }+}diff --git a/crates/cli-release/src/utilities/examples.rs b/crates/cli-release/src/utilities/examples.rsnew file mode 100644index 000000000..3ea778ac5--- /dev/null+++ b/crates/cli-release/src/utilities/examples.rs@@ -0,0 +1,44 @@+use std::{fs, path::PathBuf};++use crate::{+ types::{Error, Example},+ utilities::{kebab_filename, relative_path},+};++const EXPORTED_EXAMPLE_NAMES: [&str; 12] = [+ "quick-start",+ "chat",+ "summarization",+ "classification",+ "cloud",+ "chat-static-context",+ "chat-dynamic-context",+ "ssm",+ "structured-output",+ "chat-with-speculator",+ "classifier",+ "text-to-speech",+];++pub fn extract_examples(+ examples_path: PathBuf,+ root_path: PathBuf,+) -> Result<Vec<Example>, Error> {+ let mut examples = Vec::new();+ for entry in fs::read_dir(examples_path).map_err(|_| Error::UnableToExtractExamples)? {+ let entry = entry.map_err(|_| Error::UnableToExtractExamples)?;+ let entry_path = entry.path();+ let content = fs::read_to_string(entry_path.clone()).map_err(|_| Error::UnableToExtractExamples)?;+ let relative_path =+ relative_path(entry_path.clone(), root_path.clone()).ok_or(Error::UnableToExtractExamples)?;+ let name = kebab_filename(&entry_path).ok_or(Error::UnableToExtractExamples)?;+ examples.push(Example::new(+ name.clone(),+ relative_path,+ entry_path.clone(),+ content,+ EXPORTED_EXAMPLE_NAMES.contains(&name.clone().as_str()),+ ));+ }+ Ok(examples)+}diff --git a/crates/cli-release/src/utilities/file_system.rs b/crates/cli-release/src/utilities/file_system.rsnew file mode 100644index 000000000..7c9201608--- /dev/null+++ b/crates/cli-release/src/utilities/file_system.rs@@ -0,0 +1,133 @@+use std::{+ collections::HashSet,+ fs,+ path::{Path, PathBuf},+};++use heck::ToKebabCase;+use ignore::WalkBuilder;++use crate::types::Error;++pub fn clone_dir_with_ignore_respect(+ src: &Path,+ dst: &Path,+) -> Result<(), Error> {+ fs::create_dir_all(dst).map_err(|_| Error::UnableToCloneDirectory)?;++ let walker = WalkBuilder::new(src).standard_filters(true).parents(false).hidden(false).build();++ for result in walker {+ let entry = result.map_err(|_| Error::UnableToCloneDirectory)?;+ let path = entry.path();++ if path == src {+ continue;+ }++ let relative = path.strip_prefix(src).map_err(|_| Error::UnableToCloneDirectory)?;+ let dst_path = dst.join(relative);++ if path.is_dir() {+ fs::create_dir_all(&dst_path).map_err(|_| Error::UnableToCloneDirectory)?;+ } else if path.is_file() {+ if let Some(parent) = dst_path.parent() {+ fs::create_dir_all(parent).map_err(|_| Error::UnableToCloneDirectory)?;+ }+ fs::copy(path, &dst_path).map_err(|_| Error::UnableToCloneDirectory)?;+ }+ }++ let ignore_path: PathBuf = dst.join(".ignore");+ if ignore_path.exists() {+ fs::remove_file(&ignore_path).map_err(|_| Error::UnableToCloneDirectory)?;+ }++ Ok(())+}++pub fn remove_ignored_entities_from_directory(directory_path: PathBuf) -> Result<(), Error> {+ // Build a walker that respects ignore rules – these are the entries we KEEP+ let respected_walker =+ WalkBuilder::new(&directory_path).standard_filters(true).hidden(false).follow_links(false).build();++ let mut kept_paths: HashSet<PathBuf> = HashSet::new();+ for result in respected_walker {+ let directory_entry = result.map_err(|_| Error::UnableToRemoveIgnoredEntities)?;+ let entry_path = directory_entry.path();++ // Keep the root directory, but don't store it in the set to avoid accidental deletion logic+ if entry_path == directory_path {+ continue;+ }+ kept_paths.insert(entry_path.to_path_buf());+ }++ // Build a walker that does NOT respect ignore rules – this sees EVERYTHING+ let all_walker =+ WalkBuilder::new(&directory_path).standard_filters(false).hidden(false).follow_links(false).build();++ // Partition items to remove into files and directories.+ // We remove files first, then directories deepest-first to avoid ENOTEMPTY.+ let mut files_to_remove: Vec<PathBuf> = Vec::new();+ let mut directories_to_remove: Vec<PathBuf> = Vec::new();++ for result in all_walker {+ let directory_entry = result.map_err(|_| Error::UnableToRemoveIgnoredEntities)?;+ let entry_path = directory_entry.path();++ if entry_path == directory_path {+ continue; // never remove the root+ }++ // If not in kept set, it’s ignored -> schedule for removal+ if !kept_paths.contains(entry_path) {+ if entry_path.is_file() {+ files_to_remove.push(entry_path.to_path_buf());+ } else if entry_path.is_dir() {+ directories_to_remove.push(entry_path.to_path_buf());+ }+ }+ }++ // Remove files first+ for file_path in files_to_remove {+ fs::remove_file(&file_path).map_err(|_| Error::UnableToRemoveIgnoredEntities)?;+ }++ // Then remove directories, deepest-first+ directories_to_remove.sort_by_key(|p| std::cmp::Reverse(p.components().count()));+ for directory_to_remove in directories_to_remove {+ fs::remove_dir_all(&directory_to_remove).map_err(|_| Error::UnableToRemoveIgnoredEntities)?;+ }++ Ok(())+}++pub fn relative_path(+ target: PathBuf,+ base: PathBuf,+) -> Option<PathBuf> {+ let target_iter = target.components();+ let base_iter = base.components();++ let target_components: Vec<_> = target_iter.collect();+ let base_components: Vec<_> = base_iter.collect();++ let common_len = target_components.iter().zip(&base_components).take_while(|(a, b)| a == b).count();++ let mut result = PathBuf::new();+ for _ in base_components.iter().skip(common_len) {+ result.push("..");+ }++ for comp in target_components.iter().skip(common_len) {+ result.push(comp.as_os_str());+ }++ Some(result)+}++pub fn kebab_filename(path: &PathBuf) -> Option<String> {+ path.file_stem().and_then(|stem| stem.to_str()).map(|stem| stem.to_kebab_case())+}diff --git a/crates/cli-release/src/utilities/json.rs b/crates/cli-release/src/utilities/json.rsnew file mode 100644index 000000000..2d7983b99--- /dev/null+++ b/crates/cli-release/src/utilities/json.rs@@ -0,0 +1,19 @@+use std::{fs, path::PathBuf};++use serde_json::Value;++use crate::types::Error;++pub fn update_json_field(+ path: PathBuf,+ key: String,+ value: String,+) -> Result<(), Error> {+ let json = fs::read_to_string(path.clone()).map_err(|_| Error::UnableToUpdateJSON)?;+ let mut json: Value = serde_json::from_str(&json).map_err(|_| Error::UnableToUpdateJSON)?;+ json[key] = Value::String(value);+ fs::write(path.clone(), serde_json::to_string(&json).map_err(|_| Error::UnableToUpdateJSON)?)+ .map_err(|_| Error::UnableToUpdateJSON)?;++ Ok(())+}diff --git a/crates/cli-release/src/utilities/mod.rs b/crates/cli-release/src/utilities/mod.rsnew file mode 100644index 000000000..790a380a0--- /dev/null+++ b/crates/cli-release/src/utilities/mod.rs@@ -0,0 +1,15 @@+mod examples;+mod file_system;+mod json;+mod package_swift;+mod readme;+mod snippets;++pub use examples::extract_examples;+pub use file_system::{+ clone_dir_with_ignore_respect, kebab_filename, relative_path, remove_ignored_entities_from_directory,+};+pub use json::update_json_field;+pub use package_swift::update_package_swift;+pub use readme::update_readme;+pub use snippets::extract_snippets;diff --git a/crates/cli-release/src/utilities/package_swift.rs b/crates/cli-release/src/utilities/package_swift.rsnew file mode 100644index 000000000..4defd290a--- /dev/null+++ b/crates/cli-release/src/utilities/package_swift.rs@@ -0,0 +1,20 @@+use std::{fs, path::PathBuf};++use crate::types::Error;++pub fn update_package_swift(+ package_swift_path: PathBuf,+ version: String,+ checksum: String,+) -> Result<(), Error> {+ let original_content = fs::read_to_string(&package_swift_path).map_err(|_| Error::UnableToUpdatePackageSwift)?;++ let framework_url = format!("https://artifacts.trymirai.com/uzu-swift/releases/{}.zip", version);++ let dependency_snippet = format!("url: \"{}\",\n checksum: \"{}\"", framework_url, checksum);++ let updated_content = original_content.replace("path: \"uzu.xcframework\"", dependency_snippet.as_str());++ fs::write(&package_swift_path, updated_content).map_err(|_| Error::UnableToUpdatePackageSwift)?;+ Ok(())+}diff --git a/crates/cli-release/src/utilities/readme.rs b/crates/cli-release/src/utilities/readme.rsnew file mode 100644index 000000000..00076c84b--- /dev/null+++ b/crates/cli-release/src/utilities/readme.rs@@ -0,0 +1,87 @@+use std::{+ collections::HashMap,+ fs,+ path::{Path, PathBuf},+};++use regex::Regex;++use crate::types::{Error, Example, Snippet};++pub fn update_readme(+ readme_path: PathBuf,+ snippets: Vec<Snippet>,+ examples: Vec<Example>,+ version: String,+) -> Result<(), Error> {+ let original_content = fs::read_to_string(&readme_path).map_err(|_| Error::UnableToUpdateREADME)?;++ let include_pattern = Regex::new(r#"(?m)^\s*//\s*include:(?P<path>[^\s#]+)(?:#(?P<snippet>[^\s]+))?\s*$"#)+ .map_err(|_| Error::UnableToUpdateREADME)?;++ // Index examples by normalized relative path+ let mut examples_by_relative_path: HashMap<String, &Example> = HashMap::new();+ for example in &examples {+ examples_by_relative_path.insert(normalize_slashes(&example.relative_path), example);+ }++ // Index snippets for quick lookup+ let mut snippets_by_name_and_source_path: HashMap<(String, String), &Snippet> = HashMap::new();+ let mut snippets_by_name: HashMap<String, Vec<&Snippet>> = HashMap::new();++ for snippet in &snippets {+ snippets_by_name_and_source_path+ .insert((snippet.name.clone(), normalize_slashes(&snippet.source_path)), snippet);+ snippets_by_name.entry(snippet.name.clone()).or_default().push(snippet);+ }++ let mut updated_content = String::with_capacity(original_content.len());+ let mut last_position = 0;++ for capture in include_pattern.captures_iter(&original_content) {+ let full_match = capture.get(0).ok_or(Error::UnableToUpdateREADME)?;+ updated_content.push_str(&original_content[last_position..full_match.start()]);++ let include_path = capture.name("path").ok_or(Error::UnableToUpdateREADME)?.as_str();+ let snippet_name = capture.name("snippet").map(|m| m.as_str());+ let normalized_include_path = normalize_slashes_str(include_path);++ // Find the matching example (by relative path)+ let example = *examples_by_relative_path.get(&normalized_include_path).ok_or(Error::UnableToUpdateREADME)?;++ // Choose replacement content (no indentation modification)+ let replacement_content = if let Some(snippet_name) = snippet_name {+ let exact_key = (snippet_name.to_string(), normalize_slashes(&example.full_path));++ if let Some(snippet) = snippets_by_name_and_source_path.get(&exact_key) {+ snippet.content.clone()+ } else {+ snippets_by_name+ .get(snippet_name)+ .and_then(|list| list.first().map(|snippet| snippet.content.clone()))+ .ok_or(Error::UnableToUpdateREADME)?+ }+ } else {+ example.content.clone()+ };++ updated_content.push_str(&replacement_content);+ last_position = full_match.end();+ }++ updated_content.push_str(&original_content[last_position..]);++ // Replace all {{VERSION}} placeholders+ let final_content = updated_content.replace("{{VERSION}}", version.as_str());++ fs::write(&readme_path, final_content).map_err(|_| Error::UnableToUpdateREADME)?;+ Ok(())+}++fn normalize_slashes(path: &Path) -> String {+ normalize_slashes_str(&path.to_string_lossy())+}++fn normalize_slashes_str<S: AsRef<str>>(text: S) -> String {+ text.as_ref().replace('\\', "/")+}diff --git a/crates/cli-release/src/utilities/snippets.rs b/crates/cli-release/src/utilities/snippets.rsnew file mode 100644index 000000000..aca1d1adb--- /dev/null+++ b/crates/cli-release/src/utilities/snippets.rs@@ -0,0 +1,73 @@+use std::{fs, path::PathBuf};++use regex::Regex;++use crate::types::{Error, Snippet};++pub fn extract_snippets(path: PathBuf) -> Result<Vec<Snippet>, Error> {+ let start_re = Regex::new(r"(?m)^\s*//\s*snippet:([^\s]+)\s*$").map_err(|_| Error::UnableToExtractSnippets)?;+ let mut results = Vec::new();++ let files = fs::read_dir(path).map_err(|_| Error::UnableToExtractSnippets)?;+ for file in files {+ let file = file.map_err(|_| Error::UnableToExtractSnippets)?;+ let path = file.path();+ let contents = fs::read_to_string(path.clone()).map_err(|_| Error::UnableToExtractSnippets)?;++ for start_cap in start_re.captures_iter(&contents) {+ let name = start_cap.get(1).ok_or_else(|| Error::UnableToExtractSnippets)?.as_str().to_string();+ let body_start = start_cap.get(0).ok_or_else(|| Error::UnableToExtractSnippets)?.end();++ let end_re = Regex::new(&format!(r"(?m)^\s*//\s*endsnippet:{}\s*$", regex::escape(&name)))+ .map_err(|_| Error::UnableToExtractSnippets)?;++ let end_match = end_re.find_at(&contents, body_start).ok_or_else(|| Error::UnableToExtractSnippets)?;++ let mut content = &contents[body_start..end_match.start()];+ if let Some(stripped) = content.strip_prefix('\n') {+ content = stripped;+ }+ let content = content.trim_end().to_string();+ let content = align_to_first_line_indent(&content).to_string();++ let snippet = Snippet::new(name, content, path.clone());+ results.push(snippet);+ }+ }++ Ok(results)+}++fn align_to_first_line_indent(body: &str) -> String {+ // Trim leading/trailing blank lines first+ let mut lines: Vec<&str> = body.lines().collect();++ // leading blanks+ while lines.first().is_some_and(|l| l.trim().is_empty()) {+ lines.remove(0);+ }+ // trailing blanks+ while lines.last().is_some_and(|l| l.trim().is_empty()) {+ lines.pop();+ }++ if lines.is_empty() {+ return String::new();+ }++ // Determine the exact whitespace prefix (spaces/tabs) of the first non-empty line+ let first_non_empty_idx = lines.iter().position(|l| !l.trim().is_empty()).unwrap_or(0);+ let first = lines[first_non_empty_idx];+ let indent_prefix: String = first.chars().take_while(|c| *c == ' ' || *c == '\t').collect();++ // Strip exactly that prefix from every line when present; leave others untouched+ let mut out = String::new();+ for (i, line) in lines.iter().enumerate() {+ let dedented = line.strip_prefix(&indent_prefix).unwrap_or(line);+ if i > 0 {+ out.push('\n');+ }+ out.push_str(dedented);+ }+ out+}diff --git a/crates/cli-storage/src/app.rs b/crates/cli-storage/src/app.rsindex 7ca987a93..50cf7761c 100644--- a/crates/cli-storage/src/app.rs+++ b/crates/cli-storage/src/app.rs@@ -39,7 +39,7 @@ impl App {for model in models {let state = engine.downloader(&model).state().await.unwrap();models_with_state.insert(- model.identifier(),+ model.identifier.clone(),ModelWithState {model,state,@@ -79,7 +79,7 @@ impl App {} else {// Model not in local HashMap; fetch from storage and add itdrop(models_guard);- if let Some(fresh_model) = engine.model_by_identifier(&model_id).await.unwrap() {+ if let Some(fresh_model) = engine.model_by_identifier(model_id.clone()).await.unwrap() {let state = engine.downloader(&fresh_model).state().await.unwrap();let mut models_guard = models.lock().await;models_guard.insert(@@ -192,7 +192,7 @@ impl App {if let Some(model_with_state) = models_guard.get(&id) {use uzu::storage::types::DownloadPhase::*;match model_with_state.state.phase {- Downloaded => {+ Downloaded {} => {// Already installed; ignore download command},_ => {diff --git a/crates/cli-storage/src/main.rs b/crates/cli-storage/src/main.rsindex 0628fe196..30d022a25 100644--- a/crates/cli-storage/src/main.rs+++ b/crates/cli-storage/src/main.rs@@ -13,7 +13,7 @@ use crossterm::{terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},};use ratatui::{Terminal, backend::CrosstermBackend};-use uzu::engine::{Config as EngineConfig, Engine};+use uzu::engine::{Engine, EngineConfig};use crate::{app::App, events::EventHandler};diff --git a/crates/cli-storage/src/sections.rs b/crates/cli-storage/src/sections.rsindex 5951f7447..0445f1936 100644--- a/crates/cli-storage/src/sections.rs+++ b/crates/cli-storage/src/sections.rs@@ -37,11 +37,14 @@ impl Section {/// Determine which section a model belongs to based on its statepub fn for_model(model_with_state: &ModelWithState) -> Self {match model_with_state.state.phase {- DownloadPhase::Downloaded => Section::Installed,- DownloadPhase::Downloading | DownloadPhase::Paused | DownloadPhase::Locked | DownloadPhase::Error(_) => {- Section::Downloading- },- DownloadPhase::NotDownloaded => Section::Available,+ DownloadPhase::Downloaded {} => Section::Installed,+ DownloadPhase::Downloading {}+ | DownloadPhase::Paused {}+ | DownloadPhase::Locked {}+ | DownloadPhase::Error {+ ..+ } => Section::Downloading,+ DownloadPhase::NotDownloaded {} => Section::Available,}}diff --git a/crates/cli-storage/src/ui.rs b/crates/cli-storage/src/ui.rsindex 72624be0a..69563fa81 100644--- a/crates/cli-storage/src/ui.rs+++ b/crates/cli-storage/src/ui.rs@@ -62,8 +62,8 @@ fn render_section(let items: Vec<ListItem> = section_models.iter().map(|(id, model_with_state)| match &model_with_state.state.phase {- uzu::storage::types::DownloadPhase::Downloaded => ListItem::new(format!("✓ {}", id)),- uzu::storage::types::DownloadPhase::NotDownloaded => {+ uzu::storage::types::DownloadPhase::Downloaded {} => ListItem::new(format!("✓ {}", id)),+ uzu::storage::types::DownloadPhase::NotDownloaded {} => {let size_mb = model_with_state.state.total_bytes as f64 / 1_000_000.0;ListItem::new(format!("{} ({:.1} MB)", id, size_mb))},@@ -178,7 +178,7 @@ fn render_downloading_model(let available_width = area.width.saturating_sub(2) as usize;let (base_label, gauge_color, border_color) = match &model_with_state.state.phase {- uzu::storage::types::DownloadPhase::Downloading => {+ uzu::storage::types::DownloadPhase::Downloading {} => {let progress_info = format!(" ({:.1}/{:.1} MB - {:.1}%)", downloaded_mb, total_mb, progress * 100.0);let name = truncate_name_for_label(id, &progress_info, available_width, is_selected);(@@ -191,7 +191,7 @@ fn render_downloading_model(},)},- uzu::storage::types::DownloadPhase::Paused => {+ uzu::storage::types::DownloadPhase::Paused {} => {let progress_info =format!(" [PAUSED] ({:.1}/{:.1} MB - {:.1}%)", downloaded_mb, total_mb, progress * 100.0);let name = truncate_name_for_label(id, &progress_info, available_width, is_selected);@@ -205,7 +205,9 @@ fn render_downloading_model(},)},- uzu::storage::types::DownloadPhase::Error(err) => {+ uzu::storage::types::DownloadPhase::Error {+ message: err,+ } => {let error_info = format!(" [ERROR: {}]", err);let name = truncate_name_for_label(id, &error_info, available_width, is_selected);(diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.tomlindex 012a92188..d09beadd8 100644--- a/crates/cli/Cargo.toml+++ b/crates/cli/Cargo.toml@@ -13,7 +13,7 @@ path = "src/main.rs"[dependencies]clap.workspace = true-uzu.workspace = true+backend-uzu.workspace = truebenchmarks.workspace = truectrlc.workspace = trueindicatif.workspace = true@@ -29,4 +29,4 @@ comfy-table.workspace = true[features]default = ["metal"]-metal = ["benchmarks/metal", "uzu/metal"]+metal = ["benchmarks/metal", "backend-uzu/metal"]diff --git a/crates/cli/src/handlers/run.rs b/crates/cli/src/handlers/run.rsindex c715c908c..c35788fe9 100644--- a/crates/cli/src/handlers/run.rs+++ b/crates/cli/src/handlers/run.rs@@ -3,14 +3,14 @@ use std::sync::{atomic::{AtomicBool, Ordering},};-use console::Style;-use indicatif::{ProgressBar, ProgressStyle};-use inquire::Text;-use uzu::session::{+use backend_uzu::session::{config::RunConfig,parameter::SamplingPolicy,types::{Input, Output},};+use console::Style;+use indicatif::{ProgressBar, ProgressStyle};+use inquire::Text;use crate::server::load_session;diff --git a/crates/cli/src/server/chat_completions.rs b/crates/cli/src/server/chat_completions.rsindex 26c9a2146..2558566ed 100644--- a/crates/cli/src/server/chat_completions.rs+++ b/crates/cli/src/server/chat_completions.rs@@ -6,6 +6,11 @@ use std::{time::{SystemTime, UNIX_EPOCH},};+use backend_uzu::session::{+ config::RunConfig,+ parameter::SamplingPolicy,+ types::{FinishReason, Input, Message, Output, Role, RunStats, Stats, StepStats, TotalStats},+};use rocket::{Request, State,http::{ContentType, Header},@@ -16,11 +21,6 @@ use rocket::{use serde::{Deserialize, Serialize};use tokio::io::{AsyncRead, ReadBuf};use uuid::Uuid;-use uzu::session::{- config::RunConfig,- parameter::SamplingPolicy,- types::{FinishReason, Input, Message, Output, Role, RunStats, Stats, StepStats, TotalStats},-};use crate::server::{SessionState, SessionWrapper};diff --git a/crates/cli/src/server/state.rs b/crates/cli/src/server/state.rsindex 5e977e5ad..8818a6373 100644--- a/crates/cli/src/server/state.rs+++ b/crates/cli/src/server/state.rs@@ -3,9 +3,7 @@ use std::{sync::{Arc, Mutex},};-use console::Style;-use indicatif::{ProgressBar, ProgressStyle};-use uzu::{+use backend_uzu::{prelude::{NGramSpeculator, SamplingSeed, SpeculatorConfig},session::{Session,@@ -14,6 +12,8 @@ use uzu::{types::{Error, Input, Output},},};+use console::Style;+use indicatif::{ProgressBar, ProgressStyle};pub trait RunSession {fn run(diff --git a/crates/cli/tests/chat_completions.rs b/crates/cli/tests/chat_completions.rsindex 82e61036e..42db319b0 100644--- a/crates/cli/tests/chat_completions.rs+++ b/crates/cli/tests/chat_completions.rs@@ -1,15 +1,15 @@use std::sync::Arc;+use backend_uzu::session::{+ config::RunConfig,+ types::{Error, FinishReason, Input, Output, ParsedText, RunStats, Stats, StepStats, Text, TotalStats},+};use cli::server::{handle_chat_completions,state::{RunSession, SessionState, SessionWrapper},};use rocket::{http::Status, local::asynchronous::Client, routes};use serde_json::{Value, json};-use uzu::session::{- config::RunConfig,- types::{Error, FinishReason, Input, Output, ParsedText, RunStats, Stats, StepStats, Text, TotalStats},-};struct MockSession {result: Result<String, Error>,diff --git a/crates/download-manager/tests/test_apple_manager_lock_file.rs b/crates/download-manager/tests/test_apple_manager_lock_file.rsindex a9b04c1c3..4eff4a5a0 100644--- a/crates/download-manager/tests/test_apple_manager_lock_file.rs+++ b/crates/download-manager/tests/test_apple_manager_lock_file.rs@@ -8,6 +8,7 @@ use download_manager::{};use tokio::time::sleep;+#[ignore]#[tokio::test(flavor = "multi_thread")]async fn test_apple_manager_lock_file_prevents_concurrent_downloads() -> Result<(), Box<dyn std::error::Error>> {tracing::info!("[TEST] ========== LOCK FILE CONCURRENT DOWNLOAD TEST ==========");diff --git a/crates/hanashi/src/chat/config.rs b/crates/hanashi/src/chat/config.rsindex a59c1deca..38d7f8729 100644--- a/crates/hanashi/src/chat/config.rs+++ b/crates/hanashi/src/chat/config.rs@@ -1,5 +1,5 @@use serde::{Deserialize, Serialize};-use shoji::types::encoding::Capabilities;+use shoji::types::session::chat::ChatModelCapabilities;use crate::chat::{Error, hanashi::Config as HanashiConfig, harmony::Config as HarmonyConfig};@@ -11,7 +11,7 @@ pub enum Config {}impl Config {- pub fn capabilities(&self) -> Result<Capabilities, Error> {+ pub fn capabilities(&self) -> Result<ChatModelCapabilities, Error> {match self {Config::Hanashi(config) => config.capabilities().map_err(Error::from),Config::Harmony(config) => Ok(config.capabilities()),diff --git a/crates/hanashi/src/chat/hanashi/config/mod.rs b/crates/hanashi/src/chat/hanashi/config/mod.rsindex 641270ce0..2a9687920 100644--- a/crates/hanashi/src/chat/hanashi/config/mod.rs+++ b/crates/hanashi/src/chat/hanashi/config/mod.rs@@ -2,7 +2,10 @@ mod bundled;mod tokens;use serde::{Deserialize, Serialize};-use shoji::types::encoding::{Capabilities, ContentBlockType, ReasoningEffort};+use shoji::types::{+ basic::ReasoningEffort,+ session::chat::{ChatContentBlockType, ChatModelCapabilities},+};use token_stream_parser::token_stream::TokenStreamParserConfig;pub use tokens::TokensConfig;@@ -86,12 +89,12 @@ pub enum Config {}impl Config {- pub fn capabilities(&self) -> Result<Capabilities, Error> {+ pub fn capabilities(&self) -> Result<ChatModelCapabilities, Error> {let resolved = self.clone().resolve()?;let rendering = &resolved.rendering;let supports_multiple_tool_calls = rendering- .get_rendering_field_for_block_type(&ContentBlockType::ToolCall)+ .get_rendering_field_for_block_type(&ChatContentBlockType::ToolCall).and_then(|field| match &field.config {FieldConfig::Collected {limit,@@ -102,7 +105,7 @@ impl Config {.map_or(true, |limit| limit > 1);let supports_disable_reasoning = rendering- .get_rendering_field_for_block_type(&ContentBlockType::ReasoningEffort)+ .get_rendering_field_for_block_type(&ChatContentBlockType::ReasoningEffort).map_or(false, |field| match &field.config {FieldConfig::Unique {mapping: Some(mapping),@@ -111,14 +114,16 @@ impl Config {_ => false,});- let tools_role_and_field = rendering.get_rendering_role_and_field_for_block_type(&ContentBlockType::Tools);+ let tools_role_and_field = rendering.get_rendering_role_and_field_for_block_type(&ChatContentBlockType::Tools);let supports_tools = tools_role_and_field.is_some();let requires_tools = tools_role_and_field.map(|(role, field)| field.required && !resolved.ordering.is_role_avoidable(role)).unwrap_or(false);- Ok(Capabilities {- supports_reasoning: rendering.get_rendering_field_for_block_type(&ContentBlockType::Reasoning).is_some(),+ Ok(ChatModelCapabilities {+ supports_reasoning: rendering+ .get_rendering_field_for_block_type(&ChatContentBlockType::Reasoning)+ .is_some(),supports_disable_reasoning,supports_tools,supports_multiple_tool_calls,diff --git a/crates/hanashi/src/chat/hanashi/messages/canonical/content_block.rs b/crates/hanashi/src/chat/hanashi/messages/canonical/content_block.rsindex d42a21de7..55633721c 100644--- a/crates/hanashi/src/chat/hanashi/messages/canonical/content_block.rs+++ b/crates/hanashi/src/chat/hanashi/messages/canonical/content_block.rs@@ -1,7 +1,7 @@use serde_json::Value;-use shoji::types::encoding::ContentBlockType;+use shoji::types::session::chat::ChatContentBlockType;pub struct ContentBlock {- pub r#type: ContentBlockType,+ pub r#type: ChatContentBlockType,pub value: Value,}diff --git a/crates/hanashi/src/chat/hanashi/messages/canonical/message.rs b/crates/hanashi/src/chat/hanashi/messages/canonical/message.rsindex ea8c7a213..b59acda22 100644--- a/crates/hanashi/src/chat/hanashi/messages/canonical/message.rs+++ b/crates/hanashi/src/chat/hanashi/messages/canonical/message.rs@@ -2,8 +2,11 @@ use std::collections::HashMap;use indexmap::IndexMap;use serde_json::Value;-use shoji::types::encoding::{- ContentBlock as OriginalContentBlock, ContentBlockType, Message as OriginalMessage, Role, TranslationInput,+use shoji::types::{+ basic::TranslationPayload,+ session::chat::{+ ChatContentBlock as OriginalContentBlock, ChatContentBlockType, ChatMessage as OriginalMessage, ChatRole,+ },};use crate::chat::hanashi::messages::{@@ -12,7 +15,7 @@ use crate::chat::hanashi::messages::{};pub struct Message {- pub role: Role,+ pub role: ChatRole,pub content: Vec<ContentBlock>,pub metadata: HashMap<String, Value>,}@@ -21,7 +24,7 @@ impl Message {pub fn from_message(message: &OriginalMessage,config: &Config,- raw_types: &[ContentBlockType],+ raw_types: &[ChatContentBlockType],) -> Result<Self, Error> {let mut content = Vec::new();for block in &message.content {@@ -39,6 +42,7 @@ impl Message {content,metadata: message.metadata+ .values.iter().map(|(key, value)| {let json_value: Value =@@ -132,7 +136,7 @@ impl Message {value,} => serde_json::to_value(value.clone()),OriginalContentBlock::Translation {- input,+ payload: input,source_language_code,target_language_code,} => {@@ -148,13 +152,13 @@ impl Message {.unwrap_or_else(|| "target_language_code".to_string());let mut map = IndexMap::new();match input {- TranslationInput::Text {+ TranslationPayload::Text {text,} => {map.insert(config.type_key.clone(), Value::String(config.text_key.clone()));map.insert(config.text_key.clone(), Value::String(text.clone()));},- TranslationInput::Image {+ TranslationPayload::Image {url,} => {let url_key = config.url_key.as_ref().ok_or_else(|| Error::SerializationFailed {diff --git a/crates/hanashi/src/chat/hanashi/messages/error.rs b/crates/hanashi/src/chat/hanashi/messages/error.rsindex e8adfe05f..07430a355 100644--- a/crates/hanashi/src/chat/hanashi/messages/error.rs+++ b/crates/hanashi/src/chat/hanashi/messages/error.rs@@ -1,11 +1,11 @@-use shoji::types::encoding::{ContentBlockType, Role};+use shoji::types::session::chat::{ChatContentBlockType, ChatRole};#[derive(Debug, thiserror::Error)]#[non_exhaustive]pub enum Error {#[error("Role '{role}' is not supported")]UnsupportedRole {- role: Role,+ role: ChatRole,},#[error("Serialization failed: {reason}")]SerializationFailed {@@ -13,40 +13,40 @@ pub enum Error {},#[error("Content block '{block_type}' is not supported for role '{role}'")]UnsupportedBlock {- role: Role,- block_type: ContentBlockType,+ role: ChatRole,+ block_type: ChatContentBlockType,},#[error("Multiple '{block_type}' blocks are not allowed for role '{role}'")]MultipleNotAllowed {- role: Role,- block_type: ContentBlockType,+ role: ChatRole,+ block_type: ChatContentBlockType,},#[error("Value of '{block_type}' is not allowed for role '{role}'")]ValueNotAllowed {- role: Role,- block_type: ContentBlockType,+ role: ChatRole,+ block_type: ChatContentBlockType,allowed_values: String,},#[error("Cannot map '{value}' for '{block_type}' on role '{role}'")]UnmappedValue {- role: Role,- block_type: ContentBlockType,+ role: ChatRole,+ block_type: ChatContentBlockType,value: String,},#[error("Field '{field}' is required for role '{role}' but was not provided")]FieldRequired {- role: Role,+ role: ChatRole,field: String,},#[error("Block type '{block_type}' is assigned to multiple fields for role '{role}'")]DuplicateBlock {- role: Role,- block_type: ContentBlockType,+ role: ChatRole,+ block_type: ChatContentBlockType,},#[error("Limit of {limit} exceeded for '{block_type}' on role '{role}'")]LimitExceeded {- role: Role,- block_type: ContentBlockType,+ role: ChatRole,+ block_type: ChatContentBlockType,limit: usize,},}diff --git a/crates/hanashi/src/chat/hanashi/messages/rendered/config.rs b/crates/hanashi/src/chat/hanashi/messages/rendered/config.rsindex c68c00f10..727fbd55e 100644--- a/crates/hanashi/src/chat/hanashi/messages/rendered/config.rs+++ b/crates/hanashi/src/chat/hanashi/messages/rendered/config.rs@@ -1,7 +1,7 @@use indexmap::IndexMap;use serde::{Deserialize, Serialize};use serde_json::Value;-use shoji::types::encoding::ContentBlockType;+use shoji::types::session::chat::ChatContentBlockType;#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Field {@@ -17,14 +17,14 @@ pub struct Field {#[serde(untagged)]pub enum FieldConfig {Unique {- block: ContentBlockType,+ block: ChatContentBlockType,#[serde(default, skip_serializing_if = "Option::is_none")]mapping: Option<IndexMap<String, Option<Value>>>,#[serde(default, skip_serializing_if = "Option::is_none")]allowed_values: Option<Vec<Value>>,},Collected {- blocks: Vec<ContentBlockType>,+ blocks: Vec<ChatContentBlockType>,#[serde(default, skip_serializing_if = "Option::is_none")]limit: Option<usize>,},diff --git a/crates/hanashi/src/chat/hanashi/messages/rendered/message.rs b/crates/hanashi/src/chat/hanashi/messages/rendered/message.rsindex 9ae81f1b8..e7b2b25cb 100644--- a/crates/hanashi/src/chat/hanashi/messages/rendered/message.rs+++ b/crates/hanashi/src/chat/hanashi/messages/rendered/message.rs@@ -2,7 +2,7 @@ use std::collections::HashMap;use indexmap::IndexMap;use serde_json::{Map, Value};-use shoji::types::encoding::{ContentBlockType, Message as OriginalMessage, Role};+use shoji::types::session::chat::{ChatContentBlockType, ChatMessage as OriginalMessage, ChatRole};use crate::chat::hanashi::messages::{Error,@@ -20,7 +20,7 @@ impl Message {pub fn from_message(original_message: &OriginalMessage,canonical_config: &CanonicalConfig,- rendered_configs: &IndexMap<Role, Config>,+ rendered_configs: &IndexMap<ChatRole, Config>,) -> Result<Self, Error> {let role = &original_message.role;@@ -29,7 +29,7 @@ impl Message {})?;// Validate no duplicate block types across fields- let mut seen_block_types: IndexMap<ContentBlockType, String> = IndexMap::new();+ let mut seen_block_types: IndexMap<ChatContentBlockType, String> = IndexMap::new();for (field_name, field) in config.message.iter().chain(config.context.iter()) {let block_types = match &field.config {FieldConfig::Unique {@@ -55,7 +55,7 @@ impl Message {}// Determine which block types should get raw canonical serialization- let mut raw_types: Vec<ContentBlockType> = Vec::new();+ let mut raw_types: Vec<ChatContentBlockType> = Vec::new();for (_, field) in config.message.iter().chain(config.context.iter()) {if field.disable_raw {continue;@@ -142,7 +142,7 @@ impl Message {fn find_field_for_block<'a>(fields: &'a IndexMap<String, Field>,- block_type: &ContentBlockType,+ block_type: &ChatContentBlockType,) -> Option<(String, &'a Field)> {fields.iter().find_map(|(name, field)| {let matches = match &field.config {@@ -169,8 +169,8 @@ fn apply_field_value(config: &FieldConfig,value: &Value,raw: bool,- role: &Role,- block_type: &ContentBlockType,+ role: &ChatRole,+ block_type: &ChatContentBlockType,) -> Result<(), Error> {match config {FieldConfig::Unique {diff --git a/crates/hanashi/src/chat/hanashi/messages/streamed/content.rs b/crates/hanashi/src/chat/hanashi/messages/streamed/content.rsindex 13308a949..c68363bc6 100644--- a/crates/hanashi/src/chat/hanashi/messages/streamed/content.rs+++ b/crates/hanashi/src/chat/hanashi/messages/streamed/content.rs@@ -1,6 +1,9 @@use serde::{Deserialize, Serialize};use serde_json::Value;-use shoji::types::encoding::{ContentBlock, Role, ToolCall};+use shoji::types::{+ basic::ToolCall,+ session::chat::{ChatContentBlock, ChatRole},+};use crate::chat::hanashi::messages::streamed::Section;@@ -15,26 +18,26 @@ pub enum Content {impl Content {pub fn blocks(self,- role: &Role,- ) -> Vec<ContentBlock> {+ role: &ChatRole,+ ) -> Vec<ChatContentBlock> {match self {- Content::Text(text) => vec![ContentBlock::Text {+ Content::Text(text) => vec![ChatContentBlock::Text {value: text,}],Content::Value(value) => match role {- Role::Tool {} => vec![ContentBlock::ToolCallResult {+ ChatRole::Tool {} => vec![ChatContentBlock::ToolCallResult {identifier: None,name: None,value: value.into(),}],- _ => vec![ContentBlock::Custom {+ _ => vec![ChatContentBlock::Custom {value: value.into(),}],},Content::Sections(sections) => {let mut reasoning_parts: Vec<String> = Vec::new();let mut text_parts: Vec<String> = Vec::new();- let mut tool_calls: Vec<ContentBlock> = Vec::new();+ let mut tool_calls: Vec<ChatContentBlock> = Vec::new();for section in sections {match section {@@ -48,10 +51,10 @@ impl Content {value: Some(value),} => {let block = match serde_json::from_value::<ToolCall>(value.clone()) {- Ok(tool_call) => ContentBlock::ToolCall {+ Ok(tool_call) => ChatContentBlock::ToolCall {value: tool_call,},- Err(_) => ContentBlock::ToolCallCandidate {+ Err(_) => ChatContentBlock::ToolCallCandidate {value: value.into(),},};@@ -60,7 +63,7 @@ impl Content {Section::ToolCall {value: None,} => {- tool_calls.push(ContentBlock::ToolCallCandidate {+ tool_calls.push(ChatContentBlock::ToolCallCandidate {value: Value::Null.into(),});},@@ -72,12 +75,12 @@ impl Content {let text = text_parts.concat().trim().to_string();let mut blocks = Vec::new();if !reasoning.is_empty() {- blocks.push(ContentBlock::Reasoning {+ blocks.push(ChatContentBlock::Reasoning {value: reasoning,});}if !text.is_empty() {- blocks.push(ContentBlock::Text {+ blocks.push(ChatContentBlock::Text {value: text,});}diff --git a/crates/hanashi/src/chat/hanashi/messages/streamed/mod.rs b/crates/hanashi/src/chat/hanashi/messages/streamed/mod.rsindex c3840a598..3ee5ae753 100644--- a/crates/hanashi/src/chat/hanashi/messages/streamed/mod.rs+++ b/crates/hanashi/src/chat/hanashi/messages/streamed/mod.rs@@ -6,18 +6,18 @@ use std::{collections::HashMap, str::FromStr};pub use content::Content;pub use section::Section;use serde::{Deserialize, Deserializer};-use shoji::types::encoding::{Message as CommonMessage, Role};+use shoji::types::session::chat::{ChatMessage as CommonMessage, ChatMessageMetadata, ChatRole};#[derive(Deserialize)]pub struct Message {#[serde(deserialize_with = "deserialize_trimmed_role")]- pub role: Role,+ pub role: ChatRole,pub content: Option<Content>,}-fn deserialize_trimmed_role<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Role, D::Error> {+fn deserialize_trimmed_role<'de, D: Deserializer<'de>>(deserializer: D) -> Result<ChatRole, D::Error> {let name = String::deserialize(deserializer)?;- Role::from_str(name.trim()).map_err(serde::de::Error::custom)+ ChatRole::from_str(name.trim()).map_err(serde::de::Error::custom)}impl From<Message> for CommonMessage {@@ -28,7 +28,9 @@ impl From<Message> for CommonMessage {None => Vec::new(),},role: message.role,- metadata: HashMap::new(),+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },}}}diff --git a/crates/hanashi/src/chat/hanashi/mod.rs b/crates/hanashi/src/chat/hanashi/mod.rsindex 4af218f0b..d7271bd6c 100644--- a/crates/hanashi/src/chat/hanashi/mod.rs+++ b/crates/hanashi/src/chat/hanashi/mod.rs@@ -11,7 +11,7 @@ pub use config::Config;pub use error::Error;use shoji::types::{basic::{Token, TokenId},- encoding::{ContentBlock, Message},+ session::chat::{ChatContentBlock, ChatMessage},};use token_stream_parser::{Parser as _, token_stream::TokenStreamParser};use tokenizers::{Tokenizer, step_decode_stream};@@ -43,7 +43,7 @@ pub struct Encoding {impl EncodingTrait for Encoding {type Config = Config;type Context = Context;- type Input = Vec<Message>;+ type Input = Vec<ChatMessage>;type Output = Vec<TokenId>;type State = State;type Error = Error;@@ -138,8 +138,8 @@ impl EncodingTrait for Encoding {impl Encoding {fn fill_default_content(&self,- messages: &[Message],- ) -> Result<Vec<Message>, Error> {+ messages: &[ChatMessage],+ ) -> Result<Vec<ChatMessage>, Error> {let mut modified_messages = Vec::new();for message in messages {let mut modified_message = message.clone();@@ -168,7 +168,7 @@ impl Encoding {{modified_message.content.insert(0,- ContentBlock::Text {+ ChatContentBlock::Text {value: expected_value,},);@@ -187,12 +187,12 @@ impl Encoding {fn update_messages_from_parser_state(&mut self) -> Result<(), Error> {let value = self.parser.state().value.clone();let rendering_config = &self.config.rendering;- let streamed_messages: Vec<Message> = serde_json::from_value::<Vec<StreamedMessage>>(value)+ let streamed_messages: Vec<ChatMessage> = serde_json::from_value::<Vec<StreamedMessage>>(value).map_err(|_| Error::InvalidStreamedContent)?.into_iter().map(|streamed_message| {let role = rendering_config.get_role_by_name(&streamed_message.role.to_string());- let mut message = Message::from(streamed_message);+ let mut message = ChatMessage::from(streamed_message);message.role = role;message})diff --git a/crates/hanashi/src/chat/hanashi/ordering/config.rs b/crates/hanashi/src/chat/hanashi/ordering/config.rsindex 418cac9c0..27dbf9d24 100644--- a/crates/hanashi/src/chat/hanashi/ordering/config.rs+++ b/crates/hanashi/src/chat/hanashi/ordering/config.rs@@ -1,17 +1,17 @@use indexmap::IndexMap;use serde::{Deserialize, Serialize};-use shoji::types::encoding::Role;+use shoji::types::session::chat::ChatRole;#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Config {- pub initial: Vec<Role>,- pub transitions: IndexMap<Role, Vec<Role>>,+ pub initial: Vec<ChatRole>,+ pub transitions: IndexMap<ChatRole, Vec<ChatRole>>,}impl Config {pub fn is_role_avoidable(&self,- role: &Role,+ role: &ChatRole,) -> bool {let other_initials = self.initial.iter().any(|initial| initial != role);let all_transitions_have_alternatives = selfdiff --git a/crates/hanashi/src/chat/hanashi/ordering/error.rs b/crates/hanashi/src/chat/hanashi/ordering/error.rsindex d79bf96fe..6013f55a7 100644--- a/crates/hanashi/src/chat/hanashi/ordering/error.rs+++ b/crates/hanashi/src/chat/hanashi/ordering/error.rs@@ -1,4 +1,4 @@-use shoji::types::encoding::Role;+use shoji::types::session::chat::ChatRole;#[derive(Debug, thiserror::Error)]pub enum Error {@@ -6,17 +6,17 @@ pub enum Error {InvalidTransition {after: String,expected: String,- got: Role,+ got: ChatRole,},#[error("Expected one of [{expected}] at start, got '{got}'")]InvalidInitial {expected: String,- got: Role,+ got: ChatRole,},#[error("No transitions defined for role '{role}'")]NoTransitions {- role: Role,+ role: ChatRole,},}diff --git a/crates/hanashi/src/chat/hanashi/ordering/validator.rs b/crates/hanashi/src/chat/hanashi/ordering/validator.rsindex 1058abe98..c035fd420 100644--- a/crates/hanashi/src/chat/hanashi/ordering/validator.rs+++ b/crates/hanashi/src/chat/hanashi/ordering/validator.rs@@ -1,9 +1,9 @@-use shoji::types::encoding::Role;+use shoji::types::session::chat::ChatRole;use crate::chat::hanashi::ordering::{Config, Error};pub struct Validator {- current: Option<Role>,+ current: Option<ChatRole>,config: Config,}@@ -21,9 +21,9 @@ impl Validator {pub fn validate_next(&mut self,- role: &Role,+ role: &ChatRole,) -> Result<(), Error> {- if matches!(role, Role::Custom { .. }) {+ if matches!(role, ChatRole::Custom { .. }) {return Ok(());}@@ -54,6 +54,6 @@ impl Validator {}}-fn format_roles(roles: &[Role]) -> String {+fn format_roles(roles: &[ChatRole]) -> String {roles.iter().map(|role| role.to_string()).collect::<Vec<_>>().join(", ")}diff --git a/crates/hanashi/src/chat/hanashi/renderer/config/mod.rs b/crates/hanashi/src/chat/hanashi/renderer/config/mod.rsindex dc44f9bfd..e31cc6e91 100644--- a/crates/hanashi/src/chat/hanashi/renderer/config/mod.rs+++ b/crates/hanashi/src/chat/hanashi/renderer/config/mod.rs@@ -5,7 +5,7 @@ use indexmap::IndexMap;pub use jinja::JinjaConfig;pub use jinja_function::JinjaFunction;use serde::{Deserialize, Serialize};-use shoji::types::encoding::{ContentBlockType, Role};+use shoji::types::session::chat::{ChatContentBlockType, ChatRole};use crate::chat::hanashi::messages::{canonical::Config as CanonicalConfig,@@ -16,27 +16,27 @@ use crate::chat::hanashi::messages::{pub struct RendererConfig {pub jinja: JinjaConfig,pub canonization: CanonicalConfig,- pub rendering: IndexMap<Role, RenderedConfig>,+ pub rendering: IndexMap<ChatRole, RenderedConfig>,}impl RendererConfig {pub fn get_role_by_name(&self,name: &str,- ) -> Role {+ ) -> ChatRole {self.rendering.iter().find(|(_, rendered_config)| rendered_config.role == name).map(|(role, _)| role.clone())- .unwrap_or_else(|| Role::Custom {+ .unwrap_or_else(|| ChatRole::Custom {name: name.to_string(),})}pub fn get_rendering_role_and_field_for_block_type(&self,- block_type: &ContentBlockType,- ) -> Option<(&Role, &Field)> {+ block_type: &ChatContentBlockType,+ ) -> Option<(&ChatRole, &Field)> {self.rendering.iter().find_map(|(role, role_config)| {role_config.message@@ -58,7 +58,7 @@ impl RendererConfig {pub fn get_rendering_field_for_block_type(&self,- block_type: &ContentBlockType,+ block_type: &ChatContentBlockType,) -> Option<&Field> {self.get_rendering_role_and_field_for_block_type(block_type).map(|(_, field)| field)}diff --git a/crates/hanashi/src/chat/hanashi/renderer/mod.rs b/crates/hanashi/src/chat/hanashi/renderer/mod.rsindex c7518396d..cf7bc76e5 100644--- a/crates/hanashi/src/chat/hanashi/renderer/mod.rs+++ b/crates/hanashi/src/chat/hanashi/renderer/mod.rs@@ -8,7 +8,7 @@ use functions::{raise_exception, strftime_now, to_json};use indexmap::IndexMap;use minijinja::Environment;use minijinja_contrib::pycompat::unknown_method_callback;-use shoji::types::{basic::Token, encoding::Message};+use shoji::types::{basic::Token, session::chat::ChatMessage};use crate::chat::hanashi::messages::rendered::Message as RenderedMessage;@@ -27,7 +27,7 @@ impl Renderer {pub fn render(&self,- messages: &[Message],+ messages: &[ChatMessage],should_add_preamble: bool,bos_token: Option<Token>,eos_token: Option<Token>,diff --git a/crates/hanashi/src/chat/harmony/bridging/message.rs b/crates/hanashi/src/chat/harmony/bridging/message.rsindex 3fb892529..351965c24 100644--- a/crates/hanashi/src/chat/harmony/bridging/message.rs+++ b/crates/hanashi/src/chat/harmony/bridging/message.rs@@ -5,8 +5,8 @@ use openai_harmony::chat::{Message as ExternalMessage, Role as ExternalRole, SystemContent as ExternalSystemContent, TextContent,};use shoji::types::{- basic::Value,- encoding::{ContentBlock, Message, ReasoningEffort, Role, ToolCall, ToolNamespace},+ basic::{ReasoningEffort, ToolCall, ToolNamespace, Value},+ session::chat::{ChatContentBlock, ChatMessage, ChatMessageMetadata, ChatRole},};use crate::chat::harmony::bridging::{Error, FromHarmony, ToHarmony};@@ -20,43 +20,43 @@ const RECIPIENT_ASSISTANT: &str = "assistant";const BUILTIN_BROWSER: &str = "browser";const BUILTIN_PYTHON: &str = "python";-pub fn bridge_messages_to_harmony(messages: &[Message]) -> Result<Vec<ExternalMessage>, Error> {+pub fn bridge_messages_to_harmony(messages: &[ChatMessage]) -> Result<Vec<ExternalMessage>, Error> {let mut result = Vec::new();for message in messages {match &message.role {- Role::System {} => {+ ChatRole::System {} => {let mut system_filled = false;let mut system_content = ExternalSystemContent::default();let mut text_parts: Vec<String> = Vec::new();for block in &message.content {match block {- ContentBlock::Identity {+ ChatContentBlock::Identity {value,} => {system_filled = true;system_content.model_identity = Some(value.clone());},- ContentBlock::ReasoningEffort {+ ChatContentBlock::ReasoningEffort {value,} => {system_filled = true;system_content.reasoning_effort = Some(value.clone().to_harmony()?);},- ContentBlock::ConversationStartDate {+ ChatContentBlock::ConversationStartDate {value,} => {system_filled = true;system_content.conversation_start_date = Some(value.clone());},- ContentBlock::KnowledgeCutoff {+ ChatContentBlock::KnowledgeCutoff {value,} => {system_filled = true;system_content.knowledge_cutoff = Some(value.clone());},- ContentBlock::BuiltinTools {+ ChatContentBlock::BuiltinTools {names,} => {for name in names {@@ -77,7 +77,7 @@ pub fn bridge_messages_to_harmony(messages: &[Message]) -> Result<Vec<ExternalMe}}},- ContentBlock::Text {+ ChatContentBlock::Text {value,} => {text_parts.push(value.clone());@@ -109,18 +109,18 @@ pub fn bridge_messages_to_harmony(messages: &[Message]) -> Result<Vec<ExternalMecontent_type: None,});},- Role::Developer {} => {+ ChatRole::Developer {} => {let mut developer_content = ExternalDeveloperContent::default();let mut text_parts: Vec<String> = Vec::new();for block in &message.content {match block {- ContentBlock::Text {+ ChatContentBlock::Text {value,} => {text_parts.push(value.clone());},- ContentBlock::Tools {+ ChatContentBlock::Tools {namespaces,} => {for namespace in namespaces {@@ -148,12 +148,12 @@ pub fn bridge_messages_to_harmony(messages: &[Message]) -> Result<Vec<ExternalMecontent_type: None,});},- Role::User {} => {+ ChatRole::User {} => {let mut text_parts: Vec<String> = Vec::new();for block in &message.content {match block {- ContentBlock::Text {+ ChatContentBlock::Text {value,} => {text_parts.push(value.clone());@@ -175,24 +175,24 @@ pub fn bridge_messages_to_harmony(messages: &[Message]) -> Result<Vec<ExternalMeresult.push(ExternalMessage::from_role_and_content(ExternalRole::User, text_parts.join("")));},- Role::Assistant {} => {+ ChatRole::Assistant {} => {let mut reasoning_parts: Vec<String> = Vec::new();let mut text_parts: Vec<String> = Vec::new();let mut tool_calls: Vec<ToolCall> = Vec::new();for block in &message.content {match block {- ContentBlock::Reasoning {+ ChatContentBlock::Reasoning {value,} => {reasoning_parts.push(value.clone());},- ContentBlock::Text {+ ChatContentBlock::Text {value,} => {text_parts.push(value.clone());},- ContentBlock::ToolCall {+ ChatContentBlock::ToolCall {value,} => {tool_calls.push(value.clone());@@ -244,13 +244,13 @@ pub fn bridge_messages_to_harmony(messages: &[Message]) -> Result<Vec<ExternalMe);}},- Role::Tool {} => {+ ChatRole::Tool {} => {if message.content.len() != 1 {return Err(Error::MultipleContentBlocks);}let block = &message.content[0];- let ContentBlock::ToolCallResult {+ let ChatContentBlock::ToolCallResult {identifier: _,name,value,@@ -280,7 +280,7 @@ pub fn bridge_messages_to_harmony(messages: &[Message]) -> Result<Vec<ExternalMe.with_recipient(RECIPIENT_ASSISTANT),);},- Role::Custom {+ ChatRole::Custom {..} => {return Err(Error::UnsupportedRole {@@ -293,7 +293,7 @@ pub fn bridge_messages_to_harmony(messages: &[Message]) -> Result<Vec<ExternalMeOk(result)}-pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<Message>, Error> {+pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<ChatMessage>, Error> {let mut result = Vec::new();let mut index = 0;@@ -308,36 +308,36 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<match external_content {ExternalContent::SystemContent(system_content) => {if let Some(identity) = &system_content.model_identity {- content.push(ContentBlock::Identity {+ content.push(ChatContentBlock::Identity {value: identity.clone(),});}if let Some(effort) = &system_content.reasoning_effort {- content.push(ContentBlock::ReasoningEffort {+ content.push(ChatContentBlock::ReasoningEffort {value: ReasoningEffort::from_harmony(*effort),});}if let Some(date) = &system_content.conversation_start_date {- content.push(ContentBlock::ConversationStartDate {+ content.push(ChatContentBlock::ConversationStartDate {value: date.clone(),});}if let Some(cutoff) = &system_content.knowledge_cutoff {- content.push(ContentBlock::KnowledgeCutoff {+ content.push(ChatContentBlock::KnowledgeCutoff {value: cutoff.clone(),});}if let Some(tools) = &system_content.tools {let names: Vec<String> = tools.keys().cloned().collect();if !names.is_empty() {- content.push(ContentBlock::BuiltinTools {+ content.push(ChatContentBlock::BuiltinTools {names,});}}},ExternalContent::Text(text_content) => {- content.push(ContentBlock::Text {+ content.push(ChatContentBlock::Text {value: text_content.text.clone(),});},@@ -349,10 +349,12 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<}}- result.push(Message {- role: Role::System {},+ result.push(ChatMessage {+ role: ChatRole::System {},content,- metadata: HashMap::new(),+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },});index += 1;},@@ -363,7 +365,7 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<match external_content {ExternalContent::DeveloperContent(developer_content) => {if let Some(instructions) = &developer_content.instructions {- content.push(ContentBlock::Text {+ content.push(ChatContentBlock::Text {value: instructions.clone(),});}@@ -371,14 +373,14 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<let namespaces: Vec<ToolNamespace> =tools.values().cloned().map(ToolNamespace::from_harmony).collect();if !namespaces.is_empty() {- content.push(ContentBlock::Tools {+ content.push(ChatContentBlock::Tools {namespaces,});}}},ExternalContent::Text(text_content) => {- content.push(ContentBlock::Text {+ content.push(ChatContentBlock::Text {value: text_content.text.clone(),});},@@ -390,22 +392,26 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<}}- result.push(Message {- role: Role::Developer {},+ result.push(ChatMessage {+ role: ChatRole::Developer {},content,- metadata: HashMap::new(),+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },});index += 1;},ExternalRole::User => {let text = extract_text_content(&message.content);- result.push(Message {- role: Role::User {},- content: vec![ContentBlock::Text {+ result.push(ChatMessage {+ role: ChatRole::User {},+ content: vec![ChatContentBlock::Text {value: text,}],- metadata: HashMap::new(),+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },});index += 1;},@@ -418,7 +424,7 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<match assistant_message.channel.as_deref() {Some(CHANNEL_ANALYSIS) => {- content.push(ContentBlock::Reasoning {+ content.push(ChatContentBlock::Reasoning {value: text,});},@@ -431,7 +437,7 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<match serde_json::from_str::<serde_json::Value>(&text) {Ok(json_value) => {- content.push(ContentBlock::ToolCall {+ content.push(ChatContentBlock::ToolCall {value: ToolCall {identifier: None,name: name.to_string(),@@ -440,14 +446,14 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<});},Err(_) => {- content.push(ContentBlock::ToolCallCandidate {+ content.push(ChatContentBlock::ToolCallCandidate {value: Value::from(serde_json::Value::String(text)),});},}},_ => {- content.push(ContentBlock::Text {+ content.push(ChatContentBlock::Text {value: text,});},@@ -456,10 +462,12 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<index += 1;}- result.push(Message {- role: Role::Assistant {},+ result.push(ChatMessage {+ role: ChatRole::Assistant {},content,- metadata: HashMap::new(),+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },});},ExternalRole::Tool => {@@ -473,14 +481,16 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<}})?);- result.push(Message {- role: Role::Tool {},- content: vec![ContentBlock::ToolCallResult {+ result.push(ChatMessage {+ role: ChatRole::Tool {},+ content: vec![ChatContentBlock::ToolCallResult {identifier: None,name: Some(name.to_string()),value,}],- metadata: HashMap::new(),+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },});index += 1;},diff --git a/crates/hanashi/src/chat/harmony/bridging/mod.rs b/crates/hanashi/src/chat/harmony/bridging/mod.rsindex c264fbb4d..e35a8e806 100644--- a/crates/hanashi/src/chat/harmony/bridging/mod.rs+++ b/crates/hanashi/src/chat/harmony/bridging/mod.rs@@ -5,14 +5,17 @@ mod role;mod tool_namespace;pub use message::{bridge_messages_from_harmony, bridge_messages_to_harmony};-use shoji::types::encoding::{ContentBlockType, ReasoningEffort, Role};+use shoji::types::{+ basic::ReasoningEffort,+ session::chat::{ChatContentBlockType, ChatRole},+};#[derive(Debug, thiserror::Error)]#[non_exhaustive]pub enum Error {#[error("Role '{role}' is not supported")]UnsupportedRole {- role: Role,+ role: ChatRole,},#[error("Reasoning effort '{reasoning_effort}' is not supported")]UnsupportedReasoningEffort {@@ -24,8 +27,8 @@ pub enum Error {},#[error("Content block '{block_type}' is not supported for role '{role}'")]UnsupportedContentBlock {- block_type: ContentBlockType,- role: Role,+ block_type: ChatContentBlockType,+ role: ChatRole,},#[error("Multiple tool calls are not supported")]MultipleToolCalls,@@ -33,7 +36,7 @@ pub enum Error {MultipleContentBlocks,#[error("Content is required for role '{role}'")]ContentRequired {- role: Role,+ role: ChatRole,},#[error("Tool call result is missing a name")]MissingToolCallResultName,diff --git a/crates/hanashi/src/chat/harmony/bridging/reasoning_effort.rs b/crates/hanashi/src/chat/harmony/bridging/reasoning_effort.rsindex ef8187978..f12d5904d 100644--- a/crates/hanashi/src/chat/harmony/bridging/reasoning_effort.rs+++ b/crates/hanashi/src/chat/harmony/bridging/reasoning_effort.rs@@ -1,5 +1,5 @@use openai_harmony::chat::ReasoningEffort as ExternalReasoningEffort;-use shoji::types::encoding::ReasoningEffort;+use shoji::types::basic::ReasoningEffort;use crate::chat::harmony::bridging::{Error, FromHarmony, ToHarmony};diff --git a/crates/hanashi/src/chat/harmony/bridging/role.rs b/crates/hanashi/src/chat/harmony/bridging/role.rsindex 64b4fa908..67f940244 100644--- a/crates/hanashi/src/chat/harmony/bridging/role.rs+++ b/crates/hanashi/src/chat/harmony/bridging/role.rs@@ -1,19 +1,19 @@use openai_harmony::chat::Role as ExternalRole;-use shoji::types::encoding::Role;+use shoji::types::session::chat::ChatRole;use crate::chat::harmony::bridging::{Error, FromHarmony, ToHarmony};-impl ToHarmony for Role {+impl ToHarmony for ChatRole {type Output = ExternalRole;fn to_harmony(self) -> Result<Self::Output, Error> {match self {- Role::User {} => Ok(ExternalRole::User),- Role::Assistant {} => Ok(ExternalRole::Assistant),- Role::System {} => Ok(ExternalRole::System),- Role::Developer {} => Ok(ExternalRole::Developer),- Role::Tool {} => Ok(ExternalRole::Tool),- Role::Custom {+ ChatRole::User {} => Ok(ExternalRole::User),+ ChatRole::Assistant {} => Ok(ExternalRole::Assistant),+ ChatRole::System {} => Ok(ExternalRole::System),+ ChatRole::Developer {} => Ok(ExternalRole::Developer),+ ChatRole::Tool {} => Ok(ExternalRole::Tool),+ ChatRole::Custom {..} => Err(Error::UnsupportedRole {role: self.clone(),@@ -22,16 +22,16 @@ impl ToHarmony for Role {}}-impl FromHarmony for Role {+impl FromHarmony for ChatRole {type Input = ExternalRole;fn from_harmony(input: Self::Input) -> Self {match input {- ExternalRole::User => Role::User {},- ExternalRole::Assistant => Role::Assistant {},- ExternalRole::System => Role::System {},- ExternalRole::Developer => Role::Developer {},- ExternalRole::Tool => Role::Tool {},+ ExternalRole::User => ChatRole::User {},+ ExternalRole::Assistant => ChatRole::Assistant {},+ ExternalRole::System => ChatRole::System {},+ ExternalRole::Developer => ChatRole::Developer {},+ ExternalRole::Tool => ChatRole::Tool {},}}}diff --git a/crates/hanashi/src/chat/harmony/bridging/tool_namespace.rs b/crates/hanashi/src/chat/harmony/bridging/tool_namespace.rsindex 992fbdd70..ca5f55d02 100644--- a/crates/hanashi/src/chat/harmony/bridging/tool_namespace.rs+++ b/crates/hanashi/src/chat/harmony/bridging/tool_namespace.rs@@ -1,10 +1,7 @@use openai_harmony::chat::{ToolDescription as ExternalToolDescription, ToolNamespaceConfig as ExternalToolNamespaceConfig,};-use shoji::types::{- basic::Value,- encoding::{ToolDescription, ToolFunction, ToolNamespace},-};+use shoji::types::basic::{ToolDescription, ToolFunction, ToolNamespace, Value};use crate::chat::harmony::bridging::{Error, FromHarmony, ToHarmony};@@ -38,7 +35,7 @@ impl ToHarmony for ToolDescription {fn to_harmony(self) -> Result<Self::Output, Error> {match self {ToolDescription::Function {- function,+ tool_function: function,} => {let parameters = function.parameters.map(serde_json::Value::try_from).transpose().map_err(|error| {Error::SerializationFailed {@@ -57,11 +54,11 @@ impl FromHarmony for ToolDescription {fn from_harmony(input: Self::Input) -> Self {ToolDescription::Function {- function: ToolFunction {+ tool_function: ToolFunction {name: input.name,description: input.description,parameters: input.parameters.map(Value::from),- r#return: None,+ return_definition: None,},}}diff --git a/crates/hanashi/src/chat/harmony/config.rs b/crates/hanashi/src/chat/harmony/config.rsindex 3af85990f..c2e30dcd3 100644--- a/crates/hanashi/src/chat/harmony/config.rs+++ b/crates/hanashi/src/chat/harmony/config.rs@@ -1,5 +1,5 @@use serde::{Deserialize, Serialize};-use shoji::types::encoding::Capabilities;+use shoji::types::session::chat::ChatModelCapabilities;use crate::chat::harmony::EncodingName;@@ -10,9 +10,9 @@ pub struct Config {}impl Config {- pub fn capabilities(&self) -> Capabilities {+ pub fn capabilities(&self) -> ChatModelCapabilities {match self.encoding_name {- EncodingName::GptOss => Capabilities {+ EncodingName::GptOss => ChatModelCapabilities {supports_reasoning: true,supports_disable_reasoning: false,supports_tools: true,diff --git a/crates/hanashi/src/chat/harmony/mod.rs b/crates/hanashi/src/chat/harmony/mod.rsindex 760b56eeb..b71714533 100644--- a/crates/hanashi/src/chat/harmony/mod.rs+++ b/crates/hanashi/src/chat/harmony/mod.rs@@ -17,7 +17,7 @@ use openai_harmony::{};use shoji::types::{basic::{Token, TokenId},- encoding::Message,+ session::chat::ChatMessage,};use crate::{@@ -34,7 +34,7 @@ pub struct Encoding {impl EncodingTrait for Encoding {type Config = Config;type Context = Context;- type Input = Vec<Message>;+ type Input = Vec<ChatMessage>;type Output = Vec<TokenId>;type State = State;type Error = Error;diff --git a/crates/hanashi/src/chat/mod.rs b/crates/hanashi/src/chat/mod.rsindex 9bbb9e398..751624e13 100644--- a/crates/hanashi/src/chat/mod.rs+++ b/crates/hanashi/src/chat/mod.rs@@ -8,7 +8,7 @@ mod state;pub use config::Config;pub use context::{Context, TokenizerLocation};pub use error::Error;-use shoji::types::{basic::TokenId, encoding::Message};+use shoji::types::{basic::TokenId, session::chat::ChatMessage};pub use state::{State, SynchronizationError, SynchronizationResult};use crate::{@@ -39,7 +39,7 @@ pub enum Encoding {impl EncodingTrait for Encoding {type Config = Config;type Context = Context;- type Input = Vec<Message>;+ type Input = Vec<ChatMessage>;type Output = Vec<TokenId>;type State = State;type Error = Error;diff --git a/crates/hanashi/src/chat/state.rs b/crates/hanashi/src/chat/state.rsindex 837c88c00..a20b27927 100644--- a/crates/hanashi/src/chat/state.rs+++ b/crates/hanashi/src/chat/state.rs@@ -1,5 +1,5 @@use serde::{Deserialize, Serialize};-use shoji::types::{basic::Token, encoding::Message};+use shoji::types::{basic::Token, session::chat::ChatMessage};#[derive(Debug, thiserror::Error)]#[non_exhaustive]@@ -17,7 +17,7 @@ pub enum SynchronizationResult {#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]pub struct State {pub tokens: Vec<Token>,- pub messages: Vec<Message>,+ pub messages: Vec<ChatMessage>,}impl State {@@ -27,7 +27,7 @@ impl State {pub fn synchronize_messages(&mut self,- streamed_messages: &[Message],+ streamed_messages: &[ChatMessage],) -> Result<SynchronizationResult, SynchronizationError> {let last_message = self.messages.last().ok_or(SynchronizationError::Desynchronization)?;let last_matched_index = streamed_messagesdiff --git a/crates/hanashi/tests/helpers/mod.rs b/crates/hanashi/tests/helpers/mod.rsindex 4c90fca0e..1d46d95b3 100644--- a/crates/hanashi/tests/helpers/mod.rs+++ b/crates/hanashi/tests/helpers/mod.rs@@ -3,8 +3,9 @@use std::{collections::HashMap, path::PathBuf};use serde::Deserialize;-use shoji::types::encoding::{- ContentBlock, Message, ReasoningEffort, Role, ToolDescription, ToolNamespace, TranslationInput,+use shoji::types::{+ basic::{ReasoningEffort, ToolDescription, ToolNamespace, TranslationPayload},+ session::chat::{ChatContentBlock, ChatMessage, ChatMessageMetadata, ChatRole},};use tokenizers::Tokenizer;@@ -101,17 +102,17 @@ fn resolve_reasoning_effort(context: &HashMap<String, serde_json::Value>) -> Optfn build_system_message(raw_messages: &[serde_json::Value],reasoning_effort: Option<ReasoningEffort>,-) -> Option<Message> {+) -> Option<ChatMessage> {let system_raw = raw_messages.iter().find(|raw| raw["role"].as_str() == Some("system"));let mut content = Vec::new();if let Some(raw) = system_raw {- content.push(ContentBlock::Text {+ content.push(ChatContentBlock::Text {value: raw["content"].as_str().unwrap().to_string(),});}if let Some(effort) = reasoning_effort {- content.push(ContentBlock::ReasoningEffort {+ content.push(ChatContentBlock::ReasoningEffort {value: effort,});}@@ -119,34 +120,38 @@ fn build_system_message(return None;}- Some(Message {- role: Role::System {},+ Some(ChatMessage {+ role: ChatRole::System {},content,- metadata: HashMap::new(),+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },})}-fn build_developer_message(tools: &Option<Vec<serde_json::Value>>) -> Option<Message> {+fn build_developer_message(tools: &Option<Vec<serde_json::Value>>) -> Option<ChatMessage> {let tools = tools.as_ref()?;let tool_descriptions: Vec<ToolDescription> =tools.iter().filter_map(|tool| serde_json::from_value(tool.clone()).ok()).collect();- Some(Message {- role: Role::Developer {},- content: vec![ContentBlock::Tools {+ Some(ChatMessage {+ role: ChatRole::Developer {},+ content: vec![ChatContentBlock::Tools {namespaces: vec![ToolNamespace {name: "functions".to_string(),description: None,tools: tool_descriptions,}],}],- metadata: HashMap::new(),+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },})}-fn build_user_content(raw: &serde_json::Value) -> Vec<ContentBlock> {+fn build_user_content(raw: &serde_json::Value) -> Vec<ChatContentBlock> {if let Some(text) = raw["content"].as_str() {- return vec![ContentBlock::Text {+ return vec![ChatContentBlock::Text {value: text.to_string(),}];}@@ -156,15 +161,15 @@ fn build_user_content(raw: &serde_json::Value) -> Vec<ContentBlock> {.map(|item| {let content_type = item["type"].as_str().unwrap();match content_type {- "text" => ContentBlock::Translation {- input: TranslationInput::Text {+ "text" => ChatContentBlock::Translation {+ payload: TranslationPayload::Text {text: item["text"].as_str().unwrap().to_string(),},source_language_code: item["source_lang_code"].as_str().unwrap().to_string(),target_language_code: item["target_lang_code"].as_str().unwrap().to_string(),},- "image" => ContentBlock::Translation {- input: TranslationInput::Image {+ "image" => ChatContentBlock::Translation {+ payload: TranslationPayload::Image {url: item["url"].as_str().unwrap().to_string(),},source_language_code: item["source_lang_code"].as_str().unwrap().to_string(),@@ -180,19 +185,21 @@ fn build_user_content(raw: &serde_json::Value) -> Vec<ContentBlock> {panic!("User content must be a string or array");}-fn build_user_messages(raw_messages: &[serde_json::Value]) -> Vec<Message> {+fn build_user_messages(raw_messages: &[serde_json::Value]) -> Vec<ChatMessage> {raw_messages.iter().filter(|raw| raw["role"].as_str() == Some("user"))- .map(|raw| Message {- role: Role::User {},+ .map(|raw| ChatMessage {+ role: ChatRole::User {},content: build_user_content(raw),- metadata: HashMap::new(),+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },}).collect()}-pub fn build_messages(data: &ResponseTestData) -> Vec<Message> {+pub fn build_messages(data: &ResponseTestData) -> Vec<ChatMessage> {let raw_messages = &data.parameters.messages;let reasoning_effort = resolve_reasoning_effort(&data.parameters.context);diff --git a/crates/hanashi/tests/test_encoding.rs b/crates/hanashi/tests/test_encoding.rsindex dd63fb25d..13d7bcaa3 100644--- a/crates/hanashi/tests/test_encoding.rs+++ b/crates/hanashi/tests/test_encoding.rs@@ -14,7 +14,10 @@ use helpers::{build_messages, load_registry, load_response_test_data, load_tokenizer, normalize_pattern, response_path,tokenizer_directory,};-use shoji::types::encoding::{ContentBlock, Message, ReasoningEffort, Role};+use shoji::types::{+ basic::ReasoningEffort,+ session::chat::{ChatContentBlock, ChatMessage, ChatMessageMetadata, ChatRole},+};fn print_warning(message: &str) {println!("\x1b[33m{}\x1b[0m", message);@@ -26,7 +29,7 @@ fn run_encoding_test(tools_pattern: Option<&str>,ignore_prompt: bool,ignore_reasoning: bool,- messages_normalizer: Option<fn(String, Option<&str>, Vec<Message>) -> Vec<Message>>,+ messages_normalizer: Option<fn(String, Option<&str>, Vec<ChatMessage>) -> Vec<ChatMessage>>,) {let registry = load_registry();@@ -94,18 +97,18 @@ fn run_encoding_test(}let assistant_message = encoding.state().messages.last().unwrap();let has_reasoning =- assistant_message.content.iter().any(|block| matches!(block, ContentBlock::Reasoning { .. }));+ assistant_message.content.iter().any(|block| matches!(block, ChatContentBlock::Reasoning { .. }));let used_tool_calls = assistant_message.content.iter().flat_map(|block| match block {- ContentBlock::ToolCall {+ ChatContentBlock::ToolCall {value,} => Some(value.name.clone()),_ => None,}).collect::<Vec<_>>();- assert_eq!(assistant_message.role, Role::Assistant {});+ assert_eq!(assistant_message.role, ChatRole::Assistant {});if ignore_reasoning {if has_reasoning != data.expectations.reasoning {print_warning("Reasoning mismatch");@@ -151,36 +154,40 @@ fn test_encoding_gpt_oss() {.map(|matched| matched.as_str().to_string()).unwrap();- let original_system_message = messages.iter().find(|message| message.role == Role::System {}).cloned();+ let original_system_message = messages.iter().find(|message| message.role == ChatRole::System {}).cloned();let original_developer_message =- messages.iter().find(|message| message.role == Role::Developer {}).cloned();+ messages.iter().find(|message| message.role == ChatRole::Developer {}).cloned();let other_messages = messages.into_iter()- .filter(|message| message.role != Role::System {} && message.role != Role::Developer {})+ .filter(|message| message.role != ChatRole::System {} && message.role != ChatRole::Developer {}).collect::<Vec<_>>();- let system_message = Message {- role: Role::System {},+ let system_message = ChatMessage {+ role: ChatRole::System {},content: vec![- ContentBlock::ReasoningEffort {+ ChatContentBlock::ReasoningEffort {value: ReasoningEffort::Medium,},- ContentBlock::ConversationStartDate {+ ChatContentBlock::ConversationStartDate {value: conversation_date,},],- metadata: HashMap::new(),+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },};- let mut developer_message = Message {- role: Role::Developer {},+ let mut developer_message = ChatMessage {+ role: ChatRole::Developer {},content: vec![],- metadata: HashMap::new(),+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },};if let Some(original_developer_message) = original_developer_message {for block in original_developer_message.content {let new_block = block.clone();match block {- ContentBlock::Tools {+ ChatContentBlock::Tools {namespaces,} => {if namespaces.iter().any(|namespace| !namespace.tools.is_empty()) {@@ -194,10 +201,10 @@ fn test_encoding_gpt_oss() {if let Some(original_system_message) = original_system_message {for block in original_system_message.content {match block {- ContentBlock::Text {+ ChatContentBlock::Text {value,} => {- developer_message.content.push(ContentBlock::Text {+ developer_message.content.push(ChatContentBlock::Text {value: format!("{}{}",value,@@ -324,13 +331,13 @@ fn test_encoding_functiongemma() {false,false,Some(|_, _, messages| {- let mut result: Vec<Message> = Vec::new();+ let mut result: Vec<ChatMessage> = Vec::new();for mut message in messages {- if matches!(message.role, Role::System {}) {- message.role = Role::Developer {};+ if matches!(message.role, ChatRole::System {}) {+ message.role = ChatRole::Developer {};}if let Some(last) = result.last_mut() {- if matches!(last.role, Role::Developer {}) && matches!(message.role, Role::Developer {}) {+ if matches!(last.role, ChatRole::Developer {}) && matches!(message.role, ChatRole::Developer {}) {last.content.extend(message.content);continue;}diff --git a/crates/nagare/Cargo.toml b/crates/nagare/Cargo.tomlindex 42ed30bb2..76b8d0181 100644--- a/crates/nagare/Cargo.toml+++ b/crates/nagare/Cargo.toml@@ -7,7 +7,35 @@ license.workspace = trueauthors.workspace = truerepository.workspace = true+[lib]+crate-type = ["lib", "cdylib", "staticlib"]++[features]+default = []+bindings = [+ "bindings-uniffi",+ "bindings-napi",+ "bindings-pyo3",+ "bindings-wasm",+]+bindings-uniffi = ["shoji/bindings-uniffi", "dep:uniffi"]+bindings-napi = [+ "shoji/bindings-napi",+ "dep:napi",+ "dep:napi-derive",+ "dep:napi-build",+]+bindings-pyo3 = ["shoji/bindings-pyo3", "dep:pyo3"]+bindings-wasm = [+ "shoji/bindings-wasm",+ "dep:wasm-bindgen",+ "dep:serde-wasm-bindgen",+ "dep:wasm-bindgen-futures",+ "dep:tsify",+]+[dependencies]+bindings.workspace = trueshoji.workspace = truehanashi.workspace = trueserde.workspace = true@@ -19,3 +47,14 @@ futures.workspace = truetokio-util.workspace = truetokio.workspace = truetokio-stream.workspace = true+uniffi = { workspace = true, optional = true }+napi = { workspace = true, optional = true }+napi-derive = { workspace = true, optional = true }+pyo3 = { workspace = true, optional = true }+wasm-bindgen = { workspace = true, optional = true }+serde-wasm-bindgen = { workspace = true, optional = true }+wasm-bindgen-futures = { workspace = true, optional = true }+tsify = { workspace = true, optional = true }++[build-dependencies]+napi-build = { workspace = true, optional = true }diff --git a/crates/nagare/build.rs b/crates/nagare/build.rsnew file mode 100644index 000000000..6de3825da--- /dev/null+++ b/crates/nagare/build.rs@@ -0,0 +1,4 @@+fn main() {+ #[cfg(feature = "bindings-napi")]+ napi_build::setup();+}diff --git a/crates/nagare/src/chat/error.rs b/crates/nagare/src/chat/error.rsindex 9894084b4..39ce91287 100644--- a/crates/nagare/src/chat/error.rs+++ b/crates/nagare/src/chat/error.rs@@ -1,12 +1,17 @@-#[derive(Debug, thiserror::Error)]+use serde::{Deserialize, Serialize};++#[bindings::export(Error)]+#[derive(Debug, Clone, Serialize, Deserialize, thiserror::Error)]#[non_exhaustive]-pub enum Error {+pub enum ChatSessionError {#[error("Backend error: {message}")]Backend {message: String,},#[error("Unsupported model")]- UnsupportedModel,+ UnsupportedModel {},#[error("Unable to perform operation in current state")]- UnableToPerformOperationInCurrentState,+ UnableToPerformOperationInCurrentState {},+ #[error("No response")]+ NoResponse {},}diff --git a/crates/nagare/src/chat/message.rs b/crates/nagare/src/chat/message.rsindex 42fb2bdc1..5db934d70 100644--- a/crates/nagare/src/chat/message.rs+++ b/crates/nagare/src/chat/message.rs@@ -6,14 +6,11 @@ use shoji::{State,backend::chat_message::{Backend, Instance, Output},},- types::{- encoding::Message,- session::chat::{Config, StreamConfig},- },+ types::session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},};use tokio_util::sync::CancellationToken;-use super::Error;+use super::ChatSessionError;pub struct Session {instance: Box<dyn Instance>,@@ -23,13 +20,13 @@ pub struct Session {impl Session {pub async fn new(backend: &dyn Backend,- config: Config,+ config: ChatConfig,reference: String,- ) -> Result<Self, Error> {- let instance = backend.instance(reference, config).await.map_err(|error| Error::Backend {+ ) -> Result<Self, ChatSessionError> {+ let instance = backend.instance(reference, config).await.map_err(|error| ChatSessionError::Backend {message: error.to_string(),})?;- let state = instance.state().await.map_err(|error| Error::Backend {+ let state = instance.state().await.map_err(|error| ChatSessionError::Backend {message: error.to_string(),})?;Ok(Self {@@ -38,8 +35,8 @@ impl Session {})}- pub async fn reset(&mut self) -> Result<(), Error> {- self.state = self.instance.state().await.map_err(|error| Error::Backend {+ pub async fn reset(&mut self) -> Result<(), ChatSessionError> {+ self.state = self.instance.state().await.map_err(|error| ChatSessionError::Backend {message: error.to_string(),})?;Ok(())@@ -47,14 +44,14 @@ impl Session {pub fn stream<'a>(&'a mut self,- input: &'a Vec<Message>,- config: StreamConfig,+ input: &'a Vec<ChatMessage>,+ config: ChatReplyConfig,cancel_token: CancellationToken,- ) -> Pin<Box<dyn Stream<Item = Result<Output, Error>> + Send + 'a>> {+ ) -> Pin<Box<dyn Stream<Item = Result<Output, ChatSessionError>> + Send + 'a>> {self.instance.stream(input, self.state.as_mut(), config, cancel_token).map(|event| {- event.map_err(|error| Error::Backend {+ event.map_err(|error| ChatSessionError::Backend {message: error.to_string(),})})diff --git a/crates/nagare/src/chat/mod.rs b/crates/nagare/src/chat/mod.rsindex 6d7d3accd..ccc607a9d 100644--- a/crates/nagare/src/chat/mod.rs+++ b/crates/nagare/src/chat/mod.rs@@ -2,28 +2,81 @@ mod error;pub mod message;pub mod token;-use std::{pin::Pin, sync::Arc};+use std::{+ pin::Pin,+ sync::Arc,+ task::{Context, Poll},+};-pub use error::Error;-use futures::{Stream, StreamExt};+pub use error::ChatSessionError;+use futures::{Stream as FuturesStream, StreamExt};use indexmap::IndexMap;+use serde::{Deserialize, Serialize};use shoji::{traits::{Backend,backend::chat_message::{Output as BackendOutput, ToolCallState},},types::{- basic::{CancellationToken, Value},- encoding::{Message, ToolCall},- model::{Model, Specialization},- session::chat::{Config, Output, StreamConfig},+ basic::{CancellationToken, ToolCall, Value},+ model::{Model, ModelSpecialization},+ session::chat::{ChatConfig, ChatMessage, ChatReply, ChatReplyConfig},},};use tokio::sync::{Mutex, mpsc};-use tokio_stream::wrappers::UnboundedReceiverStream;-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]-pub enum State {+#[bindings::export(Enum)]+#[derive(Debug, Clone, Serialize, Deserialize)]+pub enum ChatSessionStreamChunk {+ Replies {+ replies: Vec<ChatReply>,+ },+ Error {+ error: ChatSessionError,+ },+}++#[bindings::export(Class)]+pub struct ChatSessionStream {+ receiver: Mutex<mpsc::UnboundedReceiver<Result<Vec<ChatReply>, ChatSessionError>>>,+ cancel_token: CancellationToken,+}++#[bindings::export(Implementation)]+impl ChatSessionStream {+ #[bindings::export(Method)]+ pub async fn next(&self) -> Option<ChatSessionStreamChunk> {+ match self.receiver.lock().await.recv().await {+ Some(Ok(replies)) => Some(ChatSessionStreamChunk::Replies {+ replies,+ }),+ Some(Err(error)) => Some(ChatSessionStreamChunk::Error {+ error,+ }),+ None => None,+ }+ }++ #[bindings::export(Getter)]+ pub fn cancel_token(&self) -> CancellationToken {+ self.cancel_token.clone()+ }+}++impl FuturesStream for ChatSessionStream {+ type Item = Result<Vec<ChatReply>, ChatSessionError>;++ fn poll_next(+ self: Pin<&mut Self>,+ context: &mut Context<'_>,+ ) -> Poll<Option<Self::Item>> {+ self.get_mut().receiver.get_mut().poll_recv(context)+ }+}++#[bindings::export(Enum)]+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum ChatSessionState {Idle,Generation,ToolCalling,@@ -35,21 +88,22 @@ enum Instance {Message(message::Session),}-pub struct Session {+#[bindings::export(Class)]+pub struct ChatSession {instance: Arc<Mutex<Instance>>,- state: Arc<Mutex<State>>,- messages: Arc<Mutex<Vec<Message>>>,+ state: Arc<Mutex<ChatSessionState>>,+ messages: Arc<Mutex<Vec<ChatMessage>>>,}-impl Session {+impl ChatSession {pub async fn new(backend: &dyn Backend,- config: Config,+ config: ChatConfig,model: Model,path: Option<String>,- ) -> Result<Self, Error> {- if !model.specializations.contains(&Specialization::Chat) {- return Err(Error::UnsupportedModel);+ ) -> Result<Self, ChatSessionError> {+ if !model.specializations.contains(&ModelSpecialization::Chat {}) {+ return Err(ChatSessionError::UnsupportedModel {});}let reference = path.unwrap_or_else(|| model.identifier.clone());@@ -58,33 +112,39 @@ impl Session {} else if let Some(message_backend) = backend.as_chat_via_message_capable() {Instance::Message(message::Session::new(message_backend, config, reference).await?)} else {- return Err(Error::UnsupportedModel);+ return Err(ChatSessionError::UnsupportedModel {});};Ok(Self {instance: Arc::new(Mutex::new(instance)),- state: Arc::new(Mutex::new(State::Idle)),+ state: Arc::new(Mutex::new(ChatSessionState::Idle)),messages: Arc::new(Mutex::new(Vec::new())),})}+}- pub async fn state(&self) -> State {+#[bindings::export(Implementation)]+impl ChatSession {+ #[bindings::export(Getter)]+ pub async fn state(&self) -> ChatSessionState {*self.state.lock().await}- pub async fn messages(&self) -> Vec<Message> {+ #[bindings::export(Getter)]+ pub async fn messages(&self) -> Vec<ChatMessage> {self.messages.lock().await.clone()}- pub async fn reset(&self) -> Result<(), Error> {+ #[bindings::export(Method)]+ pub async fn reset(&self) -> Result<(), ChatSessionError> {{let mut state = self.state.lock().await;match *state {- State::Idle | State::ToolCalling => {- *state = State::Resetting;+ ChatSessionState::Idle | ChatSessionState::ToolCalling => {+ *state = ChatSessionState::Resetting;},- State::Generation | State::Resetting => {- return Err(Error::UnableToPerformOperationInCurrentState);+ ChatSessionState::Generation | ChatSessionState::Resetting => {+ return Err(ChatSessionError::UnableToPerformOperationInCurrentState {});},}}@@ -98,18 +158,40 @@ impl Session {};self.messages.lock().await.clear();- *self.state.lock().await = State::Idle;+ *self.state.lock().await = ChatSessionState::Idle;result}- pub fn stream(+ #[bindings::export(Method)]+ pub async fn reply(&self,- input: Vec<Message>,- config: StreamConfig,- ) -> (Pin<Box<dyn Stream<Item = Result<Vec<Output>, Error>> + Send>>, CancellationToken) {+ input: Vec<ChatMessage>,+ config: ChatReplyConfig,+ ) -> Result<Vec<ChatReply>, ChatSessionError> {+ let stream = self.reply_with_stream(input, config);+ let mut outputs: Option<Vec<ChatReply>> = None;+ while let Some(progress) = stream.next().await {+ match progress {+ ChatSessionStreamChunk::Replies {+ replies,+ } => outputs = Some(replies.clone()),+ ChatSessionStreamChunk::Error {+ error,+ } => return Err(error),+ }+ }+ outputs.ok_or(ChatSessionError::NoResponse {})+ }++ #[bindings::export(Method)]+ pub fn reply_with_stream(+ &self,+ input: Vec<ChatMessage>,+ config: ChatReplyConfig,+ ) -> ChatSessionStream {let cancel_token_to_return = CancellationToken::new();- let (sender, receiver) = mpsc::unbounded_channel::<Result<Vec<Output>, Error>>();+ let (sender, receiver) = mpsc::unbounded_channel::<Result<Vec<ChatReply>, ChatSessionError>>();let instance = self.instance.clone();let state = self.state.clone();@@ -120,11 +202,11 @@ impl Session {{let mut state = state.lock().await;match *state {- State::Idle => {- *state = State::Generation;+ ChatSessionState::Idle => {+ *state = ChatSessionState::Generation;},- State::Generation | State::Resetting | State::ToolCalling => {- let _ = sender.send(Err(Error::UnableToPerformOperationInCurrentState));+ ChatSessionState::Generation | ChatSessionState::Resetting | ChatSessionState::ToolCalling => {+ let _ = sender.send(Err(ChatSessionError::UnableToPerformOperationInCurrentState {}));return;},}@@ -137,7 +219,7 @@ impl Session {messages.clone()};- let mut outputs: IndexMap<u32, Output> = IndexMap::new();+ let mut outputs: IndexMap<u32, ChatReply> = IndexMap::new();let mut instance = instance.lock().await;let mut stream = match &mut *instance {@@ -150,7 +232,7 @@ impl Session {match partial_output {Ok(backend_output) => {let message = build_message(&backend_output);- let output = Output {+ let output = ChatReply {message: message.clone(),stats: backend_output.stats.clone(),finish_reason: backend_output.finish_reason.clone(),@@ -182,16 +264,19 @@ impl Session {{let mut state = state.lock().await;- *state = State::Idle;+ *state = ChatSessionState::Idle;}});- (Box::pin(UnboundedReceiverStream::new(receiver)), cancel_token_to_return)+ ChatSessionStream {+ receiver: Mutex::new(receiver),+ cancel_token: cancel_token_to_return,+ }}}-fn build_message(output: &BackendOutput) -> Message {- let mut message = Message::assistant();+fn build_message(output: &BackendOutput) -> ChatMessage {+ let mut message = ChatMessage::assistant();if let Some(reasoning) = &output.reasoning {message = message.with_reasoning(reasoning.clone());}diff --git a/crates/nagare/src/chat/token.rs b/crates/nagare/src/chat/token.rsindex a5e26be15..5cd7d2bde 100644--- a/crates/nagare/src/chat/token.rs+++ b/crates/nagare/src/chat/token.rs@@ -9,14 +9,11 @@ use shoji::{chat_token::{Backend, Instance},},},- types::{- encoding::Message,- session::chat::{Config, StreamConfig},- },+ types::session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},};use tokio_util::sync::CancellationToken;-use super::Error;+use super::ChatSessionError;pub struct Session {_instance: Box<dyn Instance>,@@ -26,13 +23,13 @@ pub struct Session {impl Session {pub async fn new(backend: &dyn Backend,- config: Config,+ config: ChatConfig,reference: String,- ) -> Result<Self, Error> {- let instance = backend.instance(reference, config).await.map_err(|error| Error::Backend {+ ) -> Result<Self, ChatSessionError> {+ let instance = backend.instance(reference, config).await.map_err(|error| ChatSessionError::Backend {message: error.to_string(),})?;- let state = instance.state().await.map_err(|error| Error::Backend {+ let state = instance.state().await.map_err(|error| ChatSessionError::Backend {message: error.to_string(),})?;Ok(Self {@@ -41,20 +38,20 @@ impl Session {})}- pub async fn reset(&mut self) -> Result<(), Error> {- Err(Error::Backend {+ pub async fn reset(&mut self) -> Result<(), ChatSessionError> {+ Err(ChatSessionError::Backend {message: "token chat session reset not implemented".to_string(),})}pub fn stream<'a>(&'a mut self,- _input: &'a Vec<Message>,- _config: StreamConfig,+ _input: &'a Vec<ChatMessage>,+ _config: ChatReplyConfig,_cancel_token: CancellationToken,- ) -> Pin<Box<dyn Stream<Item = Result<Output, Error>> + Send + 'a>> {+ ) -> Pin<Box<dyn Stream<Item = Result<Output, ChatSessionError>> + Send + 'a>> {Box::pin(stream::once(async {- Err(Error::Backend {+ Err(ChatSessionError::Backend {message: "Token chat session stream not implemented".to_string(),})}))diff --git a/crates/nagare/src/classification/error.rs b/crates/nagare/src/classification/error.rsnew file mode 100644index 000000000..7f916bacb--- /dev/null+++ b/crates/nagare/src/classification/error.rs@@ -0,0 +1,15 @@+#[bindings::export(Error)]+#[derive(Debug, Clone, thiserror::Error)]+#[non_exhaustive]+pub enum ClassificationSessionError {+ #[error("Backend error: {message}")]+ Backend {+ message: String,+ },+ #[error("Unsupported model")]+ UnsupportedModel {},+ #[error("Unable to perform operation in current state")]+ UnableToPerformOperationInCurrentState {},+ #[error("No response")]+ NoResponse {},+}diff --git a/crates/nagare/src/classification/mod.rs b/crates/nagare/src/classification/mod.rsnew file mode 100644index 000000000..8c98a50a0--- /dev/null+++ b/crates/nagare/src/classification/mod.rs@@ -0,0 +1,126 @@+mod error;++use std::sync::Arc;++pub use error::ClassificationSessionError;+use futures::StreamExt;+use serde::{Deserialize, Serialize};+use shoji::{+ traits::{Backend, State as StateTrait, backend::classification::Instance},+ types::{+ basic::CancellationToken,+ model::{Model, ModelSpecialization},+ session::classification::{ClassificationMessage, ClassificationOutput},+ },+};+use tokio::sync::{Mutex, mpsc};++#[bindings::export(Enum)]+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum ClassificationSessionState {+ Idle,+ Classifying,+}++struct InstanceHolder {+ instance: Box<dyn Instance>,+ state: Box<dyn StateTrait>,+}++#[bindings::export(Class)]+pub struct ClassificationSession {+ holder: Arc<Mutex<InstanceHolder>>,+ state: Arc<Mutex<ClassificationSessionState>>,+}++impl ClassificationSession {+ pub async fn new(+ backend: &dyn Backend,+ model: Model,+ path: Option<String>,+ ) -> Result<Self, ClassificationSessionError> {+ if !model.specializations.contains(&ModelSpecialization::Classification {}) {+ return Err(ClassificationSessionError::UnsupportedModel {});+ }+ let reference = path.unwrap_or_else(|| model.identifier.clone());+ let classification_backend =+ backend.as_classification_capable().ok_or(ClassificationSessionError::UnsupportedModel {})?;+ let instance = classification_backend.instance(reference, ()).await.map_err(|error| {+ ClassificationSessionError::Backend {+ message: error.to_string(),+ }+ })?;+ let instance_state = instance.state().await.map_err(|error| ClassificationSessionError::Backend {+ message: error.to_string(),+ })?;+ Ok(Self {+ holder: Arc::new(Mutex::new(InstanceHolder {+ instance,+ state: instance_state,+ })),+ state: Arc::new(Mutex::new(ClassificationSessionState::Idle)),+ })+ }+}++#[bindings::export(Implementation)]+impl ClassificationSession {+ #[bindings::export(Getter)]+ pub async fn state(&self) -> ClassificationSessionState {+ *self.state.lock().await+ }++ #[bindings::export(Method)]+ pub async fn classify(+ &self,+ input: Vec<ClassificationMessage>,+ ) -> Result<ClassificationOutput, ClassificationSessionError> {+ let cancel_token_to_return = CancellationToken::new();+ let (sender, mut receiver) =+ mpsc::unbounded_channel::<Result<ClassificationOutput, ClassificationSessionError>>();++ let holder = self.holder.clone();+ let state = self.state.clone();+ let cancel_token = cancel_token_to_return.inner().clone();++ tokio::spawn(async move {+ {+ let mut state = state.lock().await;+ match *state {+ ClassificationSessionState::Idle => {+ *state = ClassificationSessionState::Classifying;+ },+ ClassificationSessionState::Classifying => {+ let _ = sender.send(Err(ClassificationSessionError::UnableToPerformOperationInCurrentState {}));+ return;+ },+ }+ }++ let result = {+ let mut holder = holder.lock().await;+ let InstanceHolder {+ instance,+ state: backend_state,+ } = &mut *holder;++ let mut stream = instance.stream(&input, backend_state.as_mut(), (), cancel_token);+ let output = stream.next().await;+ drop(stream);++ match output {+ Some(Ok(output)) => Ok(output),+ Some(Err(error)) => Err(ClassificationSessionError::Backend {+ message: error.to_string(),+ }),+ None => Err(ClassificationSessionError::NoResponse {}),+ }+ };+ let _ = sender.send(result);++ *state.lock().await = ClassificationSessionState::Idle;+ });++ receiver.recv().await.unwrap_or(Err(ClassificationSessionError::NoResponse {}))+ }+}diff --git a/crates/nagare/src/lib.rs b/crates/nagare/src/lib.rsindex 38dfdaeba..9d800aed4 100644--- a/crates/nagare/src/lib.rs+++ b/crates/nagare/src/lib.rs@@ -1,2 +1,9 @@+#[cfg(feature = "bindings-uniffi")]+shoji::uniffi_reexport_scaffolding!();+#[cfg(feature = "bindings-uniffi")]+uniffi::setup_scaffolding!();+pub mod api;pub mod chat;+pub mod classification;+pub mod text_to_speech;diff --git a/crates/nagare/src/text_to_speech/error.rs b/crates/nagare/src/text_to_speech/error.rsnew file mode 100644index 000000000..69565f364--- /dev/null+++ b/crates/nagare/src/text_to_speech/error.rs@@ -0,0 +1,17 @@+use serde::{Deserialize, Serialize};++#[bindings::export(Error)]+#[derive(Debug, Clone, Serialize, Deserialize, thiserror::Error)]+#[non_exhaustive]+pub enum TextToSpeechSessionError {+ #[error("Backend error: {message}")]+ Backend {+ message: String,+ },+ #[error("Unsupported model")]+ UnsupportedModel {},+ #[error("Unable to perform operation in current state")]+ UnableToPerformOperationInCurrentState {},+ #[error("No response")]+ NoResponse {},+}diff --git a/crates/nagare/src/text_to_speech/mod.rs b/crates/nagare/src/text_to_speech/mod.rsnew file mode 100644index 000000000..e5ab1f35f--- /dev/null+++ b/crates/nagare/src/text_to_speech/mod.rs@@ -0,0 +1,201 @@+mod error;++use std::{+ pin::Pin,+ sync::Arc,+ task::{Context, Poll},+};++pub use error::TextToSpeechSessionError;+use futures::{Stream as FuturesStream, StreamExt};+use serde::{Deserialize, Serialize};+use shoji::{+ traits::{Backend, State as StateTrait, backend::text_to_speech::Instance},+ types::{+ basic::{CancellationToken, PcmBatch},+ model::{Model, ModelSpecialization},+ },+};+use tokio::sync::{Mutex, mpsc};++#[bindings::export(Enum)]+#[derive(Debug, Clone, Serialize, Deserialize)]+pub enum TextToSpeechSessionStreamChunk {+ PcmBatch {+ batch: PcmBatch,+ },+ Error {+ error: TextToSpeechSessionError,+ },+}++#[bindings::export(Class)]+pub struct TextToSpeechSessionStream {+ receiver: Mutex<mpsc::UnboundedReceiver<Result<PcmBatch, TextToSpeechSessionError>>>,+ cancel_token: CancellationToken,+}++#[bindings::export(Implementation)]+impl TextToSpeechSessionStream {+ #[bindings::export(Method)]+ pub async fn next(&self) -> Option<TextToSpeechSessionStreamChunk> {+ match self.receiver.lock().await.recv().await {+ Some(Ok(batch)) => Some(TextToSpeechSessionStreamChunk::PcmBatch {+ batch,+ }),+ Some(Err(error)) => Some(TextToSpeechSessionStreamChunk::Error {+ error,+ }),+ None => None,+ }+ }++ #[bindings::export(Getter)]+ pub fn cancel_token(&self) -> CancellationToken {+ self.cancel_token.clone()+ }+}++impl FuturesStream for TextToSpeechSessionStream {+ type Item = Result<PcmBatch, TextToSpeechSessionError>;++ fn poll_next(+ self: Pin<&mut Self>,+ context: &mut Context<'_>,+ ) -> Poll<Option<Self::Item>> {+ self.get_mut().receiver.get_mut().poll_recv(context)+ }+}++#[bindings::export(Enum)]+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum TextToSpeechSessionState {+ Idle,+ Synthesizing,+}++struct InstanceHolder {+ instance: Box<dyn Instance>,+ state: Box<dyn StateTrait>,+}++#[bindings::export(Class)]+pub struct TextToSpeechSession {+ holder: Arc<Mutex<InstanceHolder>>,+ state: Arc<Mutex<TextToSpeechSessionState>>,+}++impl TextToSpeechSession {+ pub async fn new(+ backend: &dyn Backend,+ model: Model,+ path: Option<String>,+ ) -> Result<Self, TextToSpeechSessionError> {+ if !model.specializations.contains(&ModelSpecialization::TextToSpeech {}) {+ return Err(TextToSpeechSessionError::UnsupportedModel {});+ }+ let reference = path.unwrap_or_else(|| model.identifier.clone());+ let text_to_speech_backend =+ backend.as_text_to_speech_capable().ok_or(TextToSpeechSessionError::UnsupportedModel {})?;+ let instance = text_to_speech_backend.instance(reference, ()).await.map_err(|error| {+ TextToSpeechSessionError::Backend {+ message: error.to_string(),+ }+ })?;+ let instance_state = instance.state().await.map_err(|error| TextToSpeechSessionError::Backend {+ message: error.to_string(),+ })?;+ Ok(Self {+ holder: Arc::new(Mutex::new(InstanceHolder {+ instance,+ state: instance_state,+ })),+ state: Arc::new(Mutex::new(TextToSpeechSessionState::Idle)),+ })+ }+}++#[bindings::export(Implementation)]+impl TextToSpeechSession {+ #[bindings::export(Getter)]+ pub async fn state(&self) -> TextToSpeechSessionState {+ *self.state.lock().await+ }++ #[bindings::export(Method)]+ pub async fn synthesize(+ &self,+ input: String,+ ) -> Result<PcmBatch, TextToSpeechSessionError> {+ let stream = self.synthesize_stream(input);+ let mut batches: Vec<PcmBatch> = Vec::new();+ while let Some(event) = stream.next().await {+ match event {+ TextToSpeechSessionStreamChunk::PcmBatch {+ batch,+ } => batches.push(batch.clone()),+ TextToSpeechSessionStreamChunk::Error {+ error,+ } => return Err(error),+ }+ }+ if let Some(batch) = batches.last() {+ return Ok(batch.clone());+ }+ Err(TextToSpeechSessionError::NoResponse {})+ }+}++impl TextToSpeechSession {+ fn synthesize_stream(+ &self,+ input: String,+ ) -> TextToSpeechSessionStream {+ let cancel_token_to_return = CancellationToken::new();+ let (sender, receiver) = mpsc::unbounded_channel::<Result<PcmBatch, TextToSpeechSessionError>>();++ let holder = self.holder.clone();+ let state = self.state.clone();+ let cancel_token = cancel_token_to_return.inner().clone();++ tokio::spawn(async move {+ {+ let mut state = state.lock().await;+ match *state {+ TextToSpeechSessionState::Idle => {+ *state = TextToSpeechSessionState::Synthesizing;+ },+ TextToSpeechSessionState::Synthesizing => {+ let _ = sender.send(Err(TextToSpeechSessionError::UnableToPerformOperationInCurrentState {}));+ return;+ },+ }+ }++ {+ let mut holder = holder.lock().await;+ let InstanceHolder {+ instance,+ state: backend_state,+ } = &mut *holder;++ let mut stream = instance.stream(&input, backend_state.as_mut(), (), cancel_token);+ while let Some(event) = stream.next().await {+ let item = event.map_err(|error| TextToSpeechSessionError::Backend {+ message: error.to_string(),+ });+ if sender.send(item).is_err() {+ break;+ }+ }+ }++ *state.lock().await = TextToSpeechSessionState::Idle;+ });++ TextToSpeechSessionStream {+ receiver: Mutex::new(receiver),+ cancel_token: cancel_token_to_return,+ }+ }+}diff --git a/crates/shoji/Cargo.toml b/crates/shoji/Cargo.tomlindex 85b9b5a8f..02f2de291 100644--- a/crates/shoji/Cargo.toml+++ b/crates/shoji/Cargo.toml@@ -36,6 +36,7 @@ thiserror.workspace = trueindexmap.workspace = truefutures.workspace = truetokio-util.workspace = true+hound.workspace = trueuniffi = { workspace = true, optional = true }napi = { workspace = true, optional = true }napi-derive = { workspace = true, optional = true }diff --git a/crates/shoji/src/traits/backend/chat_message.rs b/crates/shoji/src/traits/backend/chat_message.rsindex a0e599d5e..78a5896a7 100644--- a/crates/shoji/src/traits/backend/chat_message.rs+++ b/crates/shoji/src/traits/backend/chat_message.rs@@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize};use crate::{traits::backend::{Error, Instance as InstanceTrait},types::{- encoding::{Message, ToolCall},- session::chat::{Config, FinishReason, Stats, StreamConfig},+ basic::ToolCall,+ session::chat::{ChatConfig, ChatMessage, ChatReplyConfig, ChatReplyFinishReason, ChatReplyStats},},};@@ -22,27 +22,27 @@ pub struct Output {pub reasoning: Option<String>,pub text: Option<String>,pub tool_calls: Vec<ToolCallState>,- pub finish_reason: Option<FinishReason>,- pub stats: Stats,+ pub finish_reason: Option<ChatReplyFinishReason>,+ pub stats: ChatReplyStats,}-pub type StreamInput = Vec<Message>;+pub type StreamInput = Vec<ChatMessage>;pub type StreamOutput = Output;pub trait Backend: Send + Sync {fn instance(&self,reference: String,- config: Config,+ config: ChatConfig,) -> Pin<Box<dyn Future<Output = Result<Box<dyn Instance>, Error>> + Send + '_>>;}pub trait Instance:- InstanceTrait<StreamConfig = StreamConfig, StreamInput = StreamInput, StreamOutput = StreamOutput>+ InstanceTrait<StreamConfig = ChatReplyConfig, StreamInput = StreamInput, StreamOutput = StreamOutput>{}impl<T> Instance for T where- T: InstanceTrait<StreamConfig = StreamConfig, StreamInput = StreamInput, StreamOutput = StreamOutput>+ T: InstanceTrait<StreamConfig = ChatReplyConfig, StreamInput = StreamInput, StreamOutput = StreamOutput>{}diff --git a/crates/shoji/src/traits/backend/chat_token.rs b/crates/shoji/src/traits/backend/chat_token.rsindex 8b09279d3..932e47c8a 100644--- a/crates/shoji/src/traits/backend/chat_token.rs+++ b/crates/shoji/src/traits/backend/chat_token.rs@@ -2,7 +2,7 @@ use std::pin::Pin;use crate::{traits::backend::{Error, Instance as InstanceTrait},- types::session::chat::{Config, StreamConfig},+ types::session::chat::{ChatConfig, ChatReplyConfig},};pub type StreamInput = Vec<u64>;@@ -12,16 +12,16 @@ pub trait Backend: Send + Sync {fn instance(&self,reference: String,- config: Config,+ config: ChatConfig,) -> Pin<Box<dyn Future<Output = Result<Box<dyn Instance>, Error>> + Send + '_>>;}pub trait Instance:- InstanceTrait<StreamConfig = StreamConfig, StreamInput = StreamInput, StreamOutput = StreamOutput>+ InstanceTrait<StreamConfig = ChatReplyConfig, StreamInput = StreamInput, StreamOutput = StreamOutput>{}impl<T> Instance for T where- T: InstanceTrait<StreamConfig = StreamConfig, StreamInput = StreamInput, StreamOutput = StreamOutput>+ T: InstanceTrait<StreamConfig = ChatReplyConfig, StreamInput = StreamInput, StreamOutput = StreamOutput>{}diff --git a/crates/shoji/src/traits/backend/classification.rs b/crates/shoji/src/traits/backend/classification.rsindex 7762f3e15..7d238e3a2 100644--- a/crates/shoji/src/traits/backend/classification.rs+++ b/crates/shoji/src/traits/backend/classification.rs@@ -2,13 +2,13 @@ use std::pin::Pin;use crate::{traits::backend::{Error, Instance as InstanceTrait},- types::{encoding::Message, session::classification::Output},+ types::session::classification::{ClassificationMessage, ClassificationOutput},};pub type Config = ();pub type StreamConfig = ();-pub type StreamInput = Vec<Message>;-pub type StreamOutput = Output;+pub type StreamInput = Vec<ClassificationMessage>;+pub type StreamOutput = ClassificationOutput;pub trait Backend: Send + Sync {fn instance(diff --git a/crates/shoji/src/traits/backend/text_to_speech.rs b/crates/shoji/src/traits/backend/text_to_speech.rsindex d79213df4..b1dd9fdc2 100644--- a/crates/shoji/src/traits/backend/text_to_speech.rs+++ b/crates/shoji/src/traits/backend/text_to_speech.rs@@ -2,12 +2,12 @@ use std::pin::Pin;use crate::{traits::backend::{Error, Instance as InstanceTrait},- types::{encoding::Message, session::text_to_speech::PcmBatch},+ types::basic::PcmBatch,};pub type Config = ();pub type StreamConfig = ();-pub type StreamInput = Vec<Message>;+pub type StreamInput = String;pub type StreamOutput = PcmBatch;pub trait Backend: Send + Sync {diff --git a/crates/shoji/src/traits/registry.rs b/crates/shoji/src/traits/registry.rsindex 57a3bbe44..4a2c64064 100644--- a/crates/shoji/src/traits/registry.rs+++ b/crates/shoji/src/traits/registry.rs@@ -16,7 +16,7 @@ pub trait Registry: Send + Sync {let identifier = identifier.to_string();Box::pin(async move {let models = self.models().await?;- let model = models.iter().find(|model| model.identifier() == identifier).cloned();+ let model = models.iter().find(|model| model.identifier == identifier).cloned();Ok(model)})}diff --git a/crates/shoji/src/types/basic/cancellation_token.rs b/crates/shoji/src/types/basic/cancellation_token.rsindex 1f2b24688..b6452a7d3 100644--- a/crates/shoji/src/types/basic/cancellation_token.rs+++ b/crates/shoji/src/types/basic/cancellation_token.rs@@ -1,5 +1,6 @@use tokio_util::sync::CancellationToken as TokioCancellationToken;+#[bindings::export(Class)]#[derive(Debug, Clone, Default)]pub struct CancellationToken {inner: TokioCancellationToken,@@ -11,20 +12,24 @@ impl CancellationToken {inner: TokioCancellationToken::new(),}}+}++#[bindings::export(Implementation)]+impl CancellationToken {+ #[bindings::export(Factory)]+ pub fn create() -> Self {+ Self::new()+ }+ #[bindings::export(Method)]pub fn cancel(&self) {self.inner.cancel();}+ #[bindings::export(Getter)]pub fn is_cancelled(&self) -> bool {self.inner.is_cancelled()}-- pub fn child(&self) -> Self {- Self {- inner: self.inner.child_token(),- }- }}impl CancellationToken {diff --git a/crates/shoji/src/types/session/chat/context_length.rs b/crates/shoji/src/types/basic/context_length.rssimilarity index 85%rename from crates/shoji/src/types/session/chat/context_length.rsrename to crates/shoji/src/types/basic/context_length.rsindex b3b75e617..2c7bde0bd 100644--- a/crates/shoji/src/types/session/chat/context_length.rs+++ b/crates/shoji/src/types/basic/context_length.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum, name = "ChatContextLength")]+#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum ContextLength {Default {},diff --git a/crates/shoji/src/types/session/chat/feature.rs b/crates/shoji/src/types/basic/feature.rssimilarity index 78%rename from crates/shoji/src/types/session/chat/feature.rsrename to crates/shoji/src/types/basic/feature.rsindex bd330d6fa..07c179a23 100644--- a/crates/shoji/src/types/session/chat/feature.rs+++ b/crates/shoji/src/types/basic/feature.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Struct, name = "ChatFeature")]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub struct Feature {pub name: String,diff --git a/crates/shoji/src/types/model/file.rs b/crates/shoji/src/types/basic/file.rssimilarity index 56%rename from crates/shoji/src/types/model/file.rsrename to crates/shoji/src/types/basic/file.rsindex fd71a3c3a..4b641ee51 100644--- a/crates/shoji/src/types/model/file.rs+++ b/crates/shoji/src/types/basic/file.rs@@ -1,8 +1,8 @@use serde::{Deserialize, Serialize};-use crate::types::model::{Hash, HashMethod};+use crate::types::basic::{Hash, HashMethod};-#[bindings::export(Struct)]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct File {@@ -12,8 +12,15 @@ pub struct File {pub hashes: Vec<Hash>,}+#[bindings::export(Implementation)]impl File {+ #[bindings::export(Getter)]pub fn crc32c(&self) -> Option<String> {self.hashes.iter().find(|hash| hash.method == HashMethod::CRC32C).map(|hash| hash.value.clone())}++ #[bindings::export(Getter)]+ pub fn md5(&self) -> Option<String> {+ self.hashes.iter().find(|hash| hash.method == HashMethod::MD5).map(|hash| hash.value.clone())+ }}diff --git a/crates/shoji/src/types/session/chat/grammar.rs b/crates/shoji/src/types/basic/grammar.rssimilarity index 83%rename from crates/shoji/src/types/session/chat/grammar.rsrename to crates/shoji/src/types/basic/grammar.rsindex 7f7b060b3..fdf3d6aa0 100644--- a/crates/shoji/src/types/session/chat/grammar.rs+++ b/crates/shoji/src/types/basic/grammar.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum, name = "ChatGrammar")]+#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum Grammar {JsonAny {},diff --git a/crates/shoji/src/types/model/hash.rs b/crates/shoji/src/types/basic/hash.rssimilarity index 92%rename from crates/shoji/src/types/model/hash.rsrename to crates/shoji/src/types/basic/hash.rsindex c1b383df1..a4426bd72 100644--- a/crates/shoji/src/types/model/hash.rs+++ b/crates/shoji/src/types/basic/hash.rs@@ -10,7 +10,7 @@ pub enum HashMethod {MD5,}-#[bindings::export(Struct)]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Hash {diff --git a/crates/shoji/src/types/model/image.rs b/crates/shoji/src/types/basic/image.rssimilarity index 95%rename from crates/shoji/src/types/model/image.rsrename to crates/shoji/src/types/basic/image.rsindex ffaedb310..415385910 100644--- a/crates/shoji/src/types/model/image.rs+++ b/crates/shoji/src/types/basic/image.rs@@ -17,7 +17,7 @@ pub enum ImageTheme {Dark,}-#[bindings::export(Struct)]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Image {diff --git a/crates/shoji/src/types/basic/metadata.rs b/crates/shoji/src/types/basic/metadata.rsnew file mode 100644index 000000000..9e32e63b4--- /dev/null+++ b/crates/shoji/src/types/basic/metadata.rs@@ -0,0 +1,27 @@+use serde::{Deserialize, Serialize};++use crate::types::basic::Image;++#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct Metadata {+ #[serde(rename = "id")]+ pub identifier: String,+ pub name: String,+ pub description: Option<String>,+ pub icons: Vec<Image>,+}++#[bindings::export(Implementation)]+impl Metadata {+ #[bindings::export(Factory)]+ pub fn external(name: String) -> Self {+ Self {+ identifier: "external".to_string(),+ name,+ description: None,+ icons: vec![],+ }+ }+}diff --git a/crates/shoji/src/types/basic/mod.rs b/crates/shoji/src/types/basic/mod.rsindex 738faef4e..90245aa96 100644--- a/crates/shoji/src/types/basic/mod.rs+++ b/crates/shoji/src/types/basic/mod.rs@@ -1,13 +1,43 @@mod cancellation_token;+mod context_length;+mod feature;+mod file;+mod grammar;+mod hash;+mod image;+mod metadata;+mod pcm_batch;+mod reasoning_effort;+mod repository;mod sampling_method;mod sampling_policy;mod sampling_seed;mod token;+mod tool_call;+mod tool_description;+mod tool_function;+mod tool_namespace;+mod translation_payload;mod value;pub use cancellation_token::CancellationToken;+pub use context_length::ContextLength;+pub use feature::Feature;+pub use file::File;+pub use grammar::Grammar;+pub use hash::{Hash, HashMethod};+pub use image::{Image, ImageFormat, ImageTheme};+pub use metadata::Metadata;+pub use pcm_batch::PcmBatch;+pub use reasoning_effort::ReasoningEffort;+pub use repository::Repository;pub use sampling_method::SamplingMethod;pub use sampling_policy::SamplingPolicy;pub use sampling_seed::SamplingSeed;pub use token::{Token, TokenId, TokenValue};+pub use tool_call::ToolCall;+pub use tool_description::ToolDescription;+pub use tool_function::ToolFunction;+pub use tool_namespace::ToolNamespace;+pub use translation_payload::TranslationPayload;pub use value::Value;diff --git a/crates/shoji/src/types/basic/pcm_batch.rs b/crates/shoji/src/types/basic/pcm_batch.rsnew file mode 100644index 000000000..99e61da79--- /dev/null+++ b/crates/shoji/src/types/basic/pcm_batch.rs@@ -0,0 +1,79 @@+use hound::{SampleFormat, WavSpec, WavWriter};+use serde::{Deserialize, Serialize};++#[bindings::export(Error)]+#[derive(Debug, Clone, thiserror::Error)]+#[non_exhaustive]+pub enum PcmBatchError {+ #[error("Unable to save as wav: {message}")]+ UnableToSaveAsWav {+ message: String,+ },+}++#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct PcmBatch {+ pub samples: Vec<f64>,+ pub sample_rate: u32,+ pub channels: u32,+ pub lengths: Vec<u32>,+}++impl PcmBatch {+ pub fn into_parts(self) -> (Box<[f64]>, u32, u32, Box<[u32]>) {+ (self.samples.into_boxed_slice(), self.sample_rate, self.channels, self.lengths.into_boxed_slice())+ }+}++#[bindings::export(Implementation)]+impl PcmBatch {+ #[bindings::export(Getter)]+ pub fn batch_size(&self) -> u32 {+ self.lengths.len() as u32+ }++ #[bindings::export(Getter)]+ pub fn total_frames(&self) -> u32 {+ self.lengths.iter().sum::<_>()+ }+}++#[bindings::export(Implementation)]+impl PcmBatch {+ #[bindings::export(Method)]+ pub fn save_as_wav(+ &self,+ path: String,+ ) -> Result<(), PcmBatchError> {+ let path = std::path::Path::new(&path);+ if path.exists() {+ std::fs::remove_file(path).map_err(|error| PcmBatchError::UnableToSaveAsWav {+ message: error.to_string(),+ })?;+ }++ let spec = WavSpec {+ channels: self.channels as u16,+ sample_rate: self.sample_rate,+ bits_per_sample: 16,+ sample_format: SampleFormat::Int,+ };++ let mut writer = WavWriter::create(path, spec).map_err(|error| PcmBatchError::UnableToSaveAsWav {+ message: error.to_string(),+ })?;+ for sample in self.samples.iter() {+ writer.write_sample((sample.clamp(-1.0, 1.0) * 32767.0) as i16).map_err(|error| {+ PcmBatchError::UnableToSaveAsWav {+ message: error.to_string(),+ }+ })?;+ }+ writer.finalize().map_err(|error| PcmBatchError::UnableToSaveAsWav {+ message: error.to_string(),+ })?;++ Ok(())+ }+}diff --git a/crates/shoji/src/types/encoding/reasoning_effort.rs b/crates/shoji/src/types/basic/reasoning_effort.rssimilarity index 100%rename from crates/shoji/src/types/encoding/reasoning_effort.rsrename to crates/shoji/src/types/basic/reasoning_effort.rsdiff --git a/crates/shoji/src/types/model/repository.rs b/crates/shoji/src/types/basic/repository.rssimilarity index 76%rename from crates/shoji/src/types/model/repository.rsrename to crates/shoji/src/types/basic/repository.rsindex 7bb7e6403..e11b8b683 100644--- a/crates/shoji/src/types/model/repository.rs+++ b/crates/shoji/src/types/basic/repository.rs@@ -1,10 +1,10 @@use serde::{Deserialize, Serialize};-#[bindings::export(Struct)]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Repository {pub identifier: String,- pub commit_hash: String,+ pub commit_hash: Option<String>,pub paths: Option<Vec<String>>,}diff --git a/crates/shoji/src/types/basic/sampling_method.rs b/crates/shoji/src/types/basic/sampling_method.rsindex 3ea9f933c..13d1d251f 100644--- a/crates/shoji/src/types/basic/sampling_method.rs+++ b/crates/shoji/src/types/basic/sampling_method.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum, name = "SamplingMethod")]+#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub enum SamplingMethod {Greedy {},diff --git a/crates/shoji/src/types/basic/sampling_policy.rs b/crates/shoji/src/types/basic/sampling_policy.rsindex d82a28a1a..2b7c6b2e0 100644--- a/crates/shoji/src/types/basic/sampling_policy.rs+++ b/crates/shoji/src/types/basic/sampling_policy.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::SamplingMethod;-#[bindings::export(Enum, name = "SamplingPolicy")]+#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub enum SamplingPolicy {Default {},diff --git a/crates/shoji/src/types/basic/sampling_seed.rs b/crates/shoji/src/types/basic/sampling_seed.rsindex de03c47c0..103708c6d 100644--- a/crates/shoji/src/types/basic/sampling_seed.rs+++ b/crates/shoji/src/types/basic/sampling_seed.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum, name = "SamplingSeed")]+#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum SamplingSeed {Default {},diff --git a/crates/shoji/src/types/basic/token.rs b/crates/shoji/src/types/basic/token.rsindex 0ac0ea47b..e98361f21 100644--- a/crates/shoji/src/types/basic/token.rs+++ b/crates/shoji/src/types/basic/token.rs@@ -2,10 +2,13 @@ use std::fmt;use serde::{Deserialize, Serialize};+#[bindings::export(Alias)]pub type TokenId = u32;++#[bindings::export(Alias)]pub type TokenValue = String;-#[bindings::export(Struct, name = "Token")]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Token {diff --git a/crates/shoji/src/types/encoding/tool_call.rs b/crates/shoji/src/types/basic/tool_call.rssimilarity index 89%rename from crates/shoji/src/types/encoding/tool_call.rsrename to crates/shoji/src/types/basic/tool_call.rsindex 360355b27..4aa3ab039 100644--- a/crates/shoji/src/types/encoding/tool_call.rs+++ b/crates/shoji/src/types/basic/tool_call.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::types::basic::Value;-#[bindings::export(Struct)]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ToolCall {diff --git a/crates/shoji/src/types/encoding/tool_description.rs b/crates/shoji/src/types/basic/tool_description.rssimilarity index 66%rename from crates/shoji/src/types/encoding/tool_description.rsrename to crates/shoji/src/types/basic/tool_description.rsindex 71cb8c485..4a769a6cb 100644--- a/crates/shoji/src/types/encoding/tool_description.rs+++ b/crates/shoji/src/types/basic/tool_description.rs@@ -1,12 +1,13 @@use serde::{Deserialize, Serialize};-use crate::types::encoding::ToolFunction;+use crate::types::basic::ToolFunction;#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]pub enum ToolDescription {Function {- function: ToolFunction,+ #[serde(rename = "function")]+ tool_function: ToolFunction,},}diff --git a/crates/shoji/src/types/encoding/tool_function.rs b/crates/shoji/src/types/basic/tool_function.rssimilarity index 71%rename from crates/shoji/src/types/encoding/tool_function.rsrename to crates/shoji/src/types/basic/tool_function.rsindex bbddcfd20..1ddff1946 100644--- a/crates/shoji/src/types/encoding/tool_function.rs+++ b/crates/shoji/src/types/basic/tool_function.rs@@ -2,12 +2,13 @@ use serde::{Deserialize, Serialize};use crate::types::basic::Value;-#[bindings::export(Struct)]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ToolFunction {pub name: String,pub description: String,pub parameters: Option<Value>,- pub r#return: Option<Value>,+ #[serde(rename = "return")]+ pub return_definition: Option<Value>,}diff --git a/crates/shoji/src/types/encoding/tool_namespace.rs b/crates/shoji/src/types/basic/tool_namespace.rssimilarity index 76%rename from crates/shoji/src/types/encoding/tool_namespace.rsrename to crates/shoji/src/types/basic/tool_namespace.rsindex 1143571dc..f3149d6b2 100644--- a/crates/shoji/src/types/encoding/tool_namespace.rs+++ b/crates/shoji/src/types/basic/tool_namespace.rs@@ -1,8 +1,8 @@use serde::{Deserialize, Serialize};-use crate::types::encoding::ToolDescription;+use crate::types::basic::ToolDescription;-#[bindings::export(Struct)]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct ToolNamespace {diff --git a/crates/shoji/src/types/encoding/translation_input.rs b/crates/shoji/src/types/basic/translation_payload.rssimilarity index 89%rename from crates/shoji/src/types/encoding/translation_input.rsrename to crates/shoji/src/types/basic/translation_payload.rsindex 70028de33..d92ae8285 100644--- a/crates/shoji/src/types/encoding/translation_input.rs+++ b/crates/shoji/src/types/basic/translation_payload.rs@@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize};#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]-pub enum TranslationInput {+pub enum TranslationPayload {Text {text: String,},diff --git a/crates/shoji/src/types/basic/value.rs b/crates/shoji/src/types/basic/value.rsindex 6bee593d2..41ddcd59d 100644--- a/crates/shoji/src/types/basic/value.rs+++ b/crates/shoji/src/types/basic/value.rs@@ -2,7 +2,7 @@ use std::fmt;use serde::{Deserialize, Deserializer, Serialize, Serializer};-#[bindings::export(Struct, name = "Value")]+#[bindings::export(ClassCloneable)]#[derive(Clone, PartialEq)]pub struct Value {pub json: String,diff --git a/crates/shoji/src/types/encoding/content_block.rs b/crates/shoji/src/types/encoding/content_block.rsdeleted file mode 100644index 2085f0849..000000000--- a/crates/shoji/src/types/encoding/content_block.rs+++ /dev/null@@ -1,225 +0,0 @@-use std::{- fmt::{self, Display},- str::FromStr,-};--use serde::{Deserialize, Deserializer, Serialize, Serializer, de};--use crate::types::{- basic::Value,- encoding::{ReasoningEffort, ToolCall, ToolNamespace, TranslationInput},-};--#[bindings::export(Enum)]-#[derive(Debug, Clone, PartialEq, Eq, Hash)]-pub enum ContentBlockType {- Identity,- ReasoningEffort,- ConversationStartDate,- KnowledgeCutoff,- BuiltinTools,- Tools,- Text,- Image,- Video,- Audio,- File,- Reasoning,- ToolCall,- ToolCallCandidate,- ToolCallResult,- Translation,- Custom,-}--impl FromStr for ContentBlockType {- type Err = String;-- fn from_str(s: &str) -> Result<Self, Self::Err> {- match s {- "identity" => Ok(ContentBlockType::Identity),- "reasoning_effort" => Ok(ContentBlockType::ReasoningEffort),- "conversation_start_date" => Ok(ContentBlockType::ConversationStartDate),- "knowledge_cutoff" => Ok(ContentBlockType::KnowledgeCutoff),- "builtin_tools" => Ok(ContentBlockType::BuiltinTools),- "tools" => Ok(ContentBlockType::Tools),- "text" => Ok(ContentBlockType::Text),- "image" => Ok(ContentBlockType::Image),- "video" => Ok(ContentBlockType::Video),- "audio" => Ok(ContentBlockType::Audio),- "file" => Ok(ContentBlockType::File),- "reasoning" => Ok(ContentBlockType::Reasoning),- "tool_call" => Ok(ContentBlockType::ToolCall),- "tool_call_candidate" => Ok(ContentBlockType::ToolCallCandidate),- "tool_call_result" => Ok(ContentBlockType::ToolCallResult),- "translation" => Ok(ContentBlockType::Translation),- "custom" => Ok(ContentBlockType::Custom),- other => Err(format!("Unknown content block type: {other}")),- }- }-}--impl Display for ContentBlockType {- fn fmt(- &self,- formatter: &mut fmt::Formatter<'_>,- ) -> fmt::Result {- let name = match self {- ContentBlockType::Identity => "identity",- ContentBlockType::ReasoningEffort => "reasoning_effort",- ContentBlockType::ConversationStartDate => "conversation_start_date",- ContentBlockType::KnowledgeCutoff => "knowledge_cutoff",- ContentBlockType::BuiltinTools => "builtin_tools",- ContentBlockType::Tools => "tools",- ContentBlockType::Text => "text",- ContentBlockType::Image => "image",- ContentBlockType::Video => "video",- ContentBlockType::Audio => "audio",- ContentBlockType::File => "file",- ContentBlockType::Reasoning => "reasoning",- ContentBlockType::ToolCall => "tool_call",- ContentBlockType::ToolCallCandidate => "tool_call_candidate",- ContentBlockType::ToolCallResult => "tool_call_result",- ContentBlockType::Translation => "translation",- ContentBlockType::Custom => "custom",- };- write!(formatter, "{name}")- }-}--impl Serialize for ContentBlockType {- fn serialize<S: Serializer>(- &self,- serializer: S,- ) -> Result<S::Ok, S::Error> {- serializer.serialize_str(&self.to_string())- }-}--impl<'d> Deserialize<'d> for ContentBlockType {- fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {- let name = String::deserialize(deserializer)?;- ContentBlockType::from_str(&name).map_err(de::Error::custom)- }-}--#[bindings::export(Enum)]-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(tag = "type", rename_all = "snake_case")]-pub enum ContentBlock {- Identity {- value: String,- },- ReasoningEffort {- value: ReasoningEffort,- },- ConversationStartDate {- value: String,- },- KnowledgeCutoff {- value: String,- },- BuiltinTools {- names: Vec<String>,- },- Tools {- namespaces: Vec<ToolNamespace>,- },- Text {- value: String,- },- Image {- url: String,- },- Video {- url: String,- },- Audio {- url: String,- },- File {- url: String,- },- Reasoning {- value: String,- },- ToolCall {- value: ToolCall,- },- ToolCallCandidate {- value: Value,- },- ToolCallResult {- #[serde(rename = "id")]- identifier: Option<String>,- name: Option<String>,- value: Value,- },- Translation {- #[serde(flatten)]- input: TranslationInput,- source_language_code: String,- target_language_code: String,- },- Custom {- value: Value,- },-}--impl ContentBlock {- pub fn get_type(&self) -> ContentBlockType {- match self {- ContentBlock::Identity {- ..- } => ContentBlockType::Identity,- ContentBlock::ReasoningEffort {- ..- } => ContentBlockType::ReasoningEffort,- ContentBlock::ConversationStartDate {- ..- } => ContentBlockType::ConversationStartDate,- ContentBlock::KnowledgeCutoff {- ..- } => ContentBlockType::KnowledgeCutoff,- ContentBlock::BuiltinTools {- ..- } => ContentBlockType::BuiltinTools,- ContentBlock::Tools {- ..- } => ContentBlockType::Tools,- ContentBlock::Text {- ..- } => ContentBlockType::Text,- ContentBlock::Image {- ..- } => ContentBlockType::Image,- ContentBlock::Video {- ..- } => ContentBlockType::Video,- ContentBlock::Audio {- ..- } => ContentBlockType::Audio,- ContentBlock::File {- ..- } => ContentBlockType::File,- ContentBlock::Reasoning {- ..- } => ContentBlockType::Reasoning,- ContentBlock::ToolCall {- ..- } => ContentBlockType::ToolCall,- ContentBlock::ToolCallCandidate {- ..- } => ContentBlockType::ToolCallCandidate,- ContentBlock::ToolCallResult {- ..- } => ContentBlockType::ToolCallResult,- ContentBlock::Translation {- ..- } => ContentBlockType::Translation,- ContentBlock::Custom {- ..- } => ContentBlockType::Custom,- }- }-}diff --git a/crates/shoji/src/types/encoding/message.rs b/crates/shoji/src/types/encoding/message.rsdeleted file mode 100644index 34c9d99a8..000000000--- a/crates/shoji/src/types/encoding/message.rs+++ /dev/null@@ -1,177 +0,0 @@-use std::collections::HashMap;--use serde::{Deserialize, Serialize};--use crate::types::{- basic::Value,- encoding::{ContentBlock, ReasoningEffort, Role, ToolCall, ToolNamespace},-};--#[bindings::export(Struct)]-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub struct Message {- pub role: Role,- pub content: Vec<ContentBlock>,- pub metadata: HashMap<String, Value>,-}--impl Message {- pub fn for_role(role: Role) -> Self {- Self {- role,- content: vec![],- metadata: HashMap::new(),- }- }-- pub fn system() -> Self {- Self::for_role(Role::System {})- }-- pub fn developer() -> Self {- Self::for_role(Role::Developer {})- }-- pub fn user() -> Self {- Self::for_role(Role::User {})- }-- pub fn assistant() -> Self {- Self::for_role(Role::Assistant {})- }-- pub fn tool() -> Self {- Self::for_role(Role::Tool {})- }-}--impl Message {- fn with_block(- self,- block: ContentBlock,- ) -> Self {- let mut content = self.content;- content.push(block);- Self {- content,- ..self- }- }-- pub fn with_reasoning_effort(- self,- reasoning_effort: ReasoningEffort,- ) -> Self {- self.with_block(ContentBlock::ReasoningEffort {- value: reasoning_effort,- })- }-- pub fn with_tool_namespaces(- self,- tool_namespaces: Vec<ToolNamespace>,- ) -> Self {- self.with_block(ContentBlock::Tools {- namespaces: tool_namespaces,- })- }-- pub fn with_text(- self,- text: String,- ) -> Self {- self.with_block(ContentBlock::Text {- value: text,- })- }-- pub fn with_reasoning(- self,- reasoning: String,- ) -> Self {- self.with_block(ContentBlock::Reasoning {- value: reasoning,- })- }-- pub fn with_tool_call(- self,- tool_call: ToolCall,- ) -> Self {- self.with_block(ContentBlock::ToolCall {- value: tool_call,- })- }-- pub fn with_tool_call_candidate(- self,- value: Value,- ) -> Self {- self.with_block(ContentBlock::ToolCallCandidate {- value,- })- }-}--macro_rules! blocks_by_type {- ($self:expr, $variant:ident, $field:ident) => {- $self.content.iter().filter_map(|block| match block {- ContentBlock::$variant {- $field,- } => Some($field.clone()),- _ => None,- })- };-}--impl Message {- pub fn reasoning_effort(&self) -> Option<ReasoningEffort> {- blocks_by_type!(self, ReasoningEffort, value).next()- }-- pub fn text(&self) -> String {- blocks_by_type!(self, Text, value).collect::<String>()- }-- pub fn reasoning(&self) -> String {- blocks_by_type!(self, Reasoning, value).collect::<String>()- }-- pub fn tool_namespaces(&self) -> Vec<ToolNamespace> {- blocks_by_type!(self, Tools, namespaces).flatten().collect()- }-- pub fn tool_calls(&self) -> Vec<ToolCall> {- blocks_by_type!(self, ToolCall, value).collect()- }-- pub fn tool_call_results(&self) -> Vec<(Option<String>, Option<String>, Value)> {- self.content- .iter()- .filter_map(|block| match block {- ContentBlock::ToolCallResult {- identifier,- name,- value,- } => Some((identifier.clone(), name.clone(), value.clone())),- _ => None,- })- .collect()- }-}--pub trait MessageList {- fn reasoning_effort(&self) -> Option<ReasoningEffort>;- fn tool_namespaces(&self) -> Vec<ToolNamespace>;-}--impl MessageList for Vec<Message> {- fn reasoning_effort(&self) -> Option<ReasoningEffort> {- self.iter().find_map(|message| message.reasoning_effort())- }-- fn tool_namespaces(&self) -> Vec<ToolNamespace> {- self.iter().flat_map(|message| message.tool_namespaces()).collect()- }-}diff --git a/crates/shoji/src/types/encoding/mod.rs b/crates/shoji/src/types/encoding/mod.rsdeleted file mode 100644index 3814d6d42..000000000--- a/crates/shoji/src/types/encoding/mod.rs+++ /dev/null@@ -1,21 +0,0 @@-mod capabilities;-mod content_block;-mod message;-mod reasoning_effort;-mod role;-mod tool_call;-mod tool_description;-mod tool_function;-mod tool_namespace;-mod translation_input;--pub use capabilities::Capabilities;-pub use content_block::{ContentBlock, ContentBlockType};-pub use message::{Message, MessageList};-pub use reasoning_effort::ReasoningEffort;-pub use role::Role;-pub use tool_call::ToolCall;-pub use tool_description::ToolDescription;-pub use tool_function::ToolFunction;-pub use tool_namespace::ToolNamespace;-pub use translation_input::TranslationInput;diff --git a/crates/shoji/src/types/mod.rs b/crates/shoji/src/types/mod.rsindex 34d1e0f50..f1a466faf 100644--- a/crates/shoji/src/types/mod.rs+++ b/crates/shoji/src/types/mod.rs@@ -1,4 +1,3 @@pub mod basic;-pub mod encoding;pub mod model;pub mod session;diff --git a/crates/shoji/src/types/model/accessibility.rs b/crates/shoji/src/types/model/accessibility.rsindex b620faa0a..eeb59f06a 100644--- a/crates/shoji/src/types/model/accessibility.rs+++ b/crates/shoji/src/types/model/accessibility.rs@@ -1,13 +1,13 @@use serde::{Deserialize, Serialize};-use crate::types::model::{Reference, Repository};+use crate::types::{basic::Repository, model::ModelReference};#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]-pub enum Accessibility {+pub enum ModelAccessibility {Local {- reference: Reference,+ reference: ModelReference,},Remote {repository: Option<Repository>,diff --git a/crates/shoji/src/types/model/backend.rs b/crates/shoji/src/types/model/backend.rsnew file mode 100644index 000000000..11797302a--- /dev/null+++ b/crates/shoji/src/types/model/backend.rs@@ -0,0 +1,21 @@+use serde::{Deserialize, Serialize};++use crate::types::basic::Metadata;++#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct ModelBackend {+ #[serde(rename = "id")]+ pub identifier: String,+ pub version: String,+ pub metadata: Metadata,+}++#[bindings::export(Implementation)]+impl ModelBackend {+ #[bindings::export(Getter)]+ pub fn name(&self) -> String {+ self.metadata.name.clone()+ }+}diff --git a/crates/shoji/src/types/model/entity.rs b/crates/shoji/src/types/model/entity.rsdeleted file mode 100644index 4a66341f3..000000000--- a/crates/shoji/src/types/model/entity.rs+++ /dev/null@@ -1,27 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::types::model::Image;--#[bindings::export(Enum)]-#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum EntityType {- Registry,- Backend,- Vendor,- Family,- Variant,-}--#[bindings::export(Struct)]-#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub struct Entity {- pub r#type: EntityType,- pub identifier: String,- pub parent_identifier: Option<String>,- pub name: String,- pub description: Option<String>,- pub version: Option<String>,- pub icons: Vec<Image>,-}diff --git a/crates/shoji/src/types/model/family.rs b/crates/shoji/src/types/model/family.rsnew file mode 100644index 000000000..58095ffd9--- /dev/null+++ b/crates/shoji/src/types/model/family.rs@@ -0,0 +1,21 @@+use serde::{Deserialize, Serialize};++use crate::types::{basic::Metadata, model::ModelVendor};++#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct ModelFamily {+ #[serde(rename = "id")]+ pub identifier: String,+ pub vendor: ModelVendor,+ pub metadata: Metadata,+}++#[bindings::export(Implementation)]+impl ModelFamily {+ #[bindings::export(Getter)]+ pub fn name(&self) -> String {+ self.metadata.name.clone()+ }+}diff --git a/crates/shoji/src/types/model/mod.rs b/crates/shoji/src/types/model/mod.rsindex 0adde5ff9..a30a19526 100644--- a/crates/shoji/src/types/model/mod.rs+++ b/crates/shoji/src/types/model/mod.rs@@ -1,21 +1,21 @@mod accessibility;-mod entity;-mod file;-mod hash;-mod image;+mod backend;+mod family;mod model;+mod properties;mod quantization;mod reference;-mod repository;+mod registry;mod specialization;+mod vendor;-pub use accessibility::Accessibility;-pub use entity::{Entity, EntityType};-pub use file::File;-pub use hash::{Hash, HashMethod};-pub use image::{Image, ImageFormat, ImageTheme};+pub use accessibility::ModelAccessibility;+pub use backend::ModelBackend;+pub use family::ModelFamily;pub use model::Model;-pub use quantization::Quantization;-pub use reference::Reference;-pub use repository::Repository;-pub use specialization::Specialization;+pub use properties::ModelProperties;+pub use quantization::ModelQuantization;+pub use reference::ModelReference;+pub use registry::ModelRegistry;+pub use specialization::ModelSpecialization;+pub use vendor::ModelVendor;diff --git a/crates/shoji/src/types/model/model.rs b/crates/shoji/src/types/model/model.rsindex a16d397f4..44cbae64a 100644--- a/crates/shoji/src/types/model/model.rs+++ b/crates/shoji/src/types/model/model.rs@@ -1,52 +1,83 @@use serde::{Deserialize, Serialize};-use crate::types::model::{Accessibility, Entity, EntityType, Quantization, Reference, Specialization};--#[bindings::export(Struct)]+use crate::types::{+ basic::Metadata,+ model::{+ ModelAccessibility, ModelBackend, ModelFamily, ModelProperties, ModelQuantization, ModelReference,+ ModelRegistry, ModelSpecialization,+ },+};++#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Model {+ #[serde(rename = "id")]pub identifier: String,- pub entities: Vec<Entity>,- pub specializations: Vec<Specialization>,- pub number_of_parameters: Option<i64>,- pub quantization: Option<Quantization>,- pub accessibility: Accessibility,+ pub registry: ModelRegistry,+ pub backends: Vec<ModelBackend>,+ pub family: Option<ModelFamily>,+ pub properties: Option<ModelProperties>,+ pub quantization: Option<ModelQuantization>,+ pub specializations: Vec<ModelSpecialization>,+ pub accessibility: ModelAccessibility,}+#[bindings::export(Implementation)]impl Model {- pub fn identifier(&self) -> String {- self.identifier.clone()- }-- pub fn cache_identifier(&self) -> String {- self.identifier.replace(":", "-").replace("/", "-")+ #[bindings::export(Getter)]+ pub fn name(&self) -> String {+ let parts: Vec<Option<String>> = vec![+ self.family.as_ref().map(|family| family.name()),+ self.properties.as_ref().map(|properties| properties.name()),+ self.quantization.as_ref().map(|quantization| quantization.name()),+ ];+ let name = parts.iter().filter_map(|part| part.clone()).collect::<Vec<_>>().join(" ");+ if name.is_empty() {+ self.identifier.clone()+ } else {+ name+ }}+ #[bindings::export(Getter)]pub fn is_local(&self) -> bool {- matches!(self.accessibility, Accessibility::Local { .. })+ matches!(self.accessibility, ModelAccessibility::Local { .. })}+ #[bindings::export(Getter)]pub fn is_remote(&self) -> bool {- matches!(self.accessibility, Accessibility::Remote { .. })+ matches!(self.accessibility, ModelAccessibility::Remote { .. })}+ #[bindings::export(Getter)]pub fn is_downloadable(&self) -> bool {matches!(self.accessibility,- Accessibility::Local {- reference: Reference::Mirai { .. } | Reference::HuggingFace { .. }+ ModelAccessibility::Local {+ reference: ModelReference::Mirai { .. } | ModelReference::HuggingFace { .. }})}+ #[bindings::export(Getter)]+ pub fn is_quantized(&self) -> bool {+ self.quantization.is_some()+ }++ #[bindings::export(Getter)]+ pub fn cache_identifier(&self) -> String {+ self.identifier.replace(":", "-").replace("/", "-")+ }++ #[bindings::export(Getter)]pub fn repo_ids(&self) -> Vec<String> {match &self.accessibility {- Accessibility::Local {+ ModelAccessibility::Local {reference,..} => match reference {- Reference::Mirai {+ ModelReference::Mirai {repository,source_repository,..@@ -60,14 +91,14 @@ impl Model {}result},- Reference::HuggingFace {+ ModelReference::HuggingFace {repository,} => vec![repository.identifier.clone()],- Reference::Local {+ ModelReference::Local {..} => vec![],},- Accessibility::Remote {+ ModelAccessibility::Remote {repository,..} => {@@ -80,89 +111,126 @@ impl Model {}}+ #[bindings::export(Getter)]pub fn local_external_path(&self) -> Option<String> {match &self.accessibility {- Accessibility::Local {+ ModelAccessibility::Local {reference,..} => match reference {- Reference::Mirai {+ ModelReference::Mirai {..} => None,- Reference::HuggingFace {+ ModelReference::HuggingFace {..} => None,- Reference::Local {+ ModelReference::Local {path,} => Some(path.clone()),},- Accessibility::Remote {+ ModelAccessibility::Remote {..} => None,}}+ #[bindings::export(Getter)]pub fn reference_name(&self) -> Option<String> {match &self.accessibility {- Accessibility::Local {+ ModelAccessibility::Local {reference,..} => Some(reference.name()),- Accessibility::Remote {+ ModelAccessibility::Remote {..} => None,}}+ #[bindings::export(Getter)]pub fn checkpoint_version(&self) -> Option<String> {match &self.accessibility {- Accessibility::Local {+ ModelAccessibility::Local {reference,..} => match reference {- Reference::Mirai {+ ModelReference::Mirai {toolchain_version,..} => Some(toolchain_version.clone()),- Reference::HuggingFace {+ ModelReference::HuggingFace {repository,- } => Some(repository.commit_hash.clone()),- Reference::Local {+ } => repository.commit_hash.clone(),+ ModelReference::Local {..} => None,},- Accessibility::Remote {+ ModelAccessibility::Remote {..} => None,}}}+#[bindings::export(Implementation)]impl Model {- pub fn registry_entity(&self) -> Option<Entity> {- self.entity(EntityType::Registry)+ #[bindings::export(Factory)]+ pub fn external(+ identifier: String,+ registry_identifier: String,+ registry_name: String,+ backend_identifier: String,+ backend_name: String,+ backend_version: String,+ specializations: Vec<ModelSpecialization>,+ accessibility: ModelAccessibility,+ ) -> Self {+ let registry = ModelRegistry {+ identifier: registry_identifier,+ metadata: Metadata::external(registry_name),+ };+ let backend = ModelBackend {+ identifier: backend_identifier.clone(),+ version: backend_version,+ metadata: Metadata::external(backend_name),+ };+ Self {+ identifier,+ registry,+ backends: vec![backend],+ family: None,+ properties: None,+ quantization: None,+ specializations,+ accessibility,+ }}+}- pub fn backend_entity(&self) -> Option<Entity> {- self.entity(EntityType::Backend)+#[bindings::export(Implementation)]+impl Model {+ #[bindings::export(Getter)]+ pub fn is_chat_capable(&self) -> bool {+ self.specializations.contains(&ModelSpecialization::Chat {})}- pub fn vendor_entity(&self) -> Option<Entity> {- self.entity(EntityType::Vendor)+ #[bindings::export(Getter)]+ pub fn is_classification_capable(&self) -> bool {+ self.specializations.contains(&ModelSpecialization::Classification {})}- pub fn family_entity(&self) -> Option<Entity> {- self.entity(EntityType::Family)+ #[bindings::export(Getter)]+ pub fn is_text_to_speech_capable(&self) -> bool {+ self.specializations.contains(&ModelSpecialization::TextToSpeech {})}- pub fn variant_entity(&self) -> Option<Entity> {- self.entity(EntityType::Variant)+ #[bindings::export(Getter)]+ pub fn is_translation_capable(&self) -> bool {+ self.specializations.contains(&ModelSpecialization::Translation {})}- fn entity(- &self,- r#type: EntityType,- ) -> Option<Entity> {- self.entities.iter().find(|entity| entity.r#type == r#type).map(|entity| entity.clone())+ #[bindings::export(Getter)]+ pub fn is_speculation_capable(&self) -> bool {+ self.specializations.contains(&ModelSpecialization::Speculation {})}}diff --git a/crates/shoji/src/types/model/properties.rs b/crates/shoji/src/types/model/properties.rsnew file mode 100644index 000000000..dd812a91a--- /dev/null+++ b/crates/shoji/src/types/model/properties.rs@@ -0,0 +1,22 @@+use serde::{Deserialize, Serialize};++use crate::types::basic::Metadata;++#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct ModelProperties {+ #[serde(rename = "id")]+ pub identifier: String,+ pub size: i64,+ pub version: Option<String>,+ pub metadata: Metadata,+}++#[bindings::export(Implementation)]+impl ModelProperties {+ #[bindings::export(Getter)]+ pub fn name(&self) -> String {+ self.metadata.name.clone()+ }+}diff --git a/crates/shoji/src/types/model/quantization.rs b/crates/shoji/src/types/model/quantization.rsindex c1bb0d60a..7be908425 100644--- a/crates/shoji/src/types/model/quantization.rs+++ b/crates/shoji/src/types/model/quantization.rs@@ -1,9 +1,23 @@use serde::{Deserialize, Serialize};-#[bindings::export(Struct)]+use crate::types::{basic::Metadata, model::ModelVendor};++#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]-pub struct Quantization {+pub struct ModelQuantization {+ #[serde(rename = "id")]+ pub identifier: String,pub method: String,pub bits_per_weight: u32,+ pub vendor: ModelVendor,+ pub metadata: Metadata,+}++#[bindings::export(Implementation)]+impl ModelQuantization {+ #[bindings::export(Getter)]+ pub fn name(&self) -> String {+ self.metadata.name.clone()+ }}diff --git a/crates/shoji/src/types/model/reference.rs b/crates/shoji/src/types/model/reference.rsindex 25daa58e9..164492065 100644--- a/crates/shoji/src/types/model/reference.rs+++ b/crates/shoji/src/types/model/reference.rs@@ -1,11 +1,11 @@use serde::{Deserialize, Serialize};-use crate::types::model::{File, Repository};+use crate::types::basic::{File, Repository};#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]-pub enum Reference {+pub enum ModelReference {Mirai {toolchain_version: String,repository: Option<Repository>,@@ -20,16 +20,16 @@ pub enum Reference {},}-impl Reference {+impl ModelReference {pub fn name(&self) -> String {match self {- Reference::Mirai {+ ModelReference::Mirai {..} => "mirai".to_string(),- Reference::HuggingFace {+ ModelReference::HuggingFace {..} => "huggingface".to_string(),- Reference::Local {+ ModelReference::Local {..} => "local".to_string(),}diff --git a/crates/shoji/src/types/model/registry.rs b/crates/shoji/src/types/model/registry.rsnew file mode 100644index 000000000..7ddd6de2e--- /dev/null+++ b/crates/shoji/src/types/model/registry.rs@@ -0,0 +1,20 @@+use serde::{Deserialize, Serialize};++use crate::types::basic::Metadata;++#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct ModelRegistry {+ #[serde(rename = "id")]+ pub identifier: String,+ pub metadata: Metadata,+}++#[bindings::export(Implementation)]+impl ModelRegistry {+ #[bindings::export(Getter)]+ pub fn name(&self) -> String {+ self.metadata.name.clone()+ }+}diff --git a/crates/shoji/src/types/model/specialization.rs b/crates/shoji/src/types/model/specialization.rsindex 9cfabe58a..f688ed96a 100644--- a/crates/shoji/src/types/model/specialization.rs+++ b/crates/shoji/src/types/model/specialization.rs@@ -3,10 +3,10 @@ use serde::{Deserialize, Serialize};#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]-pub enum Specialization {- Chat,- Classification,- TextToSpeech,- Translation,- Speculation,+pub enum ModelSpecialization {+ Chat {},+ Classification {},+ TextToSpeech {},+ Translation {},+ Speculation {},}diff --git a/crates/shoji/src/types/model/vendor.rs b/crates/shoji/src/types/model/vendor.rsnew file mode 100644index 000000000..b1af22410--- /dev/null+++ b/crates/shoji/src/types/model/vendor.rs@@ -0,0 +1,20 @@+use serde::{Deserialize, Serialize};++use crate::types::basic::Metadata;++#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct ModelVendor {+ #[serde(rename = "id")]+ pub identifier: String,+ pub metadata: Metadata,+}++#[bindings::export(Implementation)]+impl ModelVendor {+ #[bindings::export(Getter)]+ pub fn name(&self) -> String {+ self.metadata.name.clone()+ }+}diff --git a/crates/shoji/src/types/encoding/capabilities.rs b/crates/shoji/src/types/session/chat/capabilities.rssimilarity index 79%rename from crates/shoji/src/types/encoding/capabilities.rsrename to crates/shoji/src/types/session/chat/capabilities.rsindex 5b4ad2f75..0ddba94ad 100644--- a/crates/shoji/src/types/encoding/capabilities.rs+++ b/crates/shoji/src/types/session/chat/capabilities.rs@@ -1,8 +1,8 @@use serde::{Deserialize, Serialize};-#[bindings::export(Struct)]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub struct Capabilities {+pub struct ChatModelCapabilities {pub supports_reasoning: bool,pub supports_disable_reasoning: bool,pub supports_tools: bool,diff --git a/crates/shoji/src/types/session/chat/config.rs b/crates/shoji/src/types/session/chat/config.rsindex b8ea8d0ef..da2f470da 100644--- a/crates/shoji/src/types/session/chat/config.rs+++ b/crates/shoji/src/types/session/chat/config.rs@@ -1,19 +1,19 @@use serde::{Deserialize, Serialize};use crate::types::{- basic::SamplingSeed,- session::chat::{ContextLength, SpeculationPreset},+ basic::{ContextLength, SamplingSeed},+ session::chat::ChatSpeculationPreset,};-#[bindings::export(Struct, name = "ChatConfig")]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub struct Config {+pub struct ChatConfig {pub context_length: ContextLength,pub sampling_seed: SamplingSeed,- pub speculation_preset: Option<SpeculationPreset>,+ pub speculation_preset: Option<ChatSpeculationPreset>,}-impl Default for Config {+impl Default for ChatConfig {fn default() -> Self {Self {context_length: ContextLength::default(),@@ -23,38 +23,46 @@ impl Default for Config {}}-impl Config {+#[bindings::export(Implementation)]+impl ChatConfig {+ #[bindings::export(Factory)]+ pub fn create() -> Self {+ Self::default()+ }+}++#[bindings::export(Implementation)]+impl ChatConfig {+ #[bindings::export(Method)]pub fn with_context_length(- self,+ &self,context_length: ContextLength,) -> Self {Self {context_length,- ..self+ ..self.clone()}}-}-impl Config {+ #[bindings::export(Method)]pub fn with_sampling_seed(- self,+ &self,sampling_seed: SamplingSeed,) -> Self {Self {sampling_seed,- ..self+ ..self.clone()}}-}-impl Config {+ #[bindings::export(Method)]pub fn with_speculation_preset(- self,- speculation_preset: Option<SpeculationPreset>,+ &self,+ speculation_preset: Option<ChatSpeculationPreset>,) -> Self {Self {speculation_preset,- ..self+ ..self.clone()}}}diff --git a/crates/shoji/src/types/session/chat/content_block.rs b/crates/shoji/src/types/session/chat/content_block.rsnew file mode 100644index 000000000..4a984597b--- /dev/null+++ b/crates/shoji/src/types/session/chat/content_block.rs@@ -0,0 +1,222 @@+use std::{+ fmt::{self, Display},+ str::FromStr,+};++use serde::{Deserialize, Deserializer, Serialize, Serializer, de};++use crate::types::basic::{ReasoningEffort, ToolCall, ToolNamespace, TranslationPayload, Value};++#[bindings::export(Enum)]+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub enum ChatContentBlockType {+ Identity,+ ReasoningEffort,+ ConversationStartDate,+ KnowledgeCutoff,+ BuiltinTools,+ Tools,+ Text,+ Image,+ Video,+ Audio,+ File,+ Reasoning,+ ToolCall,+ ToolCallCandidate,+ ToolCallResult,+ Translation,+ Custom,+}++impl FromStr for ChatContentBlockType {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "identity" => Ok(ChatContentBlockType::Identity),+ "reasoning_effort" => Ok(ChatContentBlockType::ReasoningEffort),+ "conversation_start_date" => Ok(ChatContentBlockType::ConversationStartDate),+ "knowledge_cutoff" => Ok(ChatContentBlockType::KnowledgeCutoff),+ "builtin_tools" => Ok(ChatContentBlockType::BuiltinTools),+ "tools" => Ok(ChatContentBlockType::Tools),+ "text" => Ok(ChatContentBlockType::Text),+ "image" => Ok(ChatContentBlockType::Image),+ "video" => Ok(ChatContentBlockType::Video),+ "audio" => Ok(ChatContentBlockType::Audio),+ "file" => Ok(ChatContentBlockType::File),+ "reasoning" => Ok(ChatContentBlockType::Reasoning),+ "tool_call" => Ok(ChatContentBlockType::ToolCall),+ "tool_call_candidate" => Ok(ChatContentBlockType::ToolCallCandidate),+ "tool_call_result" => Ok(ChatContentBlockType::ToolCallResult),+ "translation" => Ok(ChatContentBlockType::Translation),+ "custom" => Ok(ChatContentBlockType::Custom),+ other => Err(format!("Unknown content block type: {other}")),+ }+ }+}++impl Display for ChatContentBlockType {+ fn fmt(+ &self,+ formatter: &mut fmt::Formatter<'_>,+ ) -> fmt::Result {+ let name = match self {+ ChatContentBlockType::Identity => "identity",+ ChatContentBlockType::ReasoningEffort => "reasoning_effort",+ ChatContentBlockType::ConversationStartDate => "conversation_start_date",+ ChatContentBlockType::KnowledgeCutoff => "knowledge_cutoff",+ ChatContentBlockType::BuiltinTools => "builtin_tools",+ ChatContentBlockType::Tools => "tools",+ ChatContentBlockType::Text => "text",+ ChatContentBlockType::Image => "image",+ ChatContentBlockType::Video => "video",+ ChatContentBlockType::Audio => "audio",+ ChatContentBlockType::File => "file",+ ChatContentBlockType::Reasoning => "reasoning",+ ChatContentBlockType::ToolCall => "tool_call",+ ChatContentBlockType::ToolCallCandidate => "tool_call_candidate",+ ChatContentBlockType::ToolCallResult => "tool_call_result",+ ChatContentBlockType::Translation => "translation",+ ChatContentBlockType::Custom => "custom",+ };+ write!(formatter, "{name}")+ }+}++impl Serialize for ChatContentBlockType {+ fn serialize<S: Serializer>(+ &self,+ serializer: S,+ ) -> Result<S::Ok, S::Error> {+ serializer.serialize_str(&self.to_string())+ }+}++impl<'d> Deserialize<'d> for ChatContentBlockType {+ fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {+ let name = String::deserialize(deserializer)?;+ ChatContentBlockType::from_str(&name).map_err(de::Error::custom)+ }+}++#[bindings::export(Enum)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum ChatContentBlock {+ Identity {+ value: String,+ },+ ReasoningEffort {+ value: ReasoningEffort,+ },+ ConversationStartDate {+ value: String,+ },+ KnowledgeCutoff {+ value: String,+ },+ BuiltinTools {+ names: Vec<String>,+ },+ Tools {+ namespaces: Vec<ToolNamespace>,+ },+ Text {+ value: String,+ },+ Image {+ url: String,+ },+ Video {+ url: String,+ },+ Audio {+ url: String,+ },+ File {+ url: String,+ },+ Reasoning {+ value: String,+ },+ ToolCall {+ value: ToolCall,+ },+ ToolCallCandidate {+ value: Value,+ },+ ToolCallResult {+ #[serde(rename = "id")]+ identifier: Option<String>,+ name: Option<String>,+ value: Value,+ },+ Translation {+ #[serde(flatten)]+ payload: TranslationPayload,+ source_language_code: String,+ target_language_code: String,+ },+ Custom {+ value: Value,+ },+}++impl ChatContentBlock {+ pub fn get_type(&self) -> ChatContentBlockType {+ match self {+ ChatContentBlock::Identity {+ ..+ } => ChatContentBlockType::Identity,+ ChatContentBlock::ReasoningEffort {+ ..+ } => ChatContentBlockType::ReasoningEffort,+ ChatContentBlock::ConversationStartDate {+ ..+ } => ChatContentBlockType::ConversationStartDate,+ ChatContentBlock::KnowledgeCutoff {+ ..+ } => ChatContentBlockType::KnowledgeCutoff,+ ChatContentBlock::BuiltinTools {+ ..+ } => ChatContentBlockType::BuiltinTools,+ ChatContentBlock::Tools {+ ..+ } => ChatContentBlockType::Tools,+ ChatContentBlock::Text {+ ..+ } => ChatContentBlockType::Text,+ ChatContentBlock::Image {+ ..+ } => ChatContentBlockType::Image,+ ChatContentBlock::Video {+ ..+ } => ChatContentBlockType::Video,+ ChatContentBlock::Audio {+ ..+ } => ChatContentBlockType::Audio,+ ChatContentBlock::File {+ ..+ } => ChatContentBlockType::File,+ ChatContentBlock::Reasoning {+ ..+ } => ChatContentBlockType::Reasoning,+ ChatContentBlock::ToolCall {+ ..+ } => ChatContentBlockType::ToolCall,+ ChatContentBlock::ToolCallCandidate {+ ..+ } => ChatContentBlockType::ToolCallCandidate,+ ChatContentBlock::ToolCallResult {+ ..+ } => ChatContentBlockType::ToolCallResult,+ ChatContentBlock::Translation {+ ..+ } => ChatContentBlockType::Translation,+ ChatContentBlock::Custom {+ ..+ } => ChatContentBlockType::Custom,+ }+ }+}diff --git a/crates/shoji/src/types/session/chat/message.rs b/crates/shoji/src/types/session/chat/message.rsnew file mode 100644index 000000000..9b9c9f1f9--- /dev/null+++ b/crates/shoji/src/types/session/chat/message.rs@@ -0,0 +1,223 @@+use std::collections::HashMap;++use serde::{Deserialize, Serialize};++use crate::types::{+ basic::{ReasoningEffort, ToolCall, ToolNamespace, Value},+ session::chat::{ChatContentBlock, ChatRole},+};++#[bindings::export(Struct)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct ChatMessageMetadata {+ pub values: HashMap<String, Value>,+}++impl From<HashMap<String, Value>> for ChatMessageMetadata {+ fn from(values: HashMap<String, Value>) -> Self {+ Self {+ values,+ }+ }+}++#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct ChatMessage {+ pub role: ChatRole,+ pub content: Vec<ChatContentBlock>,+ pub metadata: ChatMessageMetadata,+}++#[bindings::export(Implementation)]+impl ChatMessage {+ #[bindings::export(Factory)]+ pub fn for_role(role: ChatRole) -> Self {+ Self {+ role,+ content: vec![],+ metadata: ChatMessageMetadata {+ values: HashMap::new(),+ },+ }+ }++ #[bindings::export(Factory)]+ pub fn system() -> Self {+ Self::for_role(ChatRole::System {})+ }++ #[bindings::export(Factory)]+ pub fn developer() -> Self {+ Self::for_role(ChatRole::Developer {})+ }++ #[bindings::export(Factory)]+ pub fn user() -> Self {+ Self::for_role(ChatRole::User {})+ }++ #[bindings::export(Factory)]+ pub fn assistant() -> Self {+ Self::for_role(ChatRole::Assistant {})+ }++ #[bindings::export(Factory)]+ pub fn tool() -> Self {+ Self::for_role(ChatRole::Tool {})+ }+}++#[bindings::export(Implementation)]+impl ChatMessage {+ #[bindings::export(Method)]+ pub fn with_block(+ &self,+ block: ChatContentBlock,+ ) -> Self {+ let mut content = self.content.clone();+ content.push(block);+ Self {+ content,+ ..self.clone()+ }+ }++ #[bindings::export(Method)]+ pub fn with_reasoning_effort(+ &self,+ reasoning_effort: ReasoningEffort,+ ) -> Self {+ self.with_block(ChatContentBlock::ReasoningEffort {+ value: reasoning_effort,+ })+ }++ #[bindings::export(Method)]+ pub fn with_tool_namespaces(+ &self,+ tool_namespaces: Vec<ToolNamespace>,+ ) -> Self {+ self.with_block(ChatContentBlock::Tools {+ namespaces: tool_namespaces,+ })+ }++ #[bindings::export(Method)]+ pub fn with_text(+ &self,+ text: String,+ ) -> Self {+ self.with_block(ChatContentBlock::Text {+ value: text,+ })+ }++ #[bindings::export(Method)]+ pub fn with_reasoning(+ &self,+ reasoning: String,+ ) -> Self {+ self.with_block(ChatContentBlock::Reasoning {+ value: reasoning,+ })+ }++ #[bindings::export(Method)]+ pub fn with_tool_call(+ &self,+ tool_call: ToolCall,+ ) -> Self {+ self.with_block(ChatContentBlock::ToolCall {+ value: tool_call,+ })+ }++ #[bindings::export(Method)]+ pub fn with_tool_call_candidate(+ &self,+ value: Value,+ ) -> Self {+ self.with_block(ChatContentBlock::ToolCallCandidate {+ value,+ })+ }+}++macro_rules! blocks_by_type {+ ($self:expr, $variant:ident, $field:ident) => {+ $self.content.iter().filter_map(|block| match block {+ ChatContentBlock::$variant {+ $field,+ } => Some($field.clone()),+ _ => None,+ })+ };+}++#[bindings::export(Implementation)]+impl ChatMessage {+ #[bindings::export(Getter)]+ pub fn reasoning_effort(&self) -> Option<ReasoningEffort> {+ blocks_by_type!(self, ReasoningEffort, value).next()+ }++ #[bindings::export(Getter)]+ pub fn text(&self) -> Option<String> {+ blocks_by_type!(self, Text, value).reduce(|mut text, value| {+ text.push_str(&value);+ text+ })+ }++ #[bindings::export(Getter)]+ pub fn reasoning(&self) -> Option<String> {+ blocks_by_type!(self, Reasoning, value).reduce(|mut reasoning, value| {+ reasoning.push_str(&value);+ reasoning+ })+ }++ #[bindings::export(Getter)]+ pub fn tool_namespaces(&self) -> Vec<ToolNamespace> {+ blocks_by_type!(self, Tools, namespaces).flatten().collect()+ }++ #[bindings::export(Getter)]+ pub fn tool_calls(&self) -> Vec<ToolCall> {+ blocks_by_type!(self, ToolCall, value).collect()+ }+}++impl ChatMessage {+ pub fn tool_call_results(&self) -> Vec<(Option<String>, Option<String>, Value)> {+ self.content+ .iter()+ .filter_map(|block| match block {+ ChatContentBlock::ToolCallResult {+ identifier,+ name,+ value,+ } => Some((identifier.clone(), name.clone(), value.clone())),+ _ => None,+ })+ .collect()+ }+}++pub trait ChatMessageList {+ fn reasoning_effort(&self) -> Option<ReasoningEffort>;+ fn tool_namespaces(&self) -> Vec<ToolNamespace>;+}++impl ChatMessageList for Vec<ChatMessage> {+ fn reasoning_effort(&self) -> Option<ReasoningEffort> {+ self.iter().find_map(|message| message.reasoning_effort())+ }++ fn tool_namespaces(&self) -> Vec<ToolNamespace> {+ self.iter().flat_map(|message| message.tool_namespaces()).collect()+ }+}diff --git a/crates/shoji/src/types/session/chat/mod.rs b/crates/shoji/src/types/session/chat/mod.rsindex cfe4d3bea..6e3c3669f 100644--- a/crates/shoji/src/types/session/chat/mod.rs+++ b/crates/shoji/src/types/session/chat/mod.rs@@ -1,19 +1,15 @@+mod capabilities;mod config;-mod context_length;-mod feature;-mod finish_reason;-mod grammar;-mod output;+mod content_block;+mod message;+mod reply;+mod role;mod speculation_preset;-mod stats;-mod stream_config;-pub use config::Config;-pub use context_length::ContextLength;-pub use feature::Feature;-pub use finish_reason::FinishReason;-pub use grammar::Grammar;-pub use output::Output;-pub use speculation_preset::SpeculationPreset;-pub use stats::Stats;-pub use stream_config::StreamConfig;+pub use capabilities::ChatModelCapabilities;+pub use config::ChatConfig;+pub use content_block::{ChatContentBlock, ChatContentBlockType};+pub use message::{ChatMessage, ChatMessageList, ChatMessageMetadata};+pub use reply::{ChatReply, ChatReplyConfig, ChatReplyFinishReason, ChatReplyStats};+pub use role::ChatRole;+pub use speculation_preset::ChatSpeculationPreset;diff --git a/crates/shoji/src/types/session/chat/output.rs b/crates/shoji/src/types/session/chat/output.rsdeleted file mode 100644index ba6fecb32..000000000--- a/crates/shoji/src/types/session/chat/output.rs+++ /dev/null@@ -1,14 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::types::{- encoding::Message,- session::chat::{FinishReason, Stats},-};--#[bindings::export(Struct, name = "ChatOutput")]-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub struct Output {- pub message: Message,- pub stats: Stats,- pub finish_reason: Option<FinishReason>,-}diff --git a/crates/shoji/src/types/session/chat/stream_config.rs b/crates/shoji/src/types/session/chat/reply/config.rssimilarity index 60%rename from crates/shoji/src/types/session/chat/stream_config.rsrename to crates/shoji/src/types/session/chat/reply/config.rsindex 1fffed2b1..aa87f6785 100644--- a/crates/shoji/src/types/session/chat/stream_config.rs+++ b/crates/shoji/src/types/session/chat/reply/config.rs@@ -1,19 +1,16 @@use serde::{Deserialize, Serialize};-use crate::types::{- basic::{SamplingMethod, SamplingPolicy},- session::chat::Grammar,-};+use crate::types::basic::{Grammar, SamplingMethod, SamplingPolicy};-#[bindings::export(Struct, name = "ChatStreamConfig")]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub struct StreamConfig {+pub struct ChatReplyConfig {pub token_limit: Option<u32>,pub sampling_policy: SamplingPolicy,pub grammar: Option<Grammar>,}-impl Default for StreamConfig {+impl Default for ChatReplyConfig {fn default() -> Self {Self {token_limit: None,@@ -23,46 +20,59 @@ impl Default for StreamConfig {}}-impl StreamConfig {+#[bindings::export(Implementation)]+impl ChatReplyConfig {+ #[bindings::export(Factory)]+ pub fn create() -> Self {+ Self::default()+ }+}++#[bindings::export(Implementation)]+impl ChatReplyConfig {+ #[bindings::export(Method)]pub fn with_token_limit(- self,+ &self,token_limit: Option<u32>,) -> Self {Self {token_limit,- ..self+ ..self.clone()}}+ #[bindings::export(Method)]pub fn with_sampling_policy(- self,+ &self,sampling_policy: SamplingPolicy,) -> Self {Self {sampling_policy,- ..self+ ..self.clone()}}+ #[bindings::export(Method)]pub fn with_sampling_method(- self,+ &self,sampling_method: SamplingMethod,) -> Self {Self {sampling_policy: SamplingPolicy::Custom {method: sampling_method,},- ..self+ ..self.clone()}}+ #[bindings::export(Method)]pub fn with_grammar(- self,+ &self,grammar: Option<Grammar>,) -> Self {Self {grammar,- ..self+ ..self.clone()}}}diff --git a/crates/shoji/src/types/session/chat/finish_reason.rs b/crates/shoji/src/types/session/chat/reply/finish_reason.rssimilarity index 72%rename from crates/shoji/src/types/session/chat/finish_reason.rsrename to crates/shoji/src/types/session/chat/reply/finish_reason.rsindex 694cb1ed8..d2ae4d166 100644--- a/crates/shoji/src/types/session/chat/finish_reason.rs+++ b/crates/shoji/src/types/session/chat/reply/finish_reason.rs@@ -1,8 +1,8 @@use serde::{Deserialize, Serialize};-#[bindings::export(Enum, name = "ChatFinishReason")]+#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]-pub enum FinishReason {+pub enum ChatReplyFinishReason {Stop,Length,Cancelled,diff --git a/crates/shoji/src/types/session/chat/reply/mod.rs b/crates/shoji/src/types/session/chat/reply/mod.rsnew file mode 100644index 000000000..62ff43fa6--- /dev/null+++ b/crates/shoji/src/types/session/chat/reply/mod.rs@@ -0,0 +1,18 @@+mod config;+mod finish_reason;+mod stats;++pub use config::ChatReplyConfig;+pub use finish_reason::ChatReplyFinishReason;+use serde::{Deserialize, Serialize};+pub use stats::ChatReplyStats;++use crate::types::session::chat::ChatMessage;++#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct ChatReply {+ pub message: ChatMessage,+ pub stats: ChatReplyStats,+ pub finish_reason: Option<ChatReplyFinishReason>,+}diff --git a/crates/shoji/src/types/session/chat/stats.rs b/crates/shoji/src/types/session/chat/reply/stats.rssimilarity index 76%rename from crates/shoji/src/types/session/chat/stats.rsrename to crates/shoji/src/types/session/chat/reply/stats.rsindex cb58ad58b..018fd6e7d 100644--- a/crates/shoji/src/types/session/chat/stats.rs+++ b/crates/shoji/src/types/session/chat/reply/stats.rs@@ -1,8 +1,8 @@use serde::{Deserialize, Serialize};-#[bindings::export(Struct, name = "ChatStats")]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]-pub struct Stats {+pub struct ChatReplyStats {pub duration: f64,pub time_to_first_token: Option<f64>,pub prefill_tokens_per_second: Option<f64>,@@ -11,7 +11,9 @@ pub struct Stats {pub tokens_count_output: Option<u32>,}-impl Stats {+#[bindings::export(Implementation)]+impl ChatReplyStats {+ #[bindings::export(Getter)]pub fn tokens_count(&self) -> Option<u32> {self.tokens_count_input.and_then(|input| self.tokens_count_output.map(|output| input + output))}diff --git a/crates/shoji/src/types/encoding/role.rs b/crates/shoji/src/types/session/chat/role.rssimilarity index 58%rename from crates/shoji/src/types/encoding/role.rsrename to crates/shoji/src/types/session/chat/role.rsindex b260cb1dd..8a3bf1eb9 100644--- a/crates/shoji/src/types/encoding/role.rs+++ b/crates/shoji/src/types/session/chat/role.rs@@ -8,7 +8,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer, de};#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Eq, Hash)]-pub enum Role {+pub enum ChatRole {User {},Assistant {},System {},@@ -19,35 +19,35 @@ pub enum Role {},}-impl FromStr for Role {+impl FromStr for ChatRole {type Err = Infallible;fn from_str(s: &str) -> Result<Self, Self::Err> {Ok(match s {- "user" => Role::User {},- "assistant" => Role::Assistant {},- "system" => Role::System {},- "developer" => Role::Developer {},- "tool" => Role::Tool {},- other => Role::Custom {+ "user" => ChatRole::User {},+ "assistant" => ChatRole::Assistant {},+ "system" => ChatRole::System {},+ "developer" => ChatRole::Developer {},+ "tool" => ChatRole::Tool {},+ other => ChatRole::Custom {name: other.to_string(),},})}}-impl Display for Role {+impl Display for ChatRole {fn fmt(&self,formatter: &mut fmt::Formatter<'_>,) -> fmt::Result {let name = match self {- Role::User {} => "user",- Role::Assistant {} => "assistant",- Role::System {} => "system",- Role::Developer {} => "developer",- Role::Tool {} => "tool",- Role::Custom {+ ChatRole::User {} => "user",+ ChatRole::Assistant {} => "assistant",+ ChatRole::System {} => "system",+ ChatRole::Developer {} => "developer",+ ChatRole::Tool {} => "tool",+ ChatRole::Custom {name,} => name,};@@ -55,7 +55,7 @@ impl Display for Role {}}-impl Serialize for Role {+impl Serialize for ChatRole {fn serialize<S: Serializer>(&self,serializer: S,@@ -64,9 +64,9 @@ impl Serialize for Role {}}-impl<'d> Deserialize<'d> for Role {+impl<'d> Deserialize<'d> for ChatRole {fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {let name = String::deserialize(deserializer)?;- Ok(Role::from_str(&name).map_err(de::Error::custom)?)+ Ok(ChatRole::from_str(&name).map_err(de::Error::custom)?)}}diff --git a/crates/shoji/src/types/session/chat/speculation_preset.rs b/crates/shoji/src/types/session/chat/speculation_preset.rsindex 9ec68696c..f18e8fb65 100644--- a/crates/shoji/src/types/session/chat/speculation_preset.rs+++ b/crates/shoji/src/types/session/chat/speculation_preset.rs@@ -1,10 +1,10 @@use serde::{Deserialize, Serialize};-use crate::types::session::chat::Feature;+use crate::types::basic::Feature;-#[bindings::export(Enum, name = "ChatSpeculationPreset")]+#[bindings::export(Enum)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]-pub enum SpeculationPreset {+pub enum ChatSpeculationPreset {GeneralChat {},Summarization {},Classification {diff --git a/crates/shoji/src/types/session/classification/label.rs b/crates/shoji/src/types/session/classification/label.rsindex ed0c90437..72216281a 100644--- a/crates/shoji/src/types/session/classification/label.rs+++ b/crates/shoji/src/types/session/classification/label.rs@@ -1,8 +1,8 @@use serde::{Deserialize, Serialize};-#[bindings::export(Struct)]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub struct Label {+pub struct ClassificationLabel {pub index: i64,pub label: String,pub title: String,diff --git a/crates/shoji/src/types/session/classification/message.rs b/crates/shoji/src/types/session/classification/message.rsnew file mode 100644index 000000000..8b1106e2e--- /dev/null+++ b/crates/shoji/src/types/session/classification/message.rs@@ -0,0 +1,36 @@+use serde::{Deserialize, Serialize};++use crate::types::session::classification::ClassificationRole;++#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct ClassificationMessage {+ pub role: ClassificationRole,+ pub content: String,+}++impl ClassificationMessage {+ pub fn new(+ role: ClassificationRole,+ content: String,+ ) -> Self {+ Self {+ role,+ content,+ }+ }+}++#[bindings::export(Implementation)]+impl ClassificationMessage {+ #[bindings::export(Factory)]+ pub fn user(content: String) -> Self {+ Self::new(ClassificationRole::User, content)+ }++ #[bindings::export(Factory)]+ pub fn assistant(content: String) -> Self {+ Self::new(ClassificationRole::Assistant, content)+ }+}diff --git a/crates/shoji/src/types/session/classification/mod.rs b/crates/shoji/src/types/session/classification/mod.rsindex c0ea53c95..1b63fb030 100644--- a/crates/shoji/src/types/session/classification/mod.rs+++ b/crates/shoji/src/types/session/classification/mod.rs@@ -1,7 +1,11 @@mod label;+mod message;mod output;+mod role;mod stats;-pub use label::Label;-pub use output::Output;-pub use stats::Stats;+pub use label::ClassificationLabel;+pub use message::ClassificationMessage;+pub use output::{ClassificationOutput, ClassificationOutputProbabilities};+pub use role::ClassificationRole;+pub use stats::ClassificationStats;diff --git a/crates/shoji/src/types/session/classification/output.rs b/crates/shoji/src/types/session/classification/output.rsindex 712d53dde..099bbb9d4 100644--- a/crates/shoji/src/types/session/classification/output.rs+++ b/crates/shoji/src/types/session/classification/output.rs@@ -2,12 +2,18 @@ use std::collections::HashMap;use serde::{Deserialize, Serialize};-use crate::types::session::classification::Stats;+use crate::types::session::classification::ClassificationStats;-#[bindings::export(Struct, name = "ClassificationOutput")]+#[bindings::export(Struct)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub struct Output {+pub struct ClassificationOutputProbabilities {+ pub values: HashMap<String, f64>,+}++#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct ClassificationOutput {pub logits: Vec<f64>,- pub probabilities: HashMap<String, f64>,- pub stats: Stats,+ pub probabilities: ClassificationOutputProbabilities,+ pub stats: ClassificationStats,}diff --git a/crates/shoji/src/types/session/classification/role.rs b/crates/shoji/src/types/session/classification/role.rsnew file mode 100644index 000000000..cd0dd954e--- /dev/null+++ b/crates/shoji/src/types/session/classification/role.rs@@ -0,0 +1,8 @@+use serde::{Deserialize, Serialize};++#[bindings::export(Enum)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum ClassificationRole {+ User,+ Assistant,+}diff --git a/crates/shoji/src/types/session/classification/stats.rs b/crates/shoji/src/types/session/classification/stats.rsindex f5a7401cb..27e6939b6 100644--- a/crates/shoji/src/types/session/classification/stats.rs+++ b/crates/shoji/src/types/session/classification/stats.rs@@ -1,8 +1,8 @@use serde::{Deserialize, Serialize};-#[bindings::export(Struct, name = "ClassificationStats")]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub struct Stats {+pub struct ClassificationStats {pub preprocessing_duration: f64,pub forward_pass_duration: f64,pub postprocessing_duration: f64,diff --git a/crates/shoji/src/types/session/text_to_speech/mod.rs b/crates/shoji/src/types/session/text_to_speech/mod.rsindex bfcd648a0..6d46ab369 100644--- a/crates/shoji/src/types/session/text_to_speech/mod.rs+++ b/crates/shoji/src/types/session/text_to_speech/mod.rs@@ -1,5 +1,3 @@-mod pcm_batch;mod stats;-pub use pcm_batch::PcmBatch;-pub use stats::Stats;+pub use stats::TextToSpeechStats;diff --git a/crates/shoji/src/types/session/text_to_speech/pcm_batch.rs b/crates/shoji/src/types/session/text_to_speech/pcm_batch.rsdeleted file mode 100644index c42564d96..000000000--- a/crates/shoji/src/types/session/text_to_speech/pcm_batch.rs+++ /dev/null@@ -1,10 +0,0 @@-use serde::{Deserialize, Serialize};--#[bindings::export(Struct)]-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub struct PcmBatch {- pub samples: Vec<f64>,- pub sample_rate: u32,- pub channels: u32,- pub lengths: Vec<u32>,-}diff --git a/crates/shoji/src/types/session/text_to_speech/stats.rs b/crates/shoji/src/types/session/text_to_speech/stats.rsindex 3bb8efa76..0c31f7471 100644--- a/crates/shoji/src/types/session/text_to_speech/stats.rs+++ b/crates/shoji/src/types/session/text_to_speech/stats.rs@@ -1,15 +1,15 @@use serde::{Deserialize, Serialize};-#[bindings::export(Struct, name = "TextToSpeechStats")]+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub struct Stats {+pub struct TextToSpeechStats {pub text_length: u32,pub first_chunk_seconds: f64,pub generation_duration: f64,pub audio_duration: f64,}-impl Stats {+impl TextToSpeechStats {pub fn real_time_factor(&self) -> f64 {if self.generation_duration <= 0.0 {return 0.0;diff --git a/crates/uzu/Cargo.toml b/crates/uzu/Cargo.tomlindex 967f8cedb..83263135c 100644--- a/crates/uzu/Cargo.toml+++ b/crates/uzu/Cargo.toml@@ -21,16 +21,22 @@ bindings = ["bindings-pyo3","bindings-wasm",]-bindings-uniffi = ["shoji/bindings-uniffi", "dep:uniffi"]+bindings-uniffi = [+ "shoji/bindings-uniffi",+ "nagare/bindings-uniffi",+ "dep:uniffi",+]bindings-napi = ["shoji/bindings-napi",+ "nagare/bindings-napi","dep:napi","dep:napi-derive","dep:napi-build",]-bindings-pyo3 = ["shoji/bindings-pyo3", "dep:pyo3"]+bindings-pyo3 = ["shoji/bindings-pyo3", "nagare/bindings-pyo3", "dep:pyo3"]bindings-wasm = ["shoji/bindings-wasm",+ "nagare/bindings-wasm","dep:wasm-bindgen","dep:serde-wasm-bindgen","dep:wasm-bindgen-futures",@@ -71,6 +77,7 @@ uuid.workspace = truefutures-util.workspace = trueasync-openai.workspace = truefancy-regex.workspace = true+keyring.workspace = true[target.'cfg(target_vendor = "apple")'.dependencies]objc2.workspace = truediff --git a/crates/uzu/examples/quick_start_chat.rs b/crates/uzu/examples/quick_start_chat.rsindex 2c4792126..31082f1c5 100644--- a/crates/uzu/examples/quick_start_chat.rs+++ b/crates/uzu/examples/quick_start_chat.rs@@ -1,25 +1,25 @@-use std::path::PathBuf;--use uzu::session::{- ChatSession,- config::{DecodingConfig, RunConfig},- types::{Input, Output},+use uzu::{+ engine::{Engine, EngineConfig},+ types::session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},};-fn main() -> Result<(), Box<dyn std::error::Error>> {- let model_path = std::env::var("UZU_MODEL_PATH")- .map_err(|_| -> Box<dyn std::error::Error> { "UZU_MODEL_PATH environment variable is not set.".into() })?;- let model_path_buf = PathBuf::from(model_path);- let mut session = ChatSession::new(model_path_buf, DecodingConfig::default())?;+#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error>> {+ let config = EngineConfig::default();+ let engine = Engine::new(config).await?;++ let model = engine.model("alibaba:qwen3:0.6b".to_string()).await?.ok_or("Model not found")?;+ while let Some(update) = engine.download(&model).await?.next().await {+ println!("Downloading: {}", update.progress());+ }++ let session = engine.chat(model, ChatConfig::default()).await?;+ let outputs = session+ .reply(vec![ChatMessage::user().with_text("Tell about London".to_string())], ChatReplyConfig::default())+ .await?;+ for output in outputs {+ println!("{}", output.message.text().unwrap_or_default());+ }- let input = Input::Text(String::from("Tell about London"));- let output = session.run(- input,- RunConfig::default().tokens_limit(128),- Some(|_: Output| {- return true;- }),- )?;- println!("{}", output.text.original);Ok(())}diff --git a/crates/uzu/src/device/error.rs b/crates/uzu/src/device/error.rsindex c8183d2ee..8a59f421f 100644--- a/crates/uzu/src/device/error.rs+++ b/crates/uzu/src/device/error.rs@@ -1,6 +1,7 @@-#[derive(Debug, thiserror::Error)]+#[bindings::export(Error)]+#[derive(Debug, Clone, thiserror::Error)]#[non_exhaustive]-pub enum Error {+pub enum DeviceError {#[error("Unsupported device")]- UnsupportedDevice,+ UnsupportedDevice {},}diff --git a/crates/uzu/src/device/mod.rs b/crates/uzu/src/device/mod.rsindex 970cd0e29..54840a1fa 100644--- a/crates/uzu/src/device/mod.rs+++ b/crates/uzu/src/device/mod.rs@@ -1,40 +1,50 @@mod error;mod os;-use std::path::PathBuf;--pub use error::Error;-use os::{home_path, is_environment_sandboxed};+pub use error::DeviceError;+use os::{home_path, is_environment_sandboxed, is_keyring_available};use serde::{Deserialize, Serialize};use sysinfo::System;+#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Device {pub os_name: Option<String>,pub cpu_name: Option<String>,- pub memory_total: u64,- pub home_path: PathBuf,+ pub memory_total: i64,+ pub home_path: String,pub is_environment_sandboxed: bool,+ pub is_keyring_available: bool,}impl Device {- pub fn new() -> Result<Self, Error> {+ pub fn new() -> Result<Self, DeviceError> {let mut system_info = System::new_all();system_info.refresh_all();let os_name = System::long_os_version();let cpu_name = system_info.cpus().first().map(|cpu| cpu.brand().to_string());let memory_total = system_info.total_memory();- let home_path = home_path().ok_or(Error::UnsupportedDevice)?;+ let home_path = home_path().ok_or(DeviceError::UnsupportedDevice {})?;let is_environment_sandboxed = is_environment_sandboxed();+ let is_keyring_available = is_keyring_available();Ok(Self {os_name,cpu_name,- memory_total,- home_path,+ memory_total: memory_total as i64,+ home_path: home_path.to_string_lossy().to_string(),is_environment_sandboxed,+ is_keyring_available,})}}++#[bindings::export(Implementation)]+impl Device {+ #[bindings::export(Factory)]+ pub fn create() -> Result<Self, DeviceError> {+ Self::new()+ }+}diff --git a/crates/uzu/src/device/os.rs b/crates/uzu/src/device/os.rsindex 19e2a75f8..f01167bca 100644--- a/crates/uzu/src/device/os.rs+++ b/crates/uzu/src/device/os.rs@@ -30,3 +30,24 @@ pub fn is_environment_sandboxed() -> bool {}false}++#[allow(unreachable_code)]+pub fn is_keyring_available() -> bool {+ #[cfg(target_vendor = "apple")]+ {+ use objc2_security::SecTask;++ const CS_VALID: u32 = 0x0000_0001;+ const CS_ADHOC: u32 = 0x0000_0002;+ const CS_LINKER_SIGNED: u32 = 0x0002_0000;++ unsafe {+ let Some(task) = SecTask::from_self(None) else {+ return false;+ };+ let status = task.code_sign_status();+ return (status & CS_VALID) != 0 && (status & CS_ADHOC) == 0 && (status & CS_LINKER_SIGNED) == 0;+ }+ }+ true+}diff --git a/crates/uzu/src/engine/callback.rs b/crates/uzu/src/engine/callback.rsnew file mode 100644index 000000000..a62845440--- /dev/null+++ b/crates/uzu/src/engine/callback.rs@@ -0,0 +1,29 @@+use std::sync::Arc;++pub type EngineCallbackType = Box<dyn Fn() + Send + Sync>;++#[bindings::export(Class)]+#[derive(Clone)]+pub struct EngineCallback {+ callback: Arc<EngineCallbackType>,+}++impl EngineCallback {+ pub fn new(callback: EngineCallbackType) -> Self {+ Self {+ callback: Arc::new(callback),+ }+ }++ pub fn on_event(&self) {+ (self.callback)();+ }+}++#[bindings::export(Implementation)]+impl EngineCallback {+ #[bindings::export(FactoryWithCallback)]+ pub fn create(callback: Box<dyn Fn() + Send + Sync>) -> Self {+ Self::new(callback)+ }+}diff --git a/crates/uzu/src/engine/config.rs b/crates/uzu/src/engine/config.rsindex ac9927576..97d662152 100644--- a/crates/uzu/src/engine/config.rs+++ b/crates/uzu/src/engine/config.rs@@ -2,10 +2,22 @@ use std::env;use serde::{Deserialize, Serialize};-#[bindings::export(Struct)]+use crate::keyring::Keyring;++const KEY_MIRAI_API_KEY: &str = "MIRAI_API_KEY";+const KEY_LALAMO_PATH: &str = "LALAMO_PATH";+const KEY_HF_TOKEN: &str = "HF_TOKEN";+const KEY_OPENAI_API_KEY: &str = "OPENAI_API_KEY";+const KEY_ANTHROPIC_API_KEY: &str = "ANTHROPIC_API_KEY";+const KEY_GEMINI_API_KEY: &str = "GEMINI_API_KEY";+const KEY_XAI_API_KEY: &str = "XAI_API_KEY";+const KEY_BASETEN_API_KEY: &str = "BASETEN_API_KEY";+const KEY_OPENROUTER_API_KEY: &str = "OPENROUTER_API_KEY";++#[bindings::export(ClassCloneable)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]-pub struct Config {+pub struct EngineConfig {pub mirai_api_key: Option<String>,pub lalamo_path: Option<String>,pub huggingface_api_key: Option<String>,@@ -15,94 +27,206 @@ pub struct Config {pub xai_api_key: Option<String>,pub baseten_api_key: Option<String>,pub openrouter_api_key: Option<String>,+ pub allow_ollama_usage: bool,+ pub allow_lmstudio_usage: bool,+}++#[bindings::export(Implementation)]+impl EngineConfig {+ #[bindings::export(Factory)]+ pub fn new() -> Self {+ Self::default()+ }}-impl Default for Config {+impl Default for EngineConfig {fn default() -> Self {+ let keyring = process_env_to_keyring();Self {- mirai_api_key: env::var("MIRAI_API_KEY").ok(),- lalamo_path: env::var("LALAMO_PATH").ok(),- huggingface_api_key: env::var("HF_TOKEN").ok(),- openai_api_key: env::var("OPENAI_API_KEY").ok(),- anthropic_api_key: env::var("ANTHROPIC_API_KEY").ok(),- gemini_api_key: env::var("GEMINI_API_KEY").ok(),- xai_api_key: env::var("XAI_API_KEY").ok(),- baseten_api_key: env::var("BASETEN_API_KEY").ok(),- openrouter_api_key: env::var("OPENROUTER_API_KEY").ok(),+ mirai_api_key: retrieve_keyring_or_env_value(&keyring, KEY_MIRAI_API_KEY),+ lalamo_path: retrieve_keyring_or_env_value(&keyring, KEY_LALAMO_PATH),+ huggingface_api_key: retrieve_keyring_or_env_value(&keyring, KEY_HF_TOKEN),+ openai_api_key: retrieve_keyring_or_env_value(&keyring, KEY_OPENAI_API_KEY),+ anthropic_api_key: retrieve_keyring_or_env_value(&keyring, KEY_ANTHROPIC_API_KEY),+ gemini_api_key: retrieve_keyring_or_env_value(&keyring, KEY_GEMINI_API_KEY),+ xai_api_key: retrieve_keyring_or_env_value(&keyring, KEY_XAI_API_KEY),+ baseten_api_key: retrieve_keyring_or_env_value(&keyring, KEY_BASETEN_API_KEY),+ openrouter_api_key: retrieve_keyring_or_env_value(&keyring, KEY_OPENROUTER_API_KEY),+ allow_ollama_usage: true,+ allow_lmstudio_usage: true,}}}-impl Config {+#[bindings::export(Implementation)]+impl EngineConfig {+ #[bindings::export(Method)]pub fn with_mirai_api_key(- mut self,+ &self,mirai_api_key: String,) -> Self {- self.mirai_api_key = Some(mirai_api_key);- self+ store_keyring_pair(KEY_MIRAI_API_KEY, &mirai_api_key);+ Self {+ mirai_api_key: Some(mirai_api_key),+ ..self.clone()+ }}+ #[bindings::export(Method)]pub fn with_lalamo_path(- mut self,+ &self,lalamo_path: String,) -> Self {- self.lalamo_path = Some(lalamo_path);- self+ store_keyring_pair(KEY_LALAMO_PATH, &lalamo_path);+ Self {+ lalamo_path: Some(lalamo_path),+ ..self.clone()+ }}+ #[bindings::export(Method)]pub fn with_huggingface_api_key(- mut self,+ &self,huggingface_api_key: String,) -> Self {- self.huggingface_api_key = Some(huggingface_api_key);- self+ store_keyring_pair(KEY_HF_TOKEN, &huggingface_api_key);+ Self {+ huggingface_api_key: Some(huggingface_api_key),+ ..self.clone()+ }}+ #[bindings::export(Method)]pub fn with_openai_api_key(- mut self,+ &self,openai_api_key: String,) -> Self {- self.openai_api_key = Some(openai_api_key);- self+ store_keyring_pair(KEY_OPENAI_API_KEY, &openai_api_key);+ Self {+ openai_api_key: Some(openai_api_key),+ ..self.clone()+ }}+ #[bindings::export(Method)]pub fn with_anthropic_api_key(- mut self,+ &self,anthropic_api_key: String,) -> Self {- self.anthropic_api_key = Some(anthropic_api_key);- self+ store_keyring_pair(KEY_ANTHROPIC_API_KEY, &anthropic_api_key);+ Self {+ anthropic_api_key: Some(anthropic_api_key),+ ..self.clone()+ }}+ #[bindings::export(Method)]pub fn with_gemini_api_key(- mut self,+ &self,gemini_api_key: String,) -> Self {- self.gemini_api_key = Some(gemini_api_key);- self+ store_keyring_pair(KEY_GEMINI_API_KEY, &gemini_api_key);+ Self {+ gemini_api_key: Some(gemini_api_key),+ ..self.clone()+ }}+ #[bindings::export(Method)]pub fn with_xai_api_key(- mut self,+ &self,xai_api_key: String,) -> Self {- self.xai_api_key = Some(xai_api_key);- self+ store_keyring_pair(KEY_XAI_API_KEY, &xai_api_key);+ Self {+ xai_api_key: Some(xai_api_key),+ ..self.clone()+ }}+ #[bindings::export(Method)]pub fn with_baseten_api_key(- mut self,+ &self,baseten_api_key: String,) -> Self {- self.baseten_api_key = Some(baseten_api_key);- self+ store_keyring_pair(KEY_BASETEN_API_KEY, &baseten_api_key);+ Self {+ baseten_api_key: Some(baseten_api_key),+ ..self.clone()+ }}+ #[bindings::export(Method)]pub fn with_openrouter_api_key(- mut self,+ &self,openrouter_api_key: String,) -> Self {- self.openrouter_api_key = Some(openrouter_api_key);- self+ store_keyring_pair(KEY_OPENROUTER_API_KEY, &openrouter_api_key);+ Self {+ openrouter_api_key: Some(openrouter_api_key),+ ..self.clone()+ }+ }++ #[bindings::export(Method)]+ pub fn with_allow_ollama_usage(+ &self,+ allow_ollama_usage: bool,+ ) -> Self {+ Self {+ allow_ollama_usage,+ ..self.clone()+ }+ }++ #[bindings::export(Method)]+ pub fn with_allow_lmstudio_usage(+ &self,+ allow_lmstudio_usage: bool,+ ) -> Self {+ Self {+ allow_lmstudio_usage,+ ..self.clone()+ }+ }+}++fn process_env_to_keyring() -> Option<Keyring> {+ let keys = vec![+ KEY_MIRAI_API_KEY,+ KEY_LALAMO_PATH,+ KEY_HF_TOKEN,+ KEY_OPENAI_API_KEY,+ KEY_ANTHROPIC_API_KEY,+ KEY_GEMINI_API_KEY,+ KEY_XAI_API_KEY,+ KEY_BASETEN_API_KEY,+ KEY_OPENROUTER_API_KEY,+ ];++ let keyring = Keyring::new().ok()?;+ for key in keys {+ if let Ok(env_value) = env::var(key) {+ keyring.store(key.to_string(), env_value).ok();+ }+ }+ Some(keyring)+}++fn retrieve_keyring_or_env_value(+ keyring: &Option<Keyring>,+ key: &str,+) -> Option<String> {+ keyring.as_ref().and_then(|keyring| keyring.retrieve(key.to_string())).or_else(|| env::var(key).ok())+}++fn store_keyring_pair(+ key: &str,+ value: &str,+) -> bool {+ if let Ok(keyring) = Keyring::new() {+ keyring.store(key.to_string(), value.to_string()).is_ok()+ } else {+ false}}diff --git a/crates/uzu/src/engine/downloader.rs b/crates/uzu/src/engine/downloader.rsindex 73ec8f0b5..7397b96d7 100644--- a/crates/uzu/src/engine/downloader.rs+++ b/crates/uzu/src/engine/downloader.rs@@ -1,14 +1,16 @@+use serde::{Deserialize, Serialize};use tokio_stream::{StreamExt, wrappers::BroadcastStream};use crate::{- engine::Error,+ engine::EngineError,helpers::SharedAccess,storage::{- Error as StorageError, Storage,+ Storage, StorageError,types::{DownloadPhase, DownloadState},},};+#[bindings::export(Class)]pub struct Downloader {identifier: String,storage: SharedAccess<Storage>,@@ -24,21 +26,28 @@ impl Downloader {storage,}}+}+#[bindings::export(Implementation)]+impl Downloader {+ #[bindings::export(Getter)]pub async fn state(&self) -> Option<DownloadState> {self.storage.lock().await.state(&self.identifier).await}- pub async fn resume(&self) -> Result<(), Error> {+ #[bindings::export(Method)]+ pub async fn resume(&self) -> Result<(), EngineError> {let state = self.state().await.ok_or(StorageError::ItemNotFound {identifier: self.identifier.clone(),})?;let result = match state.phase {- DownloadPhase::Downloading | DownloadPhase::Downloaded => Ok(()),- DownloadPhase::NotDownloaded | DownloadPhase::Paused | DownloadPhase::Locked => {+ DownloadPhase::Downloading {} | DownloadPhase::Downloaded {} => Ok(()),+ DownloadPhase::NotDownloaded {} | DownloadPhase::Paused {} | DownloadPhase::Locked {} => {Ok(self.storage.lock().await.download(&self.identifier).await?)},- DownloadPhase::Error(_) => {+ DownloadPhase::Error {+ ..+ } => {let storage = self.storage.lock().await;storage.delete(&self.identifier).await?;Ok(storage.download(&self.identifier).await?)@@ -47,33 +56,37 @@ impl Downloader {result}- pub async fn pause(&self) -> Result<(), Error> {+ #[bindings::export(Method)]+ pub async fn pause(&self) -> Result<(), EngineError> {Ok(self.storage.lock().await.pause(&self.identifier).await?)}- pub async fn delete(&self) -> Result<(), Error> {+ #[bindings::export(Method)]+ pub async fn delete(&self) -> Result<(), EngineError> {Ok(self.storage.lock().await.delete(&self.identifier).await?)}- pub async fn progress(&self) -> Option<Stream> {+ #[bindings::export(Method)]+ pub async fn progress(&self) -> Result<DownloaderStream, EngineError> {let identifier = self.identifier.clone();let Some(state) = self.state().await else {- return None;+ return Err(EngineError::UnableToGetDownloaderProgressStream {});};- if matches!(state.phase, DownloadPhase::Downloaded) {- return None;+ if matches!(state.phase, DownloadPhase::Downloaded {}) {+ return Err(EngineError::UnableToGetDownloaderProgressStream {});}let stream = self.storage.lock().await.subscribe();- Some(Stream::new(identifier, stream))+ Ok(DownloaderStream::new(identifier, stream))}}-pub struct Stream {+#[bindings::export(Class)]+pub struct DownloaderStream {identifier: String,stream: SharedAccess<Option<BroadcastStream<(String, DownloadState)>>>,}-impl Stream {+impl DownloaderStream {pub(crate) fn new(identifier: String,stream: BroadcastStream<(String, DownloadState)>,@@ -84,22 +97,35 @@ impl Stream {}}- pub async fn next(&self) -> Option<Update> {+ pub(crate) fn empty(identifier: String) -> Self {+ Self {+ identifier,+ stream: SharedAccess::new(None),+ }+ }+}++#[bindings::export(Implementation)]+impl DownloaderStream {+ #[bindings::export(Method)]+ pub async fn next(&self) -> Option<DownloaderStreamUpdate> {let mut stream_guard = self.stream.lock().await;let stream = stream_guard.as_mut()?;while let Some(result) = stream.next().await {if let Ok((identifier, state)) = result {if identifier == self.identifier {- let update = Update {+ let update = DownloaderStreamUpdate {bytes_total: state.total_bytes,bytes_downloaded: state.downloaded_bytes,};match state.phase {- DownloadPhase::Downloading | DownloadPhase::Locked => {},- DownloadPhase::NotDownloaded- | DownloadPhase::Downloaded- | DownloadPhase::Error(_)- | DownloadPhase::Paused => {+ DownloadPhase::Downloading {} | DownloadPhase::Locked {} => {},+ DownloadPhase::NotDownloaded {}+ | DownloadPhase::Downloaded {}+ | DownloadPhase::Error {+ ..+ }+ | DownloadPhase::Paused {} => {*stream_guard = None;},}@@ -111,12 +137,16 @@ impl Stream {}}-pub struct Update {- pub bytes_total: u64,- pub bytes_downloaded: u64,+#[bindings::export(ClassCloneable)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub struct DownloaderStreamUpdate {+ pub bytes_total: i64,+ pub bytes_downloaded: i64,}-impl Update {+#[bindings::export(Implementation)]+impl DownloaderStreamUpdate {+ #[bindings::export(Getter)]pub fn progress(&self) -> f32 {if self.bytes_total == 0 {0.0diff --git a/crates/uzu/src/engine/error.rs b/crates/uzu/src/engine/error.rsindex 466beea22..1f0beca6b 100644--- a/crates/uzu/src/engine/error.rs+++ b/crates/uzu/src/engine/error.rs@@ -1,22 +1,29 @@-use nagare::chat::Error as ChatError;--#[derive(Debug, thiserror::Error)]+#[bindings::export(Error)]+#[derive(Debug, Clone, thiserror::Error)]#[non_exhaustive]-pub enum Error {+pub enum EngineError {#[error("Tokio error: {message}")]TokioError {message: String,},#[error(transparent)]- Device(#[from] crate::device::Error),+ Device(#[from] crate::device::DeviceError),#[error(transparent)]- Storage(#[from] crate::storage::Error),+ Keyring(#[from] crate::keyring::KeyringError),#[error(transparent)]- Registry(#[from] crate::registry::Error),+ Storage(#[from] crate::storage::StorageError),+ #[error(transparent)]+ Registry(#[from] crate::registry::RegistryError),#[error("Unable to create backend")]- UnableToCreateBackend,+ UnableToCreateBackend {},#[error("Backend not found")]- BackendNotFound,+ BackendNotFound {},+ #[error("Unable to get downloader progress stream")]+ UnableToGetDownloaderProgressStream {},+ #[error(transparent)]+ ChatSession(#[from] nagare::chat::ChatSessionError),+ #[error(transparent)]+ ClassificationSession(#[from] nagare::classification::ClassificationSessionError),#[error(transparent)]- Chat(#[from] ChatError),+ TextToSpeechSession(#[from] nagare::text_to_speech::TextToSpeechSessionError),}diff --git a/crates/uzu/src/engine/mod.rs b/crates/uzu/src/engine/mod.rsindex ebb32d55f..2d88d608a 100644--- a/crates/uzu/src/engine/mod.rs+++ b/crates/uzu/src/engine/mod.rs@@ -1,3 +1,4 @@+mod callback;mod config;mod downloader;mod error;@@ -5,24 +6,25 @@ mod error;use std::{collections::HashMap, sync::Arc};use backend_remote::openai::Backend as OpenAIBackend;-use backend_uzu::inference_backend::Backend as UzuBackend;-pub use config::Config;-pub use downloader::Downloader;-pub use error::Error;-use nagare::chat::Session as ChatSession;+use backend_uzu::inference::Backend as UzuBackend;+pub use callback::{EngineCallback, EngineCallbackType};+pub use config::EngineConfig;+pub use downloader::{Downloader, DownloaderStream, DownloaderStreamUpdate};+pub use error::EngineError;+use nagare::{chat::ChatSession, classification::ClassificationSession, text_to_speech::TextToSpeechSession};use shoji::{traits::{Backend, Registry},- types::{model::Model, session::chat::Config as ChatConfig},+ types::{model::Model, session::chat::ChatConfig},};use tokio::runtime::Handle;-use tokio_stream::wrappers::BroadcastStream;+use tokio_stream::{StreamExt, wrappers::BroadcastStream};use crate::{device::Device,helpers::{SharedAccess, is_endpoint_reachable},logs,registry::{- CachedRegistry, Error as RegistryError, MergedRegistry,+ CachedRegistry, MergedRegistry, RegistryError,local::{Config as LocalRegistryConfig, Registry as LocalRegistry},mirai::{Backend as MiraiBackend, Config as MiraiRegistryConfig, Registry as MiraiRegistry},openai::{Config as OpenAIConfig, Registry as OpenAIRegistry},@@ -33,15 +35,17 @@ use crate::{},};+#[bindings::export(Class)]pub struct Engine {registry: SharedAccess<MergedRegistry>,storage: SharedAccess<Storage>,- backends: HashMap<String, Arc<dyn Backend>>,+ backends: SharedAccess<HashMap<String, Arc<dyn Backend>>>,+ callback: SharedAccess<Option<Arc<EngineCallback>>>,}impl Engine {- pub async fn new(config: Config) -> Result<Self, Error> {- let tokio_handle = Handle::try_current().map_err(|error| Error::TokioError {+ pub async fn new(config: EngineConfig) -> Result<Self, EngineError> {+ let tokio_handle = Handle::try_current().map_err(|error| EngineError::TokioError {message: error.to_string(),})?;@@ -52,14 +56,16 @@ impl Engine {let storage = SharedAccess::new(Storage::new(tokio_handle.clone(), storage_config).await?);- let mut engine = Self {+ let engine = Self {storage,registry,- backends: HashMap::new(),+ backends: SharedAccess::new(HashMap::new()),+ callback: SharedAccess::new(None),};+ engine.spawn_storage_listener().await;{- let uzu_backend = UzuBackend::new().map_err(|_| Error::UnableToCreateBackend)?;+ let uzu_backend = UzuBackend::new();let uzu_backend_identifier = uzu_backend.identifier();let uzu_backend_version = uzu_backend.version();@@ -68,30 +74,33 @@ impl Engine {device: device.clone(),backends: vec![MiraiBackend {identifier: uzu_backend_identifier.clone(),- version: uzu_backend_version,+ version: uzu_backend_version.clone(),}],include_traces: false,};let mirai_registry = Box::new(MiraiRegistry::new(mirai_registry_config)?);- engine.add_backend(Arc::new(uzu_backend) as Arc<dyn Backend>);+ engine.add_backend(Arc::new(uzu_backend) as Arc<dyn Backend>).await;engine.add_registry(mirai_registry).await?;if let Some(lalamo_path) = config.lalamo_path {- let lalamo_registry =- LocalRegistry::new(LocalRegistryConfig::lalamo(uzu_backend_identifier, lalamo_path))?;+ let lalamo_registry = LocalRegistry::new(LocalRegistryConfig::lalamo(+ uzu_backend_identifier,+ uzu_backend_version,+ lalamo_path,+ ))?;engine.add_registry(Box::new(lalamo_registry)).await?;}}let mut openai_configs: Vec<OpenAIConfig> = vec![];- {+ if config.allow_ollama_usage {let ollama_config = OpenAIConfig::ollama();if is_endpoint_reachable(&ollama_config.api_endpoint).await {openai_configs.push(ollama_config);}}- {+ if config.allow_lmstudio_usage {let lmstudio_config = OpenAIConfig::lmstudio();if is_endpoint_reachable(&lmstudio_config.api_endpoint).await {openai_configs.push(lmstudio_config);@@ -117,87 +126,187 @@ impl Engine {}for config in openai_configs {let registry = OpenAIRegistry::new(config.clone())?;- let backend = OpenAIBackend::new(config.into()).map_err(|_| Error::UnableToCreateBackend)?;+ let backend = OpenAIBackend::new(config.into()).map_err(|_| EngineError::UnableToCreateBackend {})?;engine.add_registry(Box::new(registry)).await?;- engine.add_backend(Arc::new(backend) as Arc<dyn Backend>);+ engine.add_backend(Arc::new(backend) as Arc<dyn Backend>).await;}Ok(engine)}}+#[bindings::export(Implementation)]+impl Engine {+ #[bindings::export(Factory)]+ pub async fn create(config: EngineConfig) -> Result<Self, EngineError> {+ Self::new(config).await+ }+}++#[bindings::export(Implementation)]+impl Engine {+ #[bindings::export(Method)]+ pub async fn register_callback(+ &self,+ callback: &EngineCallback,+ ) -> Result<(), EngineError> {+ self.callback.lock().await.replace(Arc::new(callback.clone()));+ Ok(())+ }+}+impl Engine {pub async fn add_registry(&self,registry: Box<dyn Registry<Error = RegistryError>>,- ) -> Result<(), Error> {+ ) -> Result<(), EngineError> {self.registry.lock().await.add(Box::new(CachedRegistry::new(registry)))?;self.handle_registry_resfresh().await?;Ok(())}- pub async fn remove_registry(+ pub async fn add_backend(&self,- registry_identifier: &str,- ) -> Result<(), Error> {- self.registry.lock().await.remove(registry_identifier)?;- self.handle_registry_resfresh().await?;- Ok(())+ backend: Arc<dyn Backend>,+ ) {+ self.backends.lock().await.insert(backend.identifier(), backend);}}+#[bindings::export(Implementation)]impl Engine {- pub fn add_backend(- &mut self,- backend: Arc<dyn Backend>,- ) {- self.backends.insert(backend.identifier(), backend);+ #[bindings::export(Method)]+ pub async fn remove_registry(+ &self,+ registry_identifier: String,+ ) -> Result<(), EngineError> {+ self.registry.lock().await.remove(®istry_identifier)?;+ self.handle_registry_resfresh().await?;+ Ok(())}- pub fn remove_backend(- &mut self,- identifier: &str,+ #[bindings::export(Method)]+ pub async fn remove_backend(+ &self,+ identifier: String,) {- self.backends.remove(identifier);+ self.backends.lock().await.remove(&identifier);}}+#[bindings::export(Implementation)]impl Engine {- pub async fn models(&self) -> Result<Vec<Model>, Error> {- self.registry.lock().await.models().await.map_err(Error::from)+ #[bindings::export(Getter)]+ pub async fn models(&self) -> Result<Vec<Model>, EngineError> {+ self.registry.lock().await.models().await.map_err(EngineError::from)+ }++ #[bindings::export(Getter)]+ pub async fn models_local(&self) -> Result<Vec<Model>, EngineError> {+ Ok(self.models().await?.into_iter().filter(|model| model.is_local()).collect())+ }++ #[bindings::export(Getter)]+ pub async fn models_remote(&self) -> Result<Vec<Model>, EngineError> {+ Ok(self.models().await?.into_iter().filter(|model| model.is_remote()).collect())}+ #[bindings::export(Getter)]+ pub async fn models_downloadable(&self) -> Result<Vec<Model>, EngineError> {+ Ok(self.models().await?.into_iter().filter(|model| model.is_downloadable()).collect())+ }++ #[bindings::export(Getter)]+ pub async fn models_for_chat(&self) -> Result<Vec<Model>, EngineError> {+ Ok(self.models().await?.into_iter().filter(|model| model.is_chat_capable()).collect())+ }++ #[bindings::export(Getter)]+ pub async fn models_for_classification(&self) -> Result<Vec<Model>, EngineError> {+ Ok(self.models().await?.into_iter().filter(|model| model.is_classification_capable()).collect())+ }++ #[bindings::export(Getter)]+ pub async fn models_for_text_to_speech(&self) -> Result<Vec<Model>, EngineError> {+ Ok(self.models().await?.into_iter().filter(|model| model.is_text_to_speech_capable()).collect())+ }++ #[bindings::export(Getter)]+ pub async fn models_for_translation(&self) -> Result<Vec<Model>, EngineError> {+ Ok(self.models().await?.into_iter().filter(|model| model.is_translation_capable()).collect())+ }++ #[bindings::export(Getter)]+ pub async fn models_for_speculation(&self) -> Result<Vec<Model>, EngineError> {+ Ok(self.models().await?.into_iter().filter(|model| model.is_speculation_capable()).collect())+ }++ #[bindings::export(Method)]+ pub async fn models_by_vendor(+ &self,+ vendor_identifier: String,+ ) -> Result<Vec<Model>, EngineError> {+ Ok(self+ .models()+ .await?+ .into_iter()+ .filter(|model| {+ model.family.as_ref().map(|family| family.vendor.identifier == vendor_identifier).unwrap_or(false)+ })+ .collect())+ }++ #[bindings::export(Method)]+ pub async fn models_by_family(+ &self,+ family_identifier: String,+ ) -> Result<Vec<Model>, EngineError> {+ Ok(self+ .models()+ .await?+ .into_iter()+ .filter(|model| model.family.as_ref().map(|family| family.identifier == family_identifier).unwrap_or(false))+ .collect())+ }+}++#[bindings::export(Implementation)]+impl Engine {+ #[bindings::export(Method)]pub async fn model(&self,- identifier: &str,- ) -> Result<Option<Model>, Error> {- if let Some(model) = self.model_by_identifier(identifier).await? {+ identifier: String,+ ) -> Result<Option<Model>, EngineError> {+ if let Some(model) = self.model_by_identifier(identifier.clone()).await? {return Ok(Some(model));}- if let Some(model) = self.model_by_repo_id(identifier).await? {+ if let Some(model) = self.model_by_repo_id(identifier.clone()).await? {return Ok(Some(model));}- self.model_by_path(identifier).await+ self.model_by_path(identifier.clone()).await}+ #[bindings::export(Method)]pub async fn model_by_identifier(&self,- identifier: &str,- ) -> Result<Option<Model>, Error> {- self.registry.lock().await.model_by_identifier(identifier).await.map_err(Error::from)+ identifier: String,+ ) -> Result<Option<Model>, EngineError> {+ self.registry.lock().await.model_by_identifier(&identifier).await.map_err(EngineError::from)}+ #[bindings::export(Method)]pub async fn model_by_repo_id(&self,- repo_id: &str,- ) -> Result<Option<Model>, Error> {- self.registry.lock().await.model_by_repo_id(repo_id).await.map_err(Error::from)+ repo_id: String,+ ) -> Result<Option<Model>, EngineError> {+ self.registry.lock().await.model_by_repo_id(&repo_id).await.map_err(EngineError::from)}+ #[bindings::export(Method)]pub async fn model_by_path(&self,- path: &str,- ) -> Result<Option<Model>, Error> {+ path: String,+ ) -> Result<Option<Model>, EngineError> {let models = self.models().await?;for model in models {if let Some(model_path) = self.model_path(&model).await {@@ -210,18 +319,9 @@ impl Engine {}}+#[bindings::export(Implementation)]impl Engine {- pub fn downloader(- &self,- model: &Model,- ) -> Downloader {- Downloader::new(model.identifier(), self.storage.clone())- }-- pub async fn storage_subscribe(&self) -> BroadcastStream<(String, DownloadState)> {- self.storage.lock().await.subscribe()- }-+ #[bindings::export(Method)]pub async fn model_path(&self,model: &Model,@@ -231,16 +331,18 @@ impl Engine {Some(local_external_path.clone())} else {let storage = self.storage.lock().await;- let state = storage.state(&model.identifier()).await?;+ let state = storage.state(&model.identifier.clone()).await?;match state.phase {- DownloadPhase::Downloaded => {+ DownloadPhase::Downloaded {} => {storage.config.cache_model_path(model).map(|path| path.to_string_lossy().to_string())},- DownloadPhase::NotDownloaded- | DownloadPhase::Downloading- | DownloadPhase::Paused- | DownloadPhase::Locked- | DownloadPhase::Error(_) => None,+ DownloadPhase::NotDownloaded {}+ | DownloadPhase::Downloading {}+ | DownloadPhase::Paused {}+ | DownloadPhase::Locked {}+ | DownloadPhase::Error {+ ..+ } => None,}}} else {@@ -249,26 +351,121 @@ impl Engine {path}- async fn handle_registry_resfresh(&self) -> Result<(), Error> {- let models = self.registry.lock().await.models().await?;- self.storage.lock().await.refresh(models).await?;- Ok(())+ #[bindings::export(Method)]+ pub fn downloader(+ &self,+ model: &Model,+ ) -> Downloader {+ Downloader::new(model.identifier.clone(), self.storage.clone())+ }++ #[bindings::export(Method)]+ pub async fn download(+ &self,+ model: &Model,+ ) -> Result<DownloaderStream, EngineError> {+ if !model.is_downloadable() {+ return Ok(DownloaderStream::empty(model.identifier.clone()));+ }++ let downloader = self.downloader(model);+ let Some(state) = downloader.state().await else {+ return Err(EngineError::UnableToGetDownloaderProgressStream {});+ };+ if matches!(state.phase, DownloadPhase::Downloaded {}) {+ return Ok(DownloaderStream::empty(model.identifier.clone()));+ }+ downloader.resume().await?;+ Ok(downloader.progress().await?)+ }++ #[bindings::export(Method)]+ pub async fn download_state(+ &self,+ model: &Model,+ ) -> Option<DownloadState> {+ self.downloader(model).state().await}}+#[bindings::export(Implementation)]impl Engine {+ #[bindings::export(Method)]pub async fn chat(&self,model: Model,config: ChatConfig,- ) -> Result<ChatSession, Error> {+ ) -> Result<ChatSession, EngineError> {let path = self.model_path(&model).await;- if let Some(backend_entity) = model.backend_entity() {- let backend = self.backends.get(&backend_entity.identifier).ok_or(Error::BackendNotFound)?;+ if let Some(backend) = model.backends.first() {+ let backends = self.backends.lock().await;+ let backend = backends.get(&backend.identifier).ok_or(EngineError::BackendNotFound {})?;let session = ChatSession::new(backend.as_ref(), config, model, path).await?;Ok(session)} else {- return Err(Error::BackendNotFound);+ return Err(EngineError::BackendNotFound {});+ }+ }++ #[bindings::export(Method)]+ pub async fn classification(+ &self,+ model: Model,+ ) -> Result<ClassificationSession, EngineError> {+ let path = self.model_path(&model).await;+ if let Some(backend) = model.backends.first() {+ let backends = self.backends.lock().await;+ let backend = backends.get(&backend.identifier).ok_or(EngineError::BackendNotFound {})?;+ let session = ClassificationSession::new(backend.as_ref(), model, path).await?;+ Ok(session)+ } else {+ return Err(EngineError::BackendNotFound {});+ }+ }++ #[bindings::export(Method)]+ pub async fn text_to_speech(+ &self,+ model: Model,+ ) -> Result<TextToSpeechSession, EngineError> {+ let path = self.model_path(&model).await;+ if let Some(backend) = model.backends.first() {+ let backends = self.backends.lock().await;+ let backend = backends.get(&backend.identifier).ok_or(EngineError::BackendNotFound {})?;+ let session = TextToSpeechSession::new(backend.as_ref(), model, path).await?;+ Ok(session)+ } else {+ return Err(EngineError::BackendNotFound {});}}}++impl Engine {+ pub async fn storage_subscribe(&self) -> BroadcastStream<(String, DownloadState)> {+ self.storage.lock().await.subscribe()+ }++ async fn handle_registry_resfresh(&self) -> Result<(), EngineError> {+ let models = self.registry.lock().await.models().await?;+ self.storage.lock().await.refresh(models).await?;+ if let Some(callback) = self.callback.lock().await.as_ref().cloned() {+ callback.on_event();+ };+ Ok(())+ }++ async fn spawn_storage_listener(&self) {+ let mut stream = self.storage_subscribe().await;+ let callback = self.callback.clone();+ tokio::spawn(async move {+ while let Some(update) = stream.next().await {+ if update.is_err() {+ continue;+ }+ if let Some(callback) = callback.lock().await.as_ref().cloned() {+ callback.on_event();+ };+ }+ });+ }+}diff --git a/crates/uzu/src/keyring/error.rs b/crates/uzu/src/keyring/error.rsnew file mode 100644index 000000000..936914a78--- /dev/null+++ b/crates/uzu/src/keyring/error.rs@@ -0,0 +1,11 @@+#[bindings::export(Error)]+#[derive(Debug, Clone, thiserror::Error)]+#[non_exhaustive]+pub enum KeyringError {+ #[error("Backend error: {message}")]+ BackendError {+ message: String,+ },+ #[error(transparent)]+ Device(#[from] crate::device::DeviceError),+}diff --git a/crates/uzu/src/keyring/mod.rs b/crates/uzu/src/keyring/mod.rsnew file mode 100644index 000000000..55d851336--- /dev/null+++ b/crates/uzu/src/keyring/mod.rs@@ -0,0 +1,101 @@+mod error;++use std::collections::HashMap;++pub use error::KeyringError;+use keyring::{Entry, Error as BackendError};++use crate::device::Device;++const SERVICE_NAME: &str = "com.trymirai.keyring";+const BASE_KEY: &str = "keys";++#[bindings::export(Class)]+pub struct Keyring {+ device: Device,+}++impl Keyring {+ pub fn new() -> Result<Self, KeyringError> {+ Ok(Self {+ device: Device::new()?,+ })+ }++ fn entry() -> Result<Entry, KeyringError> {+ Entry::new(SERVICE_NAME, BASE_KEY).map_err(|error| KeyringError::BackendError {+ message: error.to_string(),+ })+ }++ fn load() -> Result<HashMap<String, String>, KeyringError> {+ let entry = Self::entry()?;+ match entry.get_password() {+ Ok(value) => serde_json::from_str(&value).map_err(|error| KeyringError::BackendError {+ message: error.to_string(),+ }),+ Err(BackendError::NoEntry) => Ok(HashMap::new()),+ Err(error) => Err(KeyringError::BackendError {+ message: error.to_string(),+ }),+ }+ }++ fn save(entries: &HashMap<String, String>) -> Result<(), KeyringError> {+ let entry = Self::entry()?;+ let value = serde_json::to_string(entries).map_err(|error| KeyringError::BackendError {+ message: error.to_string(),+ })?;+ entry.set_password(&value).map_err(|error| KeyringError::BackendError {+ message: error.to_string(),+ })+ }+}++#[bindings::export(Implementation)]+impl Keyring {+ #[bindings::export(Factory)]+ pub fn create() -> Result<Self, KeyringError> {+ Self::new()+ }++ #[bindings::export(Method)]+ pub fn store(+ &self,+ key: String,+ value: String,+ ) -> Result<(), KeyringError> {+ if !self.device.is_keyring_available {+ return Ok(());+ }+ let mut entries = Self::load()?;+ entries.insert(key, value);+ Self::save(&entries)+ }++ #[bindings::export(Method)]+ pub fn retrieve(+ &self,+ key: String,+ ) -> Option<String> {+ if !self.device.is_keyring_available {+ return None;+ }+ Self::load().ok()?.get(&key).cloned()+ }++ #[bindings::export(Method)]+ pub fn remove(+ &self,+ key: String,+ ) -> Result<(), KeyringError> {+ if !self.device.is_keyring_available {+ return Ok(());+ }+ let mut entries = Self::load()?;+ if entries.remove(&key).is_some() {+ Self::save(&entries)?;+ }+ Ok(())+ }+}diff --git a/crates/uzu/src/lib.rs b/crates/uzu/src/lib.rsindex fdc2767d0..3909b5212 100644--- a/crates/uzu/src/lib.rs+++ b/crates/uzu/src/lib.rs@@ -1,6 +1,8 @@#[cfg(feature = "bindings-uniffi")]shoji::uniffi_reexport_scaffolding!();#[cfg(feature = "bindings-uniffi")]+nagare::uniffi_reexport_scaffolding!();+#[cfg(feature = "bindings-uniffi")]uniffi::setup_scaffolding!();#[cfg(not(target_family = "wasm"))]@@ -10,10 +12,14 @@ pub mod engine;#[cfg(not(target_family = "wasm"))]pub mod helpers;#[cfg(not(target_family = "wasm"))]+pub mod keyring;+#[cfg(not(target_family = "wasm"))]pub mod logs;#[cfg(not(target_family = "wasm"))]pub mod registry;#[cfg(not(target_family = "wasm"))]pub mod storage;--pub use backend_uzu::*;+#[cfg(not(target_family = "wasm"))]+pub use nagare as session;+#[cfg(not(target_family = "wasm"))]+pub use shoji::*;diff --git a/crates/uzu/src/registry/cached.rs b/crates/uzu/src/registry/cached.rsindex 08b2055c7..d76896751 100644--- a/crates/uzu/src/registry/cached.rs+++ b/crates/uzu/src/registry/cached.rs@@ -3,15 +3,15 @@ use std::{future::Future, pin::Pin};use shoji::{traits::Registry, types::model::Model};use tokio::sync::Mutex;-use crate::registry::Error;+use crate::registry::RegistryError;pub struct CachedRegistry {- registry: Box<dyn Registry<Error = Error>>,+ registry: Box<dyn Registry<Error = RegistryError>>,models: Mutex<Option<Vec<Model>>>,}impl CachedRegistry {- pub fn new(registry: Box<dyn Registry<Error = Error>>) -> Self {+ pub fn new(registry: Box<dyn Registry<Error = RegistryError>>) -> Self {Self {registry,models: Mutex::new(None),@@ -25,13 +25,13 @@ impl CachedRegistry {}impl Registry for CachedRegistry {- type Error = Error;+ type Error = RegistryError;fn indentifier(&self) -> String {self.registry.indentifier()}- fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, Error>> + Send + '_>> {+ fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, RegistryError>> + Send + '_>> {Box::pin(async {let mut cached_models = self.models.lock().await;if let Some(cached_models) = cached_models.as_ref() {diff --git a/crates/uzu/src/registry/error.rs b/crates/uzu/src/registry/error.rsindex 36792f18a..f099d3c33 100644--- a/crates/uzu/src/registry/error.rs+++ b/crates/uzu/src/registry/error.rs@@ -1,6 +1,7 @@-#[derive(Debug, thiserror::Error)]+#[bindings::export(Error)]+#[derive(Debug, Clone, thiserror::Error)]#[non_exhaustive]-pub enum Error {+pub enum RegistryError {#[error("Unable to create: {message}")]UnableToCreate {message: String,diff --git a/crates/uzu/src/registry/fixed.rs b/crates/uzu/src/registry/fixed.rsindex a7df1003a..c777b1890 100644--- a/crates/uzu/src/registry/fixed.rs+++ b/crates/uzu/src/registry/fixed.rs@@ -3,7 +3,7 @@ use std::{future::Future, pin::Pin};use shoji::{traits::Registry, types::model::Model};use tokio::sync::Mutex;-use crate::registry::Error;+use crate::registry::RegistryError;pub struct FixedRegistry {identifier: String,@@ -23,13 +23,13 @@ impl FixedRegistry {}impl Registry for FixedRegistry {- type Error = Error;+ type Error = RegistryError;fn indentifier(&self) -> String {self.identifier.clone()}- fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, Error>> + Send + '_>> {+ fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, RegistryError>> + Send + '_>> {Box::pin(async {return Ok(self.models.lock().await.clone());})diff --git a/crates/uzu/src/registry/local/config.rs b/crates/uzu/src/registry/local/config.rsindex dcf3f590b..3773d8d89 100644--- a/crates/uzu/src/registry/local/config.rs+++ b/crates/uzu/src/registry/local/config.rs@@ -1,41 +1,84 @@-use std::path::PathBuf;+use std::{path::PathBuf, sync::Arc};-use serde::{Deserialize, Serialize};+use backend_uzu::inference::resolve_model_metadata;+use shoji::types::model::Model;-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]+pub type ModelResolver = Arc<dyn Fn(Model) -> Option<Model> + Send + Sync>;++#[derive(Clone)]pub struct Config {pub identifier: String,pub backend_identifier: String,+ pub backend_version: String,pub name: String,pub path: String,+ pub resolver: Option<ModelResolver>,}impl Config {pub fn new(identifier: String,backend_identifier: String,+ backend_version: String,name: String,path: String,+ resolver: Option<ModelResolver>,) -> Self {Self {identifier,backend_identifier,+ backend_version,name,path,+ resolver,}}pub fn lalamo(backend_identifier: String,+ backend_version: String,path: String,) -> Self {let models_path = PathBuf::from(&path).join("models");+ let resolver: ModelResolver = {+ let backend_version = backend_version.clone();+ Arc::new(move |mut model: Model| -> Option<Model> {+ let model_path = PathBuf::from(model.local_external_path()?);+ let metadata = resolve_model_metadata(&model_path)?;+ if !is_lalamo_version_supported(&metadata.toolchain_version, &backend_version) {+ return None;+ }+ model.specializations = vec![metadata.specialization];+ Some(model)+ })+ };Self::new("lalamo".to_string(),backend_identifier,+ backend_version,"Lalamo".to_string(),models_path.to_string_lossy().to_string(),+ Some(resolver),)}}++fn is_lalamo_version_supported(+ model_version: &str,+ backend_version: &str,+) -> bool {+ let parse_version = |value: &str| -> Option<(u32, u32, u32)> {+ let mut parts = value.split('.').map(|part| part.parse::<u32>().ok());+ let major = parts.next().flatten()?;+ let minor = parts.next().flatten()?;+ let patch = parts.next().flatten()?;+ Some((major, minor, patch))+ };+ let Some((model_major, model_minor, model_patch)) = parse_version(model_version) else {+ return false;+ };+ let Some((backend_major, backend_minor, backend_patch)) = parse_version(backend_version) else {+ return false;+ };+ model_major == backend_major && model_minor == backend_minor && model_patch <= backend_patch+}diff --git a/crates/uzu/src/registry/local/mod.rs b/crates/uzu/src/registry/local/mod.rsindex 11d522878..b3fcbbdbc 100644--- a/crates/uzu/src/registry/local/mod.rs+++ b/crates/uzu/src/registry/local/mod.rs@@ -5,17 +5,17 @@ use std::{fs, future::Future, path::Path, pin::Pin};pub use config::Config;use shoji::{traits::Registry as RegistryTrait,- types::model::{Accessibility, Entity, EntityType, Model, Reference, Specialization},+ types::model::{Model, ModelAccessibility, ModelReference, ModelSpecialization},};-use crate::registry::Error;+use crate::registry::RegistryError;pub struct Registry {config: Config,}impl Registry {- pub fn new(config: Config) -> Result<Self, Error> {+ pub fn new(config: Config) -> Result<Self, RegistryError> {Ok(Self {config,})@@ -23,22 +23,22 @@ impl Registry {}impl RegistryTrait for Registry {- type Error = Error;+ type Error = RegistryError;fn indentifier(&self) -> String {self.config.identifier.clone()}- fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, Error>> + Send + '_>> {+ fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, RegistryError>> + Send + '_>> {Box::pin(async {let path = Path::new(&self.config.path);if !path.exists() {- Err(Error::UnableToGetModels {+ Err(RegistryError::UnableToGetModels {message: format!("Path not found: {}", path.display()),})?;}- let entries = fs::read_dir(path).map_err(|error| Error::UnableToGetModels {+ let entries = fs::read_dir(path).map_err(|error| RegistryError::UnableToGetModels {message: error.to_string(),})?;@@ -54,7 +54,15 @@ impl RegistryTrait for Registry {let Some(name) = path.file_name().and_then(|name| name.to_str()) else {continue;};- models.push(self.model(name));++ let model = self.model(name);+ let model = match self.config.resolver.as_ref() {+ Some(resolver) => resolver(model),+ None => Some(model),+ };+ if let Some(model) = model {+ models.push(model);+ }}Ok(models)@@ -69,40 +77,19 @@ impl Registry {) -> Model {let path = Path::new(&self.config.path).join(name);let identifier = name.to_string();- Model {- identifier: identifier.clone(),- entities: vec![- self.entity(EntityType::Registry, &self.config.identifier, &self.config.name),- self.entity(EntityType::Backend, &self.config.backend_identifier, &self.config.backend_identifier),- self.entity(EntityType::Vendor, &self.config.identifier, &self.config.name),- self.entity(EntityType::Family, &self.config.identifier, &self.config.name),- self.entity(EntityType::Variant, &identifier, &identifier),- ],- specializations: vec![Specialization::Chat],- number_of_parameters: None,- quantization: None,- accessibility: Accessibility::Local {- reference: Reference::Local {+ Model::external(+ identifier.clone(),+ self.config.identifier.clone(),+ self.config.name.clone(),+ self.config.backend_identifier.clone(),+ self.config.backend_identifier.clone(),+ self.config.backend_version.clone(),+ vec![ModelSpecialization::Chat {}],+ ModelAccessibility::Local {+ reference: ModelReference::Local {path: path.to_string_lossy().to_string(),},},- }- }-- fn entity(- &self,- r#type: EntityType,- identifier: &str,- name: &str,- ) -> Entity {- Entity {- r#type,- identifier: identifier.to_string(),- parent_identifier: None,- name: name.to_string(),- description: None,- version: None,- icons: vec![],- }+ )}}diff --git a/crates/uzu/src/registry/merged.rs b/crates/uzu/src/registry/merged.rsindex b5feb8447..a98bc1042 100644--- a/crates/uzu/src/registry/merged.rs+++ b/crates/uzu/src/registry/merged.rs@@ -2,14 +2,14 @@ use std::{future::Future, pin::Pin};use shoji::{traits::Registry, types::model::Model};-use crate::registry::Error;+use crate::registry::RegistryError;pub struct MergedRegistry {- registries: Vec<Box<dyn Registry<Error = Error>>>,+ registries: Vec<Box<dyn Registry<Error = RegistryError>>>,}impl MergedRegistry {- pub fn new(registries: Vec<Box<dyn Registry<Error = Error>>>) -> Self {+ pub fn new(registries: Vec<Box<dyn Registry<Error = RegistryError>>>) -> Self {Self {registries,}@@ -17,10 +17,10 @@ impl MergedRegistry {pub fn add(&mut self,- registry: Box<dyn Registry<Error = Error>>,- ) -> Result<(), Error> {+ registry: Box<dyn Registry<Error = RegistryError>>,+ ) -> Result<(), RegistryError> {if self.registries.iter().any(|current_registry| current_registry.indentifier() == registry.indentifier()) {- return Err(Error::UnableToAddRegistry {+ return Err(RegistryError::UnableToAddRegistry {identifier: registry.indentifier(),});}@@ -31,20 +31,20 @@ impl MergedRegistry {pub fn remove(&mut self,identifier: &str,- ) -> Result<(), Error> {+ ) -> Result<(), RegistryError> {self.registries.retain(|registry| registry.indentifier() != identifier);Ok(())}}impl Registry for MergedRegistry {- type Error = Error;+ type Error = RegistryError;fn indentifier(&self) -> String {self.registries.iter().map(|registry| registry.indentifier()).collect::<Vec<String>>().join(":")}- fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, Error>> + Send + '_>> {+ fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, RegistryError>> + Send + '_>> {Box::pin(async {let results = futures::future::join_all(self.registries.iter().map(|registry| registry.models())).await;diff --git a/crates/uzu/src/registry/mirai/mod.rs b/crates/uzu/src/registry/mirai/mod.rsindex 162fa1cb0..36d469712 100644--- a/crates/uzu/src/registry/mirai/mod.rs+++ b/crates/uzu/src/registry/mirai/mod.rs@@ -12,7 +12,7 @@ use reqwest::header::AUTHORIZATION;use shoji::{traits::Registry as RegistryTrait, types::model::Model};pub use types::Response;-use crate::registry::Error;+use crate::registry::RegistryError;pub struct Registry {config: Config,@@ -20,7 +20,7 @@ pub struct Registry {}impl Registry {- pub fn new(config: Config) -> Result<Self, Error> {+ pub fn new(config: Config) -> Result<Self, RegistryError> {let mut headers: IndexMap<String, String> = IndexMap::new();if let Some(api_key) = config.api_key.clone() {headers.insert(AUTHORIZATION.to_string(), format!("Bearer {}", api_key));@@ -28,7 +28,7 @@ impl Registry {let client_config =ClientConfig::new("https://sdk.trymirai.com/api/v1".to_string(), Duration::from_secs(10), headers);- let client = Client::new(client_config).map_err(|error| Error::UnableToCreate {+ let client = Client::new(client_config).map_err(|error| RegistryError::UnableToCreate {message: error.to_string(),})?;@@ -39,13 +39,13 @@ impl Registry {}}impl RegistryTrait for Registry {- type Error = Error;+ type Error = RegistryError;fn indentifier(&self) -> String {"mirai".to_string()}- fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, Error>> + Send + '_>> {+ fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, RegistryError>> + Send + '_>> {Box::pin(async {let response: Response = self.client@@ -55,10 +55,10 @@ impl RegistryTrait for Registry {include_traces: self.config.include_traces,}).await- .map_err(|error| Error::UnableToGetModels {+ .map_err(|error| RegistryError::UnableToGetModels {message: error.to_string(),})?;- let models = response.models().ok_or(Error::UnableToGetModels {+ let models = response.models().ok_or(RegistryError::UnableToGetModels {message: "Unable to extract from response".to_string(),})?;Ok(models)diff --git a/crates/uzu/src/registry/mirai/types.rs b/crates/uzu/src/registry/mirai/types.rsindex f721b3f9a..7dc4ab7e8 100644--- a/crates/uzu/src/registry/mirai/types.rs+++ b/crates/uzu/src/registry/mirai/types.rs@@ -1,57 +1,218 @@use serde::{Deserialize, Serialize};-use shoji::types::model::{Accessibility, Entity, Model, Quantization, Specialization};+use shoji::types::{+ basic::Metadata,+ model::{+ Model, ModelAccessibility, ModelBackend, ModelFamily, ModelProperties, ModelQuantization, ModelRegistry,+ ModelSpecialization, ModelVendor,+ },+};+fn get_metadata(+ metadatas: &Vec<Metadata>,+ identifier: String,+) -> Option<Metadata> {+ metadatas.iter().find(|metadata| metadata.identifier == identifier).cloned()+}++#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct Registry {+ pub id: String,+ pub metadata_id: String,+}++impl Registry {+ fn to(+ &self,+ metadatas: &Vec<Metadata>,+ ) -> Option<ModelRegistry> {+ let metadata = get_metadata(metadatas, self.metadata_id.clone())?;+ return Some(ModelRegistry {+ identifier: self.id.clone(),+ metadata: metadata,+ });+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct Backend {+ pub id: String,+ pub version: String,+ pub metadata_id: String,+}++impl Backend {+ fn to(+ &self,+ metadatas: &Vec<Metadata>,+ ) -> Option<ModelBackend> {+ let metadata = get_metadata(metadatas, self.metadata_id.clone())?;+ return Some(ModelBackend {+ identifier: self.id.clone(),+ version: self.version.clone(),+ metadata: metadata,+ });+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct Vendor {+ pub id: String,+ pub metadata_id: String,+}++impl Vendor {+ fn to(+ &self,+ metadatas: &Vec<Metadata>,+ ) -> Option<ModelVendor> {+ let metadata = get_metadata(metadatas, self.metadata_id.clone())?;+ return Some(ModelVendor {+ identifier: self.id.clone(),+ metadata: metadata,+ });+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct Family {+ pub id: String,+ pub vendor: Vendor,+ pub metadata_id: String,+}++impl Family {+ fn to(+ &self,+ metadatas: &Vec<Metadata>,+ ) -> Option<ModelFamily> {+ let vendor = self.vendor.to(metadatas)?;+ let metadata = get_metadata(metadatas, self.metadata_id.clone())?;+ return Some(ModelFamily {+ identifier: self.id.clone(),+ vendor: vendor,+ metadata: metadata,+ });+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct Properties {+ pub id: String,+ pub size: i64,+ pub version: Option<String>,+ pub metadata_id: String,+}++impl Properties {+ fn to(+ &self,+ metadatas: &Vec<Metadata>,+ ) -> Option<ModelProperties> {+ let metadata = get_metadata(metadatas, self.metadata_id.clone())?;+ return Some(ModelProperties {+ identifier: self.id.clone(),+ size: self.size,+ version: self.version.clone(),+ metadata: metadata,+ });+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct Quantization {+ pub id: String,+ pub method: String,+ pub bits_per_weight: u32,+ pub vendor: Vendor,+ pub metadata_id: String,+}++impl Quantization {+ fn to(+ &self,+ metadatas: &Vec<Metadata>,+ ) -> Option<ModelQuantization> {+ let vendor = self.vendor.to(metadatas)?;+ let metadata = get_metadata(metadatas, self.metadata_id.clone())?;+ return Some(ModelQuantization {+ identifier: self.id.clone(),+ method: self.method.clone(),+ bits_per_weight: self.bits_per_weight,+ vendor: vendor,+ metadata: metadata,+ });+ }+}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]-struct ResponseModel {- pub identifier: String,- pub entity_identifiers: Vec<String>,- pub specializations: Vec<Specialization>,- pub number_of_parameters: Option<i64>,+pub struct ResponseModel {+ pub id: String,+ pub registry: Registry,+ pub backends: Vec<Backend>,+ pub family: Option<Family>,+ pub properties: Option<Properties>,pub quantization: Option<Quantization>,- pub accessibility: Accessibility,+ pub specializations: Vec<ModelSpecialization>,+ pub accessibility: ModelAccessibility,+}++impl ResponseModel {+ fn to(+ &self,+ metadatas: &Vec<Metadata>,+ ) -> Option<Model> {+ let registry = self.registry.to(metadatas)?;+ let backends = self.backends.iter().flat_map(|backend| backend.to(metadatas)).collect::<Vec<_>>();+ if backends.len() != self.backends.len() {+ return None;+ }+ let family = match &self.family {+ Some(family) => Some(family.to(metadatas)?),+ None => None,+ };+ let properties = match &self.properties {+ Some(properties) => Some(properties.to(metadatas)?),+ None => None,+ };+ let quantization = match &self.quantization {+ Some(quantization) => Some(quantization.to(metadatas)?),+ None => None,+ };+ let specializations = self.specializations.clone();+ let accessibility = self.accessibility.clone();+ return Some(Model {+ identifier: self.id.clone(),+ registry: registry,+ backends: backends,+ family: family,+ properties: properties,+ quantization: quantization,+ specializations: specializations,+ accessibility: accessibility,+ });+ }}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub struct Response {models: Vec<ResponseModel>,- entities: Vec<Entity>,+ metadatas: Vec<Metadata>,}impl Response {pub fn models(&self) -> Option<Vec<Model>> {- let models = self- .models- .iter()- .flat_map(|response_model| {- let entities = self- .entities- .iter()- .filter(|entity| response_model.entity_identifiers.contains(&entity.identifier))- .map(|entity| entity.clone())- .collect::<Vec<_>>();-- if entities.len() != response_model.entity_identifiers.len() {- return None;- }-- let model = Model {- identifier: response_model.identifier.clone(),- entities: entities,- specializations: response_model.specializations.clone(),- number_of_parameters: response_model.number_of_parameters.clone(),- quantization: response_model.quantization.clone(),- accessibility: response_model.accessibility.clone(),- };- return Some(model);- })- .collect::<Vec<_>>();-+ let models =+ self.models.iter().flat_map(|response_model| response_model.to(&self.metadatas)).collect::<Vec<_>>();if models.len() != self.models.len() {return None;}-return Some(models);}}diff --git a/crates/uzu/src/registry/mod.rs b/crates/uzu/src/registry/mod.rsindex 62a0a781e..25e91a452 100644--- a/crates/uzu/src/registry/mod.rs+++ b/crates/uzu/src/registry/mod.rs@@ -7,6 +7,6 @@ pub mod mirai;pub mod openai;pub use cached::CachedRegistry;-pub use error::Error;+pub use error::RegistryError;pub use fixed::FixedRegistry;pub use merged::MergedRegistry;diff --git a/crates/uzu/src/registry/openai/mod.rs b/crates/uzu/src/registry/openai/mod.rsindex dae4442fa..19f491b9a 100644--- a/crates/uzu/src/registry/openai/mod.rs+++ b/crates/uzu/src/registry/openai/mod.rs@@ -8,7 +8,7 @@ use fancy_regex::Regex;use serde::Deserialize;use shoji::{traits::Registry as RegistryTrait,- types::model::{Accessibility, Entity, EntityType, Model as ShojiModel, Specialization},+ types::model::{Model as ShojiModel, ModelAccessibility, ModelSpecialization},};#[derive(Debug, Deserialize)]@@ -21,7 +21,7 @@ struct ListModelsResponse {data: Vec<Model>,}-use crate::registry::Error;+use crate::registry::RegistryError;pub struct Registry {config: Config,@@ -30,19 +30,20 @@ pub struct Registry {}impl Registry {- pub fn new(config: Config) -> Result<Self, Error> {+ pub fn new(config: Config) -> Result<Self, RegistryError> {let mut openai_config = OpenAIConfig::new().with_api_base(&config.api_endpoint);if let Some(api_key) = config.api_key.as_ref() {openai_config = openai_config.with_api_key(api_key);}if let Some(headers) = config.headers.as_ref() {for (key, value) in headers {- let name =- reqwest::header::HeaderName::from_bytes(key.as_bytes()).map_err(|error| Error::UnableToCreate {+ let name = reqwest::header::HeaderName::from_bytes(key.as_bytes()).map_err(|error| {+ RegistryError::UnableToCreate {message: error.to_string(),- })?;+ }+ })?;openai_config =- openai_config.with_header(name, value.as_str()).map_err(|error| Error::UnableToCreate {+ openai_config.with_header(name, value.as_str()).map_err(|error| RegistryError::UnableToCreate {message: error.to_string(),})?;}@@ -51,7 +52,7 @@ impl Registry {let client = Client::with_config(openai_config);let model_filter = config.model_filter_pattern.as_deref().map(Regex::new).transpose().map_err(|error| {- Error::UnableToCreate {+ RegistryError::UnableToCreate {message: error.to_string(),}})?;@@ -65,57 +66,39 @@ impl Registry {}impl RegistryTrait for Registry {- type Error = Error;+ type Error = RegistryError;fn indentifier(&self) -> String {self.config.identifier.clone()}- fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<ShojiModel>, Error>> + Send + '_>> {+ fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<ShojiModel>, RegistryError>> + Send + '_>> {Box::pin(async {let response: ListModelsResponse =- self.client.models().list_byot().await.map_err(|error| Error::UnableToGetModels {+ self.client.models().list_byot().await.map_err(|error| RegistryError::UnableToGetModels {message: error.to_string(),})?;let mut identifiers = response.data.into_iter().map(|model| model.id).collect::<Vec<_>>();identifiers.sort();- let registry_entity = self.create_entity(EntityType::Registry);- let backend_entity = self.create_entity(EntityType::Backend);- let vendor_entity = self.create_entity(EntityType::Vendor);- let family_entity = self.create_entity(EntityType::Family);-let models = identifiers.into_iter().filter(|identifier| {self.model_filter.as_ref().is_none_or(|regex| regex.is_match(identifier).unwrap_or(false))}).map(|identifier| {- let variant_entity = Entity {- r#type: EntityType::Variant,- identifier: identifier.clone(),- parent_identifier: None,- name: identifier.clone(),- description: None,- version: None,- icons: vec![],- };- let model = ShojiModel {- identifier: identifier.clone(),- entities: vec![- registry_entity.clone(),- backend_entity.clone(),- vendor_entity.clone(),- family_entity.clone(),- variant_entity,- ],- specializations: vec![Specialization::Chat],- number_of_parameters: None,- quantization: None,- accessibility: Accessibility::Remote {+ let model = ShojiModel::external(+ identifier.clone(),+ self.config.identifier.clone(),+ self.config.name.clone(),+ self.config.identifier.clone(),+ self.config.name.clone(),+ "default".to_string(),+ vec![ModelSpecialization::Chat {}],+ ModelAccessibility::Remote {repository: None,},- };+ );model}).collect();@@ -124,20 +107,3 @@ impl RegistryTrait for Registry {})}}--impl Registry {- fn create_entity(- &self,- r#type: EntityType,- ) -> Entity {- Entity {- r#type,- identifier: self.config.identifier.clone(),- parent_identifier: None,- name: self.config.name.clone(),- description: None,- version: None,- icons: vec![],- }- }-}diff --git a/crates/uzu/src/storage/config.rs b/crates/uzu/src/storage/config.rsindex d13867d80..01ea647a5 100644--- a/crates/uzu/src/storage/config.rs+++ b/crates/uzu/src/storage/config.rs@@ -27,7 +27,7 @@ impl Config {}pub fn cache_path(&self) -> PathBuf {- self.base_path.clone().unwrap_or(self.device.home_path.clone()).join(".cache").join(&self.name)+ self.base_path.clone().unwrap_or(PathBuf::from(self.device.home_path.clone())).join(".cache").join(&self.name)}pub fn cache_models_path(&self) -> PathBuf {diff --git a/crates/uzu/src/storage/error.rs b/crates/uzu/src/storage/error.rsindex d4082e441..15ad97593 100644--- a/crates/uzu/src/storage/error.rs+++ b/crates/uzu/src/storage/error.rs@@ -1,8 +1,9 @@-use crate::{registry::Error as RegistryError, storage::types::DownloadPhase};+use crate::{registry::RegistryError, storage::types::DownloadPhase};-#[derive(Debug, thiserror::Error)]+#[bindings::export(Error)]+#[derive(Debug, Clone, thiserror::Error)]#[non_exhaustive]-pub enum Error {+pub enum StorageError {#[error("Unable to create directory: {path}")]UnableToCreateDirectory {path: String,diff --git a/crates/uzu/src/storage/mod.rs b/crates/uzu/src/storage/mod.rsindex 2f9ad7f55..ffd1223ed 100644--- a/crates/uzu/src/storage/mod.rs+++ b/crates/uzu/src/storage/mod.rs@@ -12,8 +12,11 @@ pub use config::Config;use download_manager::{FileCheck, FileDownloadManager, FileDownloadManagerType, FileDownloadPhase, create_download_manager,};-pub use error::Error;-use shoji::types::model::{Accessibility, File, Model, Reference};+pub use error::StorageError;+use shoji::types::{+ basic::File,+ model::{Model, ModelAccessibility, ModelReference},+};use tokio::{runtime::Handle,sync::broadcast::{Sender, channel},@@ -38,8 +41,8 @@ impl Storage {pub async fn new(tokio_handle: Handle,config: Config,- ) -> Result<Self, Error> {- create_dir_all(config.cache_path()).map_err(|_| Error::UnableToCreateDirectory {+ ) -> Result<Self, StorageError> {+ create_dir_all(config.cache_path()).map_err(|_| StorageError::UnableToCreateDirectory {path: config.cache_path().to_string_lossy().to_string(),})?;@@ -50,7 +53,7 @@ impl Storage {tokio_handle.clone(),).await- .map_err(|error| Error::DownloadManager {+ .map_err(|error| StorageError::DownloadManager {message: error.to_string(),})?,));@@ -74,14 +77,14 @@ impl Storage {pub async fn refresh(&self,models: Vec<Model>,- ) -> Result<(), Error> {+ ) -> Result<(), StorageError> {let models = models.into_iter().filter(|model| model.is_downloadable()).collect::<Vec<_>>();- let actual_model_identifiers: HashSet<String> = models.iter().map(|model| model.identifier()).collect();+ let actual_model_identifiers: HashSet<String> = models.iter().map(|model| model.identifier.clone()).collect();let download_manager = { self.download_manager.lock().await.clone() };let existing_file_tasks =- download_manager.get_all_file_tasks().await.map_err(|error| Error::DownloadManager {+ download_manager.get_all_file_tasks().await.map_err(|error| StorageError::DownloadManager {message: error.to_string(),})?;let mut active_file_tasks = Vec::with_capacity(existing_file_tasks.len());@@ -107,7 +110,7 @@ impl Storage {}for model in models {- let identifier = model.identifier();+ let identifier = model.identifier.clone();if items.contains_key(&identifier) {continue;}@@ -115,7 +118,7 @@ impl Storage {let files = self.resolve_model_files(&model)?;let total_bytes: u64 = files.iter().map(|file| file.size as u64).sum();- let cache_path = self.config.cache_model_path(&model).ok_or(Error::UnsupportedItem {+ let cache_path = self.config.cache_model_path(&model).ok_or(StorageError::UnsupportedItem {identifier: identifier.clone(),})?;@@ -129,7 +132,7 @@ impl Storage {let mut file_tasks = Vec::new();for file in &files {let file_path = cache_path.join(&file.name);- let file_check = FileCheck::CRC(file.crc32c().ok_or(Error::HashNotFound {+ let file_check = FileCheck::CRC(file.crc32c().ok_or(StorageError::HashNotFound {identifier: identifier.clone(),name: file.name.clone(),})?);@@ -137,7 +140,7 @@ impl Storage {let file_task = download_manager.file_download_task(&file.url, &file_path, file_check, Some(file.size as u64)).await- .map_err(|error| Error::DownloadManager {+ .map_err(|error| StorageError::DownloadManager {message: error.to_string(),})?;@@ -148,7 +151,7 @@ impl Storage {identifier.clone(),files.into(),cache_path.clone(),- DownloadState::not_downloaded(total_bytes),+ DownloadState::not_downloaded(total_bytes as i64),download_manager.clone(),file_tasks,self.handle.clone(),@@ -159,7 +162,7 @@ impl Storage {let _ = item.reconcile().await;let item_state = item.state().await;- if matches!(item_state.phase, DownloadPhase::NotDownloaded)+ if matches!(item_state.phase, DownloadPhase::NotDownloaded {})&& cache_path.exists()&& let Ok(entries) = read_dir(&cache_path){@@ -180,7 +183,7 @@ impl Storage {identifier.clone(),files.into(),cache_path.clone(),- DownloadState::not_downloaded(total_bytes),+ DownloadState::not_downloaded(total_bytes as i64),download_manager.clone(),Vec::new(),self.handle.clone(),@@ -218,8 +221,8 @@ impl Storage {pub async fn download(&self,model_identifier: &String,- ) -> Result<(), Error> {- let item = self.get(model_identifier).await.ok_or_else(|| Error::ItemNotFound {+ ) -> Result<(), StorageError> {+ let item = self.get(model_identifier).await.ok_or_else(|| StorageError::ItemNotFound {identifier: model_identifier.clone(),})?;item.download().await@@ -228,8 +231,8 @@ impl Storage {pub async fn pause(&self,model_identifier: &String,- ) -> Result<(), Error> {- let item = self.get(model_identifier).await.ok_or_else(|| Error::ItemNotFound {+ ) -> Result<(), StorageError> {+ let item = self.get(model_identifier).await.ok_or_else(|| StorageError::ItemNotFound {identifier: model_identifier.clone(),})?;item.pause().await@@ -238,8 +241,8 @@ impl Storage {pub async fn delete(&self,model_identifier: &String,- ) -> Result<(), Error> {- let item = self.get(model_identifier).await.ok_or_else(|| Error::ItemNotFound {+ ) -> Result<(), StorageError> {+ let item = self.get(model_identifier).await.ok_or_else(|| StorageError::ItemNotFound {identifier: model_identifier.clone(),})?;item.cancel().await@@ -250,31 +253,31 @@ impl Storage {fn resolve_model_files(&self,model: &Model,- ) -> Result<Vec<File>, Error> {+ ) -> Result<Vec<File>, StorageError> {match &model.accessibility {- Accessibility::Local {+ ModelAccessibility::Local {reference,..} => match &reference {- Reference::Mirai {+ ModelReference::Mirai {files,..} => Ok(files.clone()),- Reference::HuggingFace {+ ModelReference::HuggingFace {..- } => Err(Error::UnsupportedItem {- identifier: model.identifier(),+ } => Err(StorageError::UnsupportedItem {+ identifier: model.identifier.clone(),}),- Reference::Local {+ ModelReference::Local {..- } => Err(Error::UnsupportedItem {- identifier: model.identifier(),+ } => Err(StorageError::UnsupportedItem {+ identifier: model.identifier.clone(),}),},- Accessibility::Remote {+ ModelAccessibility::Remote {..- } => Err(Error::UnsupportedItem {- identifier: model.identifier(),+ } => Err(StorageError::UnsupportedItem {+ identifier: model.identifier.clone(),}),}}diff --git a/crates/uzu/src/storage/types/crc_snapshot.rs b/crates/uzu/src/storage/types/crc_snapshot.rsindex 32afa5f6c..891707c7f 100644--- a/crates/uzu/src/storage/types/crc_snapshot.rs+++ b/crates/uzu/src/storage/types/crc_snapshot.rs@@ -1,6 +1,6 @@use std::{fs::remove_file, path::Path};-use crate::storage::Error;+use crate::storage::StorageError;pub struct CrcSnapshot;@@ -15,10 +15,10 @@ impl CrcSnapshot {pub fn remove_crc(model_dir: &Path,filename: &str,- ) -> Result<(), Error> {+ ) -> Result<(), StorageError> {let crc_path = Self::crc_file_path(model_dir, filename);if crc_path.exists() {- remove_file(&crc_path).map_err(|error| Error::IO {+ remove_file(&crc_path).map_err(|error| StorageError::IO {message: error.to_string(),})?;}diff --git a/crates/uzu/src/storage/types/download_phase.rs b/crates/uzu/src/storage/types/download_phase.rsindex 1bde53093..262a8f80b 100644--- a/crates/uzu/src/storage/types/download_phase.rs+++ b/crates/uzu/src/storage/types/download_phase.rs@@ -1,24 +1,29 @@-#[derive(Debug, Clone, PartialEq, Eq, Hash)]+use serde::{Deserialize, Serialize};++#[bindings::export(Enum)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum DownloadPhase {- NotDownloaded,- Downloading,- Paused,- Downloaded,- Locked,- Error(String),+ NotDownloaded {},+ Downloading {},+ Paused {},+ Downloaded {},+ Locked {},+ Error {+ message: String,+ },}impl DownloadPhase {pub fn is_in_progress(&self) -> bool {- matches!(self, Self::Downloading | Self::Paused)+ matches!(self, Self::Downloading {} | Self::Paused {})}pub fn can_pause(&self) -> bool {- matches!(self, Self::Downloading | Self::Paused)+ matches!(self, Self::Downloading {} | Self::Paused {})}pub fn can_delete(&self) -> bool {// Allow delete in all states except NotDownloaded- !matches!(self, Self::NotDownloaded)+ !matches!(self, Self::NotDownloaded {})}}diff --git a/crates/uzu/src/storage/types/download_state.rs b/crates/uzu/src/storage/types/download_state.rsindex f17f96574..501f418b9 100644--- a/crates/uzu/src/storage/types/download_state.rs+++ b/crates/uzu/src/storage/types/download_state.rs@@ -1,61 +1,63 @@use download_manager::{FileDownloadPhase, FileDownloadState};+use serde::{Deserialize, Serialize};use crate::storage::types::DownloadPhase;-#[derive(Debug, Clone, PartialEq, Eq, Hash)]+#[bindings::export(Struct)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]pub struct DownloadState {- pub total_bytes: u64,- pub downloaded_bytes: u64,+ pub total_bytes: i64,+ pub downloaded_bytes: i64,pub phase: DownloadPhase,}impl DownloadState {- pub fn not_downloaded(total_bytes: u64) -> Self {+ pub fn not_downloaded(total_bytes: i64) -> Self {Self {total_bytes,downloaded_bytes: 0,- phase: DownloadPhase::NotDownloaded,+ phase: DownloadPhase::NotDownloaded {},}}pub fn downloading(- downloaded_bytes: u64,- total_bytes: u64,+ downloaded_bytes: i64,+ total_bytes: i64,) -> Self {Self {total_bytes,downloaded_bytes,- phase: DownloadPhase::Downloading,+ phase: DownloadPhase::Downloading {},}}pub fn paused(- downloaded_bytes: u64,- total_bytes: u64,+ downloaded_bytes: i64,+ total_bytes: i64,) -> Self {Self {total_bytes,downloaded_bytes,- phase: DownloadPhase::Paused,+ phase: DownloadPhase::Paused {},}}- pub fn downloaded(total_bytes: u64) -> Self {+ pub fn downloaded(total_bytes: i64) -> Self {Self {total_bytes,downloaded_bytes: total_bytes,- phase: DownloadPhase::Downloaded,+ phase: DownloadPhase::Downloaded {},}}pub fn locked(- downloaded_bytes: u64,- total_bytes: u64,+ downloaded_bytes: i64,+ total_bytes: i64,) -> Self {Self {total_bytes,downloaded_bytes,- phase: DownloadPhase::Locked,+ phase: DownloadPhase::Locked {},}}@@ -63,10 +65,16 @@ impl DownloadState {Self {total_bytes: 0,downloaded_bytes: 0,- phase: DownloadPhase::Error(error_message),+ phase: DownloadPhase::Error {+ message: error_message,+ },}}+}+#[bindings::export(Implementation)]+impl DownloadState {+ #[bindings::export(Getter)]pub fn progress(&self) -> f32 {if self.total_bytes == 0 {0.0@@ -75,14 +83,17 @@ impl DownloadState {}}+ #[bindings::export(Getter)]pub fn is_in_progress(&self) -> bool {self.phase.is_in_progress()}+ #[bindings::export(Getter)]pub fn can_pause(&self) -> bool {self.phase.can_pause()}+ #[bindings::export(Getter)]pub fn can_delete(&self) -> bool {self.phase.can_delete()}@@ -104,20 +115,20 @@ pub fn reduce_file_download_states(file_states: &[FileDownloadState]) -> Downloalet any_locked = file_states.iter().any(|f| matches!(f.phase, FileDownloadPhase::LockedByOther(_)));if all_downloaded {- return DownloadState::downloaded(total_bytes);+ return DownloadState::downloaded(total_bytes as i64);}// Locked takes precedence over other in-progress statesif any_locked {- return DownloadState::locked(downloaded_bytes, total_bytes);+ return DownloadState::locked(downloaded_bytes as i64, total_bytes as i64);}if any_downloading {- return DownloadState::downloading(downloaded_bytes, total_bytes);+ return DownloadState::downloading(downloaded_bytes as i64, total_bytes as i64);}if any_paused {- return DownloadState::paused(downloaded_bytes, total_bytes);+ return DownloadState::paused(downloaded_bytes as i64, total_bytes as i64);}if any_error {@@ -131,8 +142,8 @@ pub fn reduce_file_download_states(file_states: &[FileDownloadState]) -> Downloa// If some files are downloaded but not all, and nothing is actively// downloading, treat as paused (partial progress, can resume)if any_downloaded && downloaded_bytes > 0 {- return DownloadState::paused(downloaded_bytes, total_bytes);+ return DownloadState::paused(downloaded_bytes as i64, total_bytes as i64);}- DownloadState::not_downloaded(total_bytes)+ DownloadState::not_downloaded(total_bytes as i64)}diff --git a/crates/uzu/src/storage/types/item.rs b/crates/uzu/src/storage/types/item.rsindex dfa73bf9f..637244baa 100644--- a/crates/uzu/src/storage/types/item.rs+++ b/crates/uzu/src/storage/types/item.rs@@ -6,7 +6,7 @@ use std::{use download_manager::{FileDownloadManager, FileDownloadState, FileDownloadTask};use futures_util::future::join_all;-use shoji::types::model::File;+use shoji::types::basic::File;use tokio::{runtime::Handle,sync::broadcast::{Sender, channel},@@ -17,7 +17,7 @@ use tokio_stream::wrappers::BroadcastStream;use crate::{helpers::SharedAccess,storage::{- Error,+ StorageError,types::{CrcSnapshot, DownloadPhase, DownloadState, reduce_file_download_states},},};@@ -241,7 +241,7 @@ impl Item {file_tasks_guard.iter().find(|task| task.download_id() == download_id).cloned()}- pub async fn reconcile(&self) -> Result<(), Error> {+ pub async fn reconcile(&self) -> Result<(), StorageError> {// Reconciliation is now handled by FileDownloadTask// Just update our broadcast with current statelet calculated_state = self.reduce_state().await;@@ -249,7 +249,7 @@ impl Item {Ok(())}- async fn ensure_file_tasks(&self) -> Result<bool, Error> {+ async fn ensure_file_tasks(&self) -> Result<bool, StorageError> {let mut file_tasks_guard = self.file_download_tasks.lock().await;// If file tasks already exist, skip creation@@ -261,16 +261,17 @@ impl Item {let mut new_file_tasks = Vec::new();for file_info in self.files.iter() {let file_path = self.cache_path.join(&file_info.name);- let file_check = download_manager::FileCheck::CRC(file_info.crc32c().ok_or(Error::HashNotFound {- identifier: self.identifier.clone(),- name: file_info.name.clone(),- })?);+ let file_check =+ download_manager::FileCheck::CRC(file_info.crc32c().ok_or(StorageError::HashNotFound {+ identifier: self.identifier.clone(),+ name: file_info.name.clone(),+ })?);let file_task = self.file_download_manager.file_download_task(&file_info.url, &file_path, file_check, Some(file_info.size as u64)).await- .map_err(|error| Error::DownloadManager {+ .map_err(|error| StorageError::DownloadManager {message: error.to_string(),})?;@@ -284,7 +285,7 @@ impl Item {Ok(true)}- pub async fn download(&self) -> Result<(), Error> {+ pub async fn download(&self) -> Result<(), StorageError> {tracing::debug!("[MODEL] download() called for model: {}", self.identifier);// Ensure file tasks are initialized@@ -308,9 +309,9 @@ impl Item {);if !Self::can_transition_to_downloading(¤t_state.phase) {- return Err(Error::InvalidStateTransition {+ return Err(StorageError::InvalidStateTransition {from: current_state.phase.clone(),- to: DownloadPhase::Downloading,+ to: DownloadPhase::Downloading {},});}@@ -323,7 +324,7 @@ impl Item {result}- pub async fn pause(&self) -> Result<(), Error> {+ pub async fn pause(&self) -> Result<(), StorageError> {tracing::debug!("[MODEL] pause() called for model: {}", self.identifier);// Ensure file tasks are initialized@@ -341,9 +342,9 @@ impl Item {self.update_state_and_broadcast(current_state.clone()).await;if !current_state.can_pause() {- return Err(Error::InvalidStateTransition {+ return Err(StorageError::InvalidStateTransition {from: current_state.phase.clone(),- to: DownloadPhase::Paused,+ to: DownloadPhase::Paused {},});}@@ -356,7 +357,7 @@ impl Item {result}- pub async fn cancel(&self) -> Result<(), Error> {+ pub async fn cancel(&self) -> Result<(), StorageError> {// Ensure file tasks are initializedlet tasks_were_created = self.ensure_file_tasks().await?;@@ -396,12 +397,12 @@ impl Item {}let total_bytes: u64 = self.files.iter().map(|f| f.size as u64).sum();- let not_downloaded_state = DownloadState::not_downloaded(total_bytes);+ let not_downloaded_state = DownloadState::not_downloaded(total_bytes as i64);self.update_state_and_broadcast(not_downloaded_state).await;Ok(())}- pub async fn progress(&self) -> Result<BroadcastStream<DownloadState>, Error> {+ pub async fn progress(&self) -> Result<BroadcastStream<DownloadState>, StorageError> {Ok(BroadcastStream::new(self.broadcast_sender.subscribe()))}@@ -423,10 +424,10 @@ impl Item {self.update_state_and_broadcast(new_state).await;}- async fn ensure_downloading(&self) -> Result<(), Error> {+ async fn ensure_downloading(&self) -> Result<(), StorageError> {tracing::debug!("[MODEL] ensure_downloading: model={}", self.identifier);- create_dir_all(&self.cache_path).map_err(|error| Error::IO {+ create_dir_all(&self.cache_path).map_err(|error| StorageError::IO {message: error.to_string(),})?;@@ -443,7 +444,7 @@ impl Item {Ok(())}- async fn ensure_paused(&self) -> Result<(), Error> {+ async fn ensure_paused(&self) -> Result<(), StorageError> {tracing::debug!("[MODEL] ensure_paused: model={}", self.identifier);let file_tasks_guard = self.file_download_tasks.lock().await;let pause_futures = file_tasks_guard.iter().map(|file_task| {@@ -459,11 +460,11 @@ impl Item {}#[allow(dead_code)]- async fn cleanup_empty_directory(&self) -> Result<(), Error> {+ async fn cleanup_empty_directory(&self) -> Result<(), StorageError> {if !self.cache_path.exists() {return Ok(());}- let entries = read_dir(&self.cache_path).map_err(|error| Error::IO {+ let entries = read_dir(&self.cache_path).map_err(|error| StorageError::IO {message: error.to_string(),})?;let mut has_real_files = false;@@ -637,7 +638,10 @@ impl Item {fn can_transition_to_downloading(from: &DownloadPhase) -> bool {matches!(from,- DownloadPhase::NotDownloaded | DownloadPhase::Downloading | DownloadPhase::Paused | DownloadPhase::Error(_)+ DownloadPhase::NotDownloaded {}+ | DownloadPhase::Downloading {}+ | DownloadPhase::Paused {}+ | DownloadPhase::Error { .. })}}diff --git a/crates/uzu/tests/common/test_helpers.rs b/crates/uzu/tests/common/test_helpers.rsindex 586179bbf..0c6db2182 100644--- a/crates/uzu/tests/common/test_helpers.rs+++ b/crates/uzu/tests/common/test_helpers.rs@@ -2,7 +2,10 @@use std::path::PathBuf;-use shoji::types::model::{Accessibility, Entity, EntityType, File, Hash, HashMethod, Model, Reference};+use shoji::types::{+ basic::{File, Hash, HashMethod, Metadata},+ model::{Model, ModelAccessibility, ModelBackend, ModelReference, ModelRegistry},+};use tokio::runtime::Handle;use uzu::{device::Device,@@ -49,54 +52,15 @@ impl TestStorage {}fn test_model(index: usize) -> Model {- let registry_entity = Entity {- r#type: EntityType::Registry,+ let registry = ModelRegistry {identifier: "test-registry".to_string(),- parent_identifier: None,- version: None,- name: "Test Registry".to_string(),- description: None,- icons: vec![],+ metadata: Metadata::external("test-registry-metadata".to_string()),};- let backend_entity = Entity {- r#type: EntityType::Backend,+ let backend = ModelBackend {identifier: "test-backend".to_string(),- parent_identifier: None,- version: None,- name: "Test Backend".to_string(),- description: None,- icons: vec![],- };-- let vendor_entity = Entity {- r#type: EntityType::Vendor,- identifier: "test-vendor".to_string(),- parent_identifier: None,- version: None,- name: "Test Vendor".to_string(),- description: None,- icons: vec![],- };-- let family_entity = Entity {- r#type: EntityType::Family,- identifier: "test-family".to_string(),- parent_identifier: None,- version: None,- name: "Test Family".to_string(),- description: None,- icons: vec![],- };-- let model_entity = Entity {- r#type: EntityType::Variant,- identifier: format!("test-model-{}", index),- parent_identifier: None,- version: None,- name: format!("Test Model {}", index),- description: None,- icons: vec![],+ version: "1.0".to_string(),+ metadata: Metadata::external("test-backend-metadata".to_string()),};let files_1 = vec![@@ -161,12 +125,14 @@ fn test_model(index: usize) -> Model {Model {identifier: format!("test-model-{}", index),- entities: vec![registry_entity, backend_entity, vendor_entity, family_entity, model_entity],- specializations: vec![],- number_of_parameters: None,+ registry: registry,+ backends: vec![backend],+ family: None,+ properties: None,quantization: None,- accessibility: Accessibility::Local {- reference: Reference::Mirai {+ specializations: vec![],+ accessibility: ModelAccessibility::Local {+ reference: ModelReference::Mirai {toolchain_version: "1.0".to_string(),repository: None,source_repository: None,diff --git a/crates/uzu/tests/test_engine.rs b/crates/uzu/tests/test_engine.rsindex e01fb250b..5fbbf5ef6 100644--- a/crates/uzu/tests/test_engine.rs+++ b/crates/uzu/tests/test_engine.rs@@ -1,64 +1,131 @@#![cfg(not(target_family = "wasm"))]-use futures::StreamExt;-use shoji::types::{- encoding::Message,- session::chat::{Config as ChatConfig, StreamConfig as ChatStreamConfig},+use uzu::{+ engine::{Engine, EngineConfig},+ session::chat::ChatSessionStreamChunk,+ types::session::{+ chat::{ChatConfig, ChatMessage, ChatReplyConfig},+ classification::ClassificationMessage,+ },};-use uzu::engine::{Config, Engine};#[ignore]#[tokio::test]-async fn test_engine() {+async fn test_engine_chat() {dotenvy::dotenv().ok();- let config = Config::default();+ let config = EngineConfig::default();let engine = Engine::new(config).await.unwrap();+ println!("-------------------------");let models = engine.models().await.unwrap();for model in models {- let identifier = model.identifier();- let registry_identifier = model.registry_entity().map(|entity| entity.identifier);+ let identifier = model.identifier.clone();+ let name = model.name();+ let repo_ids = model.repo_ids();+ let registry_identifier = model.registry.identifier.clone();+ let backend_identifiers = model.backends.iter().map(|backend| backend.identifier.clone()).collect::<Vec<_>>();+ let family_vendor_identifier = model.family.as_ref().map(|family| family.vendor.identifier.clone());+ let family_identifier = model.family.as_ref().map(|family| family.identifier.clone());+ let properties_identifier = model.properties.as_ref().map(|properties| properties.identifier.clone());+ let quantization_vendor_identifier =+ model.quantization.as_ref().map(|quantization| quantization.vendor.identifier.clone());+ let quantization_identifier = model.quantization.as_ref().map(|quantization| quantization.identifier.clone());let download_phase = engine.downloader(&model).state().await.map_or(None, |state| Some(state.phase));- println!("{:?}, {}, {:?}, {:?}", registry_identifier, identifier, download_phase, model.specializations);+ println!("identifier: {}", identifier);+ println!("name: {}", name);+ println!("repo_ids: {:?}", repo_ids);+ println!("registry_identifier: {}", registry_identifier);+ println!("backend_identifiers: {:?}", backend_identifiers);+ println!("family_vendor_identifier: {:?}", family_vendor_identifier);+ println!("family_identifier: {:?}", family_identifier);+ println!("properties_identifier: {:?}", properties_identifier);+ println!("quantization_vendor_identifier: {:?}", quantization_vendor_identifier);+ println!("quantization_identifier: {:?}", quantization_identifier);+ println!("download_phase: {:?}", download_phase);+ println!("specializations: {:?}", model.specializations);+ println!("-------------------------");+ }++ let model = engine.model("alibaba:qwen3:0.6b".to_string()).await.unwrap().unwrap();+ while let Some(update) = engine.download(&model).await.unwrap().next().await {+ println!("Downloading: {}", update.progress());}- let model = engine.model("gpt-3.5-turbo").await.unwrap().unwrap();let session = engine.chat(model, ChatConfig::default()).await.unwrap();session.reset().await.unwrap();let messages = vec![- Message::system().with_text("You are a helpful assistant.".to_string()),- Message::user().with_text("My name is John Doe".to_string()),+ ChatMessage::system().with_text("You are a helpful assistant.".to_string()),+ ChatMessage::user().with_text("My name is John Doe".to_string()),];- let (mut stream, _) = session.stream(messages, ChatStreamConfig::default());+ let stream = session.reply_with_stream(messages, ChatReplyConfig::default());while let Some(progress) = stream.next().await {match progress {- Ok(outputs) => {+ ChatSessionStreamChunk::Replies {+ replies,+ } => {let state = session.state().await;let messages = session.messages().await;let roles = messages.iter().map(|message| message.role.clone()).collect::<Vec<_>>();println!("State: {state:?}");println!("Roles: {roles:?}");- for output in outputs {- let duration = output.stats.duration;- let finish_reason = output.finish_reason;- let text_length = output.message.text().len();+ for reply in replies {+ let duration = reply.stats.duration;+ let finish_reason = reply.finish_reason;+ let text_length = reply.message.text().unwrap_or_default().len();println!("\tDuration: {duration}\n\tFinish reason: {finish_reason:?}\n\tText length: {text_length}");}},- Err(error) => eprintln!("Stream error: {error}"),+ ChatSessionStreamChunk::Error {+ error,+ } => eprintln!("Stream error: {error}"),}}- let messages = vec![Message::user().with_text("What is my name?".to_string())];- let (mut stream, _) = session.stream(messages, ChatStreamConfig::default());- while let Some(_) = stream.next().await {}+ let messages = vec![ChatMessage::user().with_text("What is my name?".to_string())];+ let _ = session.reply(messages, ChatReplyConfig::default()).await.unwrap();let messages = session.messages().await;for message in messages {println!("Message: {message:?}");}}++#[ignore]+#[tokio::test]+async fn test_engine_classification() {+ dotenvy::dotenv().ok();++ let config = EngineConfig::default();+ let engine = Engine::new(config).await.unwrap();+ let model = engine.model("ModernBERT-Chat-Moderation".to_string()).await.unwrap().unwrap();+ while let Some(update) = engine.download(&model).await.unwrap().next().await {+ println!("Downloading: {}", update.progress());+ }++ let session = engine.classification(model).await.unwrap();+ let messages = vec![ClassificationMessage::user("Hi!".to_string())];+ let result = session.classify(messages).await.unwrap();+ println!("Output: {result:?}");+}++#[ignore]+#[tokio::test]+async fn test_engine_text_to_speech() {+ dotenvy::dotenv().ok();++ let config = EngineConfig::default();+ let engine = Engine::new(config).await.unwrap();+ let model = engine.model("s1-mini".to_string()).await.unwrap().unwrap();+ while let Some(update) = engine.download(&model).await.unwrap().next().await {+ println!("Downloading: {}", update.progress());+ }++ let session = engine.text_to_speech(model).await.unwrap();+ let result = session.synthesize("London is the capital of United Kingdom and one of the world’s most influential cities, known for its rich history, cultural diversity, and global significance in finance, politics, and the arts. Situated along the River Thames, the city blends historic landmarks like Tower of London and Buckingham Palace with modern architecture such as The Shard. London is also home to renowned institutions including the British Museum and vibrant areas like Covent Garden, offering a mix of history, entertainment, and innovation that attracts millions of visitors each year.".to_string()).await.unwrap();+ let path = dirs::home_dir().unwrap().join("Desktop").join("output.wav").to_string_lossy().to_string();+ result.save_as_wav(path).unwrap();+}diff --git a/crates/uzu/tests/test_storage_comprehensive_download.rs b/crates/uzu/tests/test_storage_comprehensive_download.rsindex a1f715e81..3c44cd390 100644--- a/crates/uzu/tests/test_storage_comprehensive_download.rs+++ b/crates/uzu/tests/test_storage_comprehensive_download.rs@@ -19,7 +19,7 @@ async fn test_storage_comprehensive_download() -> Result<(), Box<dyn std::error:tracing::info!("[TEST] Initializing storage...");let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model_identifier = test_storage.model(0).identifier();+ let model_identifier = test_storage.model(0).identifier.clone();let storage = &test_storage.storage;tokio::time::sleep(Duration::from_millis(200)).await;@@ -33,7 +33,7 @@ async fn test_storage_comprehensive_download() -> Result<(), Box<dyn std::error:initial_state.total_bytes,initial_state.phase);- let pb = ProgressBar::new(initial_state.total_bytes);+ let pb = ProgressBar::new(initial_state.total_bytes as u64);pb.set_style(ProgressStyle::default_bar().template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%, {bytes_per_sec}, eta {eta}) - {msg}")@@ -59,15 +59,15 @@ async fn test_storage_comprehensive_download() -> Result<(), Box<dyn std::error:state.total_bytes);if id == model_identifier_clone {- pb_clone.set_position(state.downloaded_bytes);+ pb_clone.set_position(state.downloaded_bytes as u64);if state.downloaded_bytes >= quarter_threshold {tracing::info!("[PHASE1] ✓ Reached 25% threshold");- let _ = phase1_tx.send(state.downloaded_bytes).await;+ let _ = phase1_tx.send(state.downloaded_bytes as u64).await;break;}- if matches!(state.phase, DownloadPhase::Downloaded) {+ if matches!(state.phase, DownloadPhase::Downloaded {}) {tracing::info!("[PHASE1] ✓ Downloaded state reached (completed before 25%)");- let _ = phase1_tx.send(state.downloaded_bytes).await;+ let _ = phase1_tx.send(state.downloaded_bytes as u64).await;break;}}@@ -87,7 +87,7 @@ async fn test_storage_comprehensive_download() -> Result<(), Box<dyn std::error:monitor_task.abort();let current_state = model.state().await;- if matches!(current_state.phase, DownloadPhase::Downloaded) {+ if matches!(current_state.phase, DownloadPhase::Downloaded {}) {tracing::info!("\n[TEST] ========== Download completed early, skipping pause/resume tests ==========");pb.finish_with_message("Download completed");return Ok(());@@ -117,13 +117,13 @@ async fn test_storage_comprehensive_download() -> Result<(), Box<dyn std::error:const TIMEOUT: Duration = Duration::from_secs(120);while let Ok(Some(Ok((id, state)))) = tokio::time::timeout(TIMEOUT, updates.next()).await {if id == model_identifier_clone {- pb_clone.set_position(state.downloaded_bytes);+ pb_clone.set_position(state.downloaded_bytes as u64);if state.downloaded_bytes >= half_threshold {- let _ = phase3_tx.send(state.downloaded_bytes).await;+ let _ = phase3_tx.send(state.downloaded_bytes as u64).await;break;}- if matches!(state.phase, DownloadPhase::Downloaded) {- let _ = phase3_tx.send(state.downloaded_bytes).await;+ if matches!(state.phase, DownloadPhase::Downloaded {}) {+ let _ = phase3_tx.send(state.downloaded_bytes as u64).await;break;}}@@ -145,7 +145,7 @@ async fn test_storage_comprehensive_download() -> Result<(), Box<dyn std::error:let cancelled_state = model.state().await;tracing::info!("[PHASE4] ✓ Cancelled state confirmed: phase={:?}", cancelled_state.phase);assert!(- matches!(cancelled_state.phase, DownloadPhase::NotDownloaded),+ matches!(cancelled_state.phase, DownloadPhase::NotDownloaded {}),"Expected model to be in NotDownloaded state after cancellation, got {:?}",cancelled_state.phase);@@ -161,13 +161,13 @@ async fn test_storage_comprehensive_download() -> Result<(), Box<dyn std::error:const TIMEOUT: Duration = Duration::from_secs(120);while let Ok(Some(Ok((id, state)))) = tokio::time::timeout(TIMEOUT, updates.next()).await {if id == model_identifier_clone {- pb_clone.set_position(state.downloaded_bytes);+ pb_clone.set_position(state.downloaded_bytes as u64);if state.downloaded_bytes >= half_threshold {- let _ = phase5_tx.send(state.downloaded_bytes).await;+ let _ = phase5_tx.send(state.downloaded_bytes as u64).await;break;}- if matches!(state.phase, DownloadPhase::Downloaded) {- let _ = phase5_tx.send(state.downloaded_bytes).await;+ if matches!(state.phase, DownloadPhase::Downloaded {}) {+ let _ = phase5_tx.send(state.downloaded_bytes as u64).await;break;}}@@ -212,16 +212,18 @@ async fn test_storage_comprehensive_download() -> Result<(), Box<dyn std::error:state.total_bytes);if id == model_identifier_clone {- pb_clone.set_position(state.downloaded_bytes);+ pb_clone.set_position(state.downloaded_bytes as u64);match state.phase {- DownloadPhase::Downloaded => {+ DownloadPhase::Downloaded {} => {tracing::info!("[PHASE7] ✓ Downloaded state reached!");pb_clone.finish_with_message("✓ Download complete!");let send_result = phase7_tx.send(()).await;tracing::info!("[PHASE7] Channel send result: {:?}", send_result);break;},- DownloadPhase::Error(ref err) => {+ DownloadPhase::Error {+ message: ref err,+ } => {tracing::info!("[PHASE7] ✗ Error state reached: {}", err);pb_clone.abandon_with_message(format!("✗ Error: {}", err));break;@@ -250,7 +252,7 @@ async fn test_storage_comprehensive_download() -> Result<(), Box<dyn std::error:tracing::info!("[TEST] Final model state: {:?}, bytes: {}", final_state.phase, final_state.downloaded_bytes);assert!(- matches!(final_state.phase, DownloadPhase::Downloaded),+ matches!(final_state.phase, DownloadPhase::Downloaded {}),"Expected Downloaded state, got {:?}",final_state.phase);diff --git a/crates/uzu/tests/test_storage_comprehensive_state.rs b/crates/uzu/tests/test_storage_comprehensive_state.rsindex 4c5ade0c0..66ff6005b 100644--- a/crates/uzu/tests/test_storage_comprehensive_state.rs+++ b/crates/uzu/tests/test_storage_comprehensive_state.rs@@ -16,12 +16,12 @@ async fn test_storage_comprehensive_state_fresh_download_to_completion() -> Resutracing::info!("\n[SCENARIO_1] Fresh download to completion");let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::NotDownloaded), "Fresh model should be NotDownloaded");+ assert!(matches!(state.phase, DownloadPhase::NotDownloaded {}), "Fresh model should be NotDownloaded");// Set up progress bar- let pb = ProgressBar::new(state.total_bytes);+ let pb = ProgressBar::new(state.total_bytes as u64);pb.set_style(ProgressStyle::default_bar().template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%, {bytes_per_sec}) - {msg}")@@ -37,9 +37,9 @@ async fn test_storage_comprehensive_state_fresh_download_to_completion() -> Resulet monitor = tokio::spawn(async move {while let Ok(Some(Ok((id, state)))) = tokio::time::timeout(Duration::from_secs(120), updates.next()).await {- if id == test_storage.model(0).identifier() {- pb_clone.set_position(state.downloaded_bytes);- if matches!(state.phase, DownloadPhase::Downloaded) {+ if id == test_storage.model(0).identifier.clone() {+ pb_clone.set_position(state.downloaded_bytes as u64);+ if matches!(state.phase, DownloadPhase::Downloaded {}) {pb_clone.finish_with_message("✓ Downloaded");let _ = done_tx.send(()).await;break;@@ -52,7 +52,7 @@ async fn test_storage_comprehensive_state_fresh_download_to_completion() -> Resutokio::time::sleep(Duration::from_millis(300)).await;let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Downloading), "Should be Downloading after start");+ assert!(matches!(state.phase, DownloadPhase::Downloading {}), "Should be Downloading after start");// Wait for completion with timeoutlet completed = tokio::time::timeout(Duration::from_secs(600), done_rx.recv()).await;@@ -61,7 +61,7 @@ async fn test_storage_comprehensive_state_fresh_download_to_completion() -> Resuassert!(completed.is_ok(), "Download did not complete within timeout");let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Downloaded), "Should be Downloaded after completion");+ assert!(matches!(state.phase, DownloadPhase::Downloaded {}), "Should be Downloaded after completion");Ok(())}@@ -73,25 +73,25 @@ async fn test_storage_comprehensive_state_pause_and_resume() -> Result<(), Box<dlet base_path = temp_dir.path().to_path_buf();let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.download().await?;tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.pause().await?;tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Paused), "Should be Paused after pause command");+ assert!(matches!(state.phase, DownloadPhase::Paused {}), "Should be Paused after pause command");let paused_progress = state.progress();- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.download().await?;tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Downloading), "Should be Downloading after resume");+ assert!(matches!(state.phase, DownloadPhase::Downloading {}), "Should be Downloading after resume");assert!(state.progress() >= paused_progress, "Progress should not decrease after resume");Ok(())}@@ -105,13 +105,13 @@ async fn test_storage_comprehensive_state_pause_quit_relaunch_resume() -> Resultlet test_storage = TestStorage::new_with_base_path(base_path.clone()).await?;let storage = &test_storage.storage;- let model = storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.download().await?;tokio::time::sleep(std::time::Duration::from_millis(1000)).await;- let model = storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.pause().await?;tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model = storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;let paused_progress = state.progress();let model_dir = test_storage.config.clone().cache_model_path(&test_storage.model(0)).unwrap();@@ -136,9 +136,9 @@ async fn test_storage_comprehensive_state_pause_quit_relaunch_resume() -> Resultlet test_storage_2 = TestStorage::new_with_base_path(base_path).await?;let storage_2 = &test_storage_2.storage;let model =- storage_2.get(&test_storage_2.model(0).identifier()).await.ok_or("Model not found after relaunch")?;+ storage_2.get(&test_storage_2.model(0).identifier.clone()).await.ok_or("Model not found after relaunch")?;let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Paused), "Model should remain Paused after relaunch");+ assert!(matches!(state.phase, DownloadPhase::Paused {}), "Model should remain Paused after relaunch");assert!(state.progress() >= paused_progress, "Progress should not decrease after relaunch");let model_dir = test_storage_2.config.cache_model_path(&test_storage_2.model(0)).unwrap();if model_dir.exists() {@@ -160,12 +160,12 @@ async fn test_storage_comprehensive_state_pause_quit_relaunch_resume() -> Result);}}- let model = storage_2.get(&test_storage_2.model(0).identifier()).await.ok_or("Model not found")?;+ let model = storage_2.get(&test_storage_2.model(0).identifier.clone()).await.ok_or("Model not found")?;model.download().await?;tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = storage_2.get(&test_storage_2.model(0).identifier()).await.ok_or("Model not found")?;+ let model = storage_2.get(&test_storage_2.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Downloading), "Should be Downloading after resume");+ assert!(matches!(state.phase, DownloadPhase::Downloading {}), "Should be Downloading after resume");}Ok(())}@@ -177,18 +177,18 @@ async fn test_storage_comprehensive_state_delete_from_various_states() -> Resultlet base_path = temp_dir.path().to_path_buf();let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.download().await?;tokio::time::sleep(std::time::Duration::from_millis(1000)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.pause().await?;tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Paused), "Should be Paused");- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ assert!(matches!(state.phase, DownloadPhase::Paused {}), "Should be Paused");+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.cancel().await?;tokio::time::sleep(std::time::Duration::from_millis(300)).await;@@ -218,28 +218,35 @@ async fn test_storage_comprehensive_state_multiple_pause_resume_cycles() -> Resulet base_path = temp_dir.path().to_path_buf();let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.download().await?;tokio::time::sleep(std::time::Duration::from_millis(100)).await;for cycle in 1..=3 {- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model =+ test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.pause().await?;tokio::time::sleep(std::time::Duration::from_millis(100)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model =+ test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;let paused_progress = state.progress();assert!(- matches!(state.phase, DownloadPhase::Paused | DownloadPhase::Downloaded | DownloadPhase::Downloading),+ matches!(+ state.phase,+ DownloadPhase::Paused {} | DownloadPhase::Downloaded {} | DownloadPhase::Downloading {}+ ),"Should be Paused/Downloaded/Downloading in cycle {} (got {:?})",cycle,state.phase);- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model =+ test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.download().await?;tokio::time::sleep(std::time::Duration::from_millis(1000)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model =+ test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;assert!(state.progress() >= paused_progress, "Progress should not decrease in cycle {}", cycle);}@@ -255,7 +262,8 @@ async fn test_storage_comprehensive_state_completed_files_preserved_on_relaunch(let base_path = temp_dir.path().to_path_buf();let test_storage = TestStorage::new_with_base_path(base_path.clone()).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model =+ test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.download().await?;for _ in 0..30 {tokio::time::sleep(std::time::Duration::from_secs(1)).await;@@ -287,7 +295,8 @@ async fn test_storage_comprehensive_state_completed_files_preserved_on_relaunch(}}}- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model =+ test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.pause().await?;tokio::time::sleep(std::time::Duration::from_millis(500)).await;let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();@@ -327,9 +336,10 @@ async fn test_storage_comprehensive_state_completed_files_preserved_on_relaunch(name);}- let model = test_storage_2.storage.get(&test_storage_2.model(0).identifier()).await.ok_or("Model not found")?;+ let model =+ test_storage_2.storage.get(&test_storage_2.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Paused), "Model should be Paused after relaunch");+ assert!(matches!(state.phase, DownloadPhase::Paused {}), "Model should be Paused after relaunch");}Ok(())}@@ -341,24 +351,24 @@ async fn test_storage_comprehensive_state_idempotent_pause() -> Result<(), Box<dlet base_path = temp_dir.path().to_path_buf();let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.download().await?;tokio::time::sleep(std::time::Duration::from_millis(1000)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.pause().await?;tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;let progress_after_first_pause = state.progress();- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.pause().await?;tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Paused), "Should remain Paused after second pause");+ assert!(matches!(state.phase, DownloadPhase::Paused {}), "Should remain Paused after second pause");assert_eq!(state.progress(), progress_after_first_pause, "Progress should not change on idempotent pause");Ok(())}@@ -369,7 +379,7 @@ async fn test_storage_comprehensive_state_crc_validation_on_init() -> Result<(),let base_path = temp_dir.path().to_path_buf();let test_storage = TestStorage::new_with_base_path(base_path.clone()).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.download().await?;for _ in 0..60 {tokio::time::sleep(std::time::Duration::from_secs(1)).await;@@ -389,11 +399,12 @@ async fn test_storage_comprehensive_state_crc_validation_on_init() -> Result<(),}}// Check if download completed before we can pause- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await;if let Some(m) = model {let state = m.state().await;- if !matches!(state.phase, DownloadPhase::Downloaded) {- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ if !matches!(state.phase, DownloadPhase::Downloaded {}) {+ let model =+ test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.pause().await?;}}@@ -410,10 +421,14 @@ async fn test_storage_comprehensive_state_crc_validation_on_init() -> Result<(),assert!(tokenizer_path.exists(), "tokenizer.json should exist after relaunch");assert!(!config_resume.exists(), "config.json.resume_data should be deleted for complete file");assert!(!tokenizer_resume.exists(), "tokenizer.json.resume_data should be deleted for complete file");- let model = test_storage_2.storage.get(&test_storage_2.model(0).identifier()).await.ok_or("Model not found")?;+ let model =+ test_storage_2.storage.get(&test_storage_2.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;assert!(- matches!(state.phase, DownloadPhase::Paused | DownloadPhase::Downloading | DownloadPhase::Downloaded),+ matches!(+ state.phase,+ DownloadPhase::Paused {} | DownloadPhase::Downloading {} | DownloadPhase::Downloaded {}+ ),"Model should be in a valid state after relaunch (Paused, Downloading, or Downloaded)");}@@ -430,7 +445,8 @@ async fn test_storage_comprehensive_state_progress_calculation_with_mixed_files(let test_storage = TestStorage::new_with_base_path(base_path).await?;let expected_config_bytes = 2907;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model =+ test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.download().await?;let mut config_completed = false;for _ in 0..30 {@@ -445,13 +461,18 @@ async fn test_storage_comprehensive_state_progress_calculation_with_mixed_files(}}if config_completed {- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model =+ test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;model.pause().await?;tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model =+ test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;let state = model.state().await;let downloaded_bytes = state.downloaded_bytes;- assert!(downloaded_bytes >= expected_config_bytes, "Downloaded bytes should include completed config.json");+ assert!(+ downloaded_bytes >= expected_config_bytes as i64,+ "Downloaded bytes should include completed config.json"+ );}}Ok(())diff --git a/crates/uzu/tests/test_storage_concurrent_multi_model.rs b/crates/uzu/tests/test_storage_concurrent_multi_model.rsindex ac93af035..baeeeb3fb 100644--- a/crates/uzu/tests/test_storage_concurrent_multi_model.rs+++ b/crates/uzu/tests/test_storage_concurrent_multi_model.rs@@ -30,13 +30,13 @@ async fn test_storage_concurrent_multi_model_download() -> Result<(), Box<dyn st// Get the test model and create instancestracing::info!("[CONCURRENT_TEST] Fetching test model {}...", i);let model = test_storage.model(i).clone();- let item = test_storage.storage.get(&model.identifier()).await.ok_or("Model not found")?;+ let item = test_storage.storage.get(&model.identifier.clone()).await.ok_or("Model not found")?;// Cancel first to ensure it's not already downloadedtracing::info!("[CONCURRENT_TEST] Canceling model {} to ensure fresh download...", i);item.cancel().await?;tokio::time::sleep(Duration::from_millis(500)).await;- models.push((model.identifier(), item.clone()));+ models.push((model.identifier.clone(), item.clone()));}tracing::info!("[CONCURRENT_TEST] ✓ Created {} model instances", models.len());@@ -69,7 +69,7 @@ async fn test_storage_concurrent_multi_model_download() -> Result<(), Box<dyn stlet progress_check = tokio::time::timeout(Duration::from_secs(10), async {while let Some(Ok((id, state))) = progress_stream.next().await {- if matches!(state.phase, DownloadPhase::Downloading | DownloadPhase::Downloaded) {+ if matches!(state.phase, DownloadPhase::Downloading {} | DownloadPhase::Downloaded {}) {progress_count += 1;if progress_count <= 5 || progress_count % 10 == 0 {tracing::info!(@@ -103,7 +103,7 @@ async fn test_storage_concurrent_multi_model_download() -> Result<(), Box<dyn ststate.total_bytes);assert!(- matches!(state.phase, DownloadPhase::Downloading | DownloadPhase::Downloaded),+ matches!(state.phase, DownloadPhase::Downloading {} | DownloadPhase::Downloaded {}),"Model {} should be downloading or downloaded, got {:?}",id,state.phase@@ -139,7 +139,7 @@ async fn test_storage_concurrent_multi_model_download() -> Result<(), Box<dyn stlet mut paused_count = 0;for (_, model) in &models {let state = model.state().await;- if matches!(state.phase, DownloadPhase::Paused | DownloadPhase::Downloaded) {+ if matches!(state.phase, DownloadPhase::Paused {} | DownloadPhase::Downloaded {}) {paused_count += 1;}}@@ -165,7 +165,7 @@ async fn test_storage_concurrent_multi_model_download() -> Result<(), Box<dyn ststate.total_bytes);assert!(- matches!(state.phase, DownloadPhase::Paused | DownloadPhase::Downloaded),+ matches!(state.phase, DownloadPhase::Paused {} | DownloadPhase::Downloaded {}),"Model {} should be paused or downloaded after pause, got {:?}",id,state.phase@@ -239,7 +239,7 @@ async fn test_storage_concurrent_multi_model_download() -> Result<(), Box<dyn stfor (idx, (_, model)) in models.iter().enumerate() {if idx < cancel_count {let state = model.state().await;- if matches!(state.phase, DownloadPhase::NotDownloaded) {+ if matches!(state.phase, DownloadPhase::NotDownloaded {}) {cancelled_count += 1;}}@@ -261,7 +261,7 @@ async fn test_storage_concurrent_multi_model_download() -> Result<(), Box<dyn stif idx < cancel_count {tracing::info!("[CONCURRENT_TEST] Cancelled model {} state: phase={:?}", id, state.phase);assert!(- matches!(state.phase, DownloadPhase::NotDownloaded),+ matches!(state.phase, DownloadPhase::NotDownloaded {}),"Cancelled model {} should be NotDownloaded, got {:?}",id,state.phase@@ -301,7 +301,7 @@ async fn test_storage_concurrent_multi_model_download() -> Result<(), Box<dyn ststate.downloaded_bytes,state.total_bytes);- if update_count >= 5 || matches!(state.phase, DownloadPhase::Downloaded) {+ if update_count >= 5 || matches!(state.phase, DownloadPhase::Downloaded {}) {break;}}diff --git a/crates/uzu/tests/test_storage_debug_file_preservation.rs b/crates/uzu/tests/test_storage_debug_file_preservation.rsindex aade71ae5..9e05c67df 100644--- a/crates/uzu/tests/test_storage_debug_file_preservation.rs+++ b/crates/uzu/tests/test_storage_debug_file_preservation.rs@@ -20,13 +20,13 @@ async fn test_storage_debug_file_preservation_complete_app_relaunch_resume() ->let runtime = tokio::runtime::Runtime::new().unwrap();runtime.block_on(async {let test_storage = TestStorage::new_with_base_path(base_path_clone).await.unwrap();- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();- tracing::info!("[S1] Starting download for {}", test_storage.model(0).identifier());+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();+ tracing::info!("[S1] Starting download for {}", test_storage.model(0).identifier.clone());model.download().await.unwrap();let mut reached_target = false;for i in 0..180 {tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();tracing::info!("[S1] Iteration {}: pausing model", i);model.pause().await.unwrap();let state = model.state().await;@@ -47,11 +47,11 @@ async fn test_storage_debug_file_preservation_complete_app_relaunch_resume() ->model.download().await.unwrap();}assert!(reached_target, "Failed to reach target progress");- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();tracing::info!("[S1] Pausing before shutdown");model.pause().await.unwrap();tokio::time::sleep(std::time::Duration::from_millis(1000)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model.state().await;let progress = state.progress();let bytes = state.downloaded_bytes;@@ -108,7 +108,7 @@ async fn test_storage_debug_file_preservation_complete_app_relaunch_resume() ->);}- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model.state().await;let progress_session2 = state.progress();let bytes_session2 = state.downloaded_bytes;@@ -129,7 +129,7 @@ async fn test_storage_debug_file_preservation_complete_app_relaunch_resume() ->tracing::info!("[S2] Resuming download after relaunch");model.download().await.unwrap();tokio::time::sleep(std::time::Duration::from_millis(200)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model.state().await;let progress_after_resume = state.progress();let bytes_after_resume = state.downloaded_bytes;@@ -163,12 +163,12 @@ async fn test_storage_debug_file_preservation_resume_from_20_percent() -> Resultlet (progress_at_pause, bytes_at_pause, _total_bytes);{let test_storage = TestStorage::new_with_base_path(base_path_clone).await.unwrap();- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();model.download().await.unwrap();let mut reached_target = false;for i in 0..180 {tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model.state().await;let progress = state.progress();let _downloaded = state.downloaded_bytes;@@ -182,23 +182,23 @@ async fn test_storage_debug_file_preservation_resume_from_20_percent() -> Resultif !reached_target {return Err("Failed to reach target progress range in time".into());}- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();model.pause().await?;for i in 0..20 {tokio::time::sleep(std::time::Duration::from_millis(200)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model.state().await;- if matches!(state.phase, DownloadPhase::Paused) {+ if matches!(state.phase, DownloadPhase::Paused {}) {break;}if i == 19 {}}- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model.state().await;progress_at_pause = state.progress();bytes_at_pause = state.downloaded_bytes;_total_bytes = state.total_bytes;- if !matches!(state.phase, DownloadPhase::Paused) {}+ if !matches!(state.phase, DownloadPhase::Paused {}) {}let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();let mut resume_files = Vec::new();if model_dir.exists() {@@ -240,11 +240,11 @@ async fn test_storage_debug_file_preservation_resume_from_20_percent() -> Resultlet _meta = entry.metadata().await?;}}- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model.state().await;let progress_after_relaunch = state.progress();let bytes_after_relaunch = state.downloaded_bytes;- assert!(matches!(state.phase, DownloadPhase::Paused), "Model should be Paused after relaunch");+ assert!(matches!(state.phase, DownloadPhase::Paused {}), "Model should be Paused after relaunch");let progress_diff = (progress_at_pause - progress_after_relaunch).abs();let _bytes_diff = (bytes_at_pause as i64 - bytes_after_relaunch as i64).abs();assert!(@@ -273,10 +273,10 @@ async fn test_storage_debug_file_preservation_resume_from_20_percent() -> Result}}}- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();model.download().await?;tokio::time::sleep(std::time::Duration::from_millis(100)).await;- let model_immediate = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model_immediate = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model_immediate.state().await;let progress_immediate = state.progress();let bytes_immediate = state.downloaded_bytes;@@ -294,10 +294,10 @@ async fn test_storage_debug_file_preservation_resume_from_20_percent() -> Result);}tokio::time::sleep(std::time::Duration::from_secs(1)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();model.pause().await?;tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model.state().await;let progress_after_resume = state.progress();let bytes_after_resume = state.downloaded_bytes;@@ -328,7 +328,7 @@ async fn test_storage_debug_file_preservation_completed_file_detection() -> Resulet (_progress_after_pause, downloaded_bytes_after_pause);{let test_storage = TestStorage::new_with_base_path(base_dir_clone).await.unwrap();- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();model.download().await?;let mut config_done = false;let mut tokenizer_done = false;@@ -357,16 +357,16 @@ async fn test_storage_debug_file_preservation_completed_file_detection() -> Resu}// Check if download is already complete before trying to pause- let model_before_pause = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model_before_pause = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model_before_pause.state().await;- if !matches!(state.phase, DownloadPhase::Downloaded) {- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ if !matches!(state.phase, DownloadPhase::Downloaded {}) {+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();model.pause().await?;tokio::time::sleep(std::time::Duration::from_millis(500)).await;}- let model_paused = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model_paused = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model_paused.state().await;_progress_after_pause = state.progress();downloaded_bytes_after_pause = state.downloaded_bytes;@@ -383,12 +383,12 @@ async fn test_storage_debug_file_preservation_completed_file_detection() -> Resulet _meta = entry.metadata().await?;}}- let model_relaunched = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model_relaunched = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model_relaunched.state().await;let _progress_after_relaunch = state.progress();let downloaded_bytes_after_relaunch = state.downloaded_bytes;assert!(- matches!(state.phase, DownloadPhase::Paused | DownloadPhase::Downloaded),+ matches!(state.phase, DownloadPhase::Paused {} | DownloadPhase::Downloaded {}),"Model should be Paused or Downloaded after relaunch, got: {:?}",state.phase);@@ -411,18 +411,21 @@ async fn test_storage_debug_file_preservation_completed_file_detection() -> Resu// Only try to resume if not already downloadedlet state = model_relaunched.state().await;- if !matches!(state.phase, DownloadPhase::Downloaded) {- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ if !matches!(state.phase, DownloadPhase::Downloaded {}) {+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();model.download().await?;tokio::time::sleep(std::time::Duration::from_millis(2000)).await;}- let model_resumed = test_storage.storage.get(&test_storage.model(0).identifier()).await.unwrap();+ let model_resumed = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();let state = model_resumed.state().await;let _progress_after_resume = state.progress();let downloaded_bytes_after_resume = state.downloaded_bytes;assert!(- matches!(state.phase, DownloadPhase::Downloading | DownloadPhase::Paused | DownloadPhase::Downloaded),+ matches!(+ state.phase,+ DownloadPhase::Downloading {} | DownloadPhase::Paused {} | DownloadPhase::Downloaded {}+ ),"Model should be Downloading, Paused, or Downloaded after resume, got: {:?}",state.phase);diff --git a/crates/uzu/tests/test_storage_stall_detection.rs b/crates/uzu/tests/test_storage_stall_detection.rsindex 54772a941..1ef5db87e 100644--- a/crates/uzu/tests/test_storage_stall_detection.rs+++ b/crates/uzu/tests/test_storage_stall_detection.rs@@ -15,7 +15,7 @@ async fn test_stall_detection_no_progress() -> Result<(), Box<dyn std::error::Erlet temp_dir = tempfile::tempdir()?;let base_path = temp_dir.path().to_path_buf();let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;tracing::info!("[STALL_TEST] Starting download...");model.download().await?;@@ -33,21 +33,21 @@ async fn test_stall_detection_no_progress() -> Result<(), Box<dyn std::error::Erloop {tokio::select! {Some(Ok((id, state))) = progress_stream.next() => {- if id == test_storage.model(0).identifier() {+ if id == test_storage.model(0).identifier.clone() {let current_bytes = state.downloaded_bytes;- if current_bytes > last_bytes {+ if current_bytes > last_bytes as i64 {let elapsed = last_progress_time.elapsed();tracing::info!("[STALL_TEST] Progress: {} bytes (delta: {}, time_since_last: {:?})",current_bytes,- current_bytes - last_bytes,+ current_bytes - last_bytes as i64,elapsed);- last_bytes = current_bytes;+ last_bytes = current_bytes as u64;last_progress_time = std::time::Instant::now();}- if matches!(state.phase, DownloadPhase::Downloaded) {+ if matches!(state.phase, DownloadPhase::Downloaded {}) {tracing::info!("[STALL_TEST] ✓ Download completed");return Ok::<_, String>(());}@@ -113,7 +113,7 @@ async fn test_stall_detection_broadcast_liveness() -> Result<(), Box<dyn std::erlet temp_dir = tempfile::tempdir()?;let base_path = temp_dir.path().to_path_buf();let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier()).await.ok_or("Model not found")?;+ let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;tracing::info!("[BROADCAST_TEST] Starting download...");model.download().await?;@@ -127,7 +127,7 @@ async fn test_stall_detection_broadcast_liveness() -> Result<(), Box<dyn std::erlet broadcast_check = tokio::time::timeout(Duration::from_secs(30), async {while let Some(Ok((id, state))) = progress_stream.next().await {- if id == test_storage.model(0).identifier() {+ if id == test_storage.model(0).identifier.clone() {let gap = last_update_time.elapsed();update_count += 1;@@ -153,7 +153,7 @@ async fn test_stall_detection_broadcast_liveness() -> Result<(), Box<dyn std::erlast_update_time = std::time::Instant::now();// Stop after 100 updates or completion- if update_count >= 100 || matches!(state.phase, DownloadPhase::Downloaded) {+ if update_count >= 100 || matches!(state.phase, DownloadPhase::Downloaded {}) {return Ok::<_, String>(update_count);}}diff --git a/deny.toml b/deny.tomlindex 0519c8b89..ef133f6f3 100644--- a/deny.toml+++ b/deny.toml@@ -6,6 +6,7 @@ ignore = ["RUSTSEC-2025-0057", # fxhash - no longer maintained"RUSTSEC-2024-0384", # instant is unmaintained"RUSTSEC-2025-0012", # backoff is unmaintained+ "RUSTSEC-2026-0104", # reachable panic in certificate revocation list parsing][licenses]diff --git a/workspace/.gitignore b/workspace/.gitignoreindex 6ea887496..b88365c94 100644--- a/workspace/.gitignore+++ b/workspace/.gitignore@@ -1 +1,2 @@-models/\ No newline at end of file+models/+release/\ No newline at end of file