commit 597ac432e13fd6d17c79d396cd9a4a3dfae3e0e4 Author: iz0eyj Date: Tue Nov 24 05:28:56 2026 +0100 strata-ctl: Rust control layer for the Strata engine (OpenAI-compatible API) From-scratch rewrite of the Python serve (Python kept as behavioral spec). - engine: line-protocol supervisor (GEN/T/DONE/STOP/QUIT), silence watchdog, abort, is_idle probe. - config: tolerant shared-JSON loader; foreign keys ignored so one file drives strata-ctl and uostream; CLI --config/--host/--port/--serve. - inkling: o200k tokenizer wrapper + incremental UTF-8-safe detok; chat template via minijinja; channel-token dialect (reasoning streamed live); image bridge (in-process Vision, image=); formatter assembling the API seam. - api: /v1/chat/completions (stream SSE + non-stream), /v1/models, /health; reasoning_content; structured tool_calls (llama.cpp --jinja style, client-side execution); stop sequences with hold-back; abort on client disconnect. 69 tests green + 2 real-file ignored; clippy clean. Text, images and tools validated live against the real Inkling engine. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c403c34 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +.idea/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..2eb9f26 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2290 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fca89247609239eeb6915e6991111866b92d7b31025e69302bbf430cc4d2c38" +dependencies = [ + "cfg-if", + "getrandom 0.4.3", + "once_cell", + "serde", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey 0.1.1", + "rayon", + "thiserror", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom 8.0.0", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "serde", + "static_assertions", +] + +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "unicode-width", + "windows-sys 0.61.2", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "daachorse" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5614204febbc33cc07a2806aa6440b904ac012b68eecc37f4493ea4a76455a3d" + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dary_heap" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe" +dependencies = [ + "serde", +] + +[[package]] +name = "derive_builder" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "derive_builder_macro" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" +dependencies = [ + "derive_builder_core", + "syn 2.0.119", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "esaxx-rs" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6" +dependencies = [ + "cc", +] + +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "wasm-bindgen", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "qoi", + "ravif", + "rayon", + "rgb", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + +[[package]] +name = "indicatif" +version = "0.18.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9433806cd6b4ec1aba79c021c7e4c58fb4c3b9977c085062e611ac929998fb0c" +dependencies = [ + "console", + "portable-atomic", + "unicode-width", + "unit-prefix", + "web-time", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "macro_rules_attribute" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c" +dependencies = [ + "macro_rules_attribute-proc_macro", + "pastey 0.2.3", +] + +[[package]] +name = "macro_rules_attribute-proc_macro" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "minijinja" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "509eeb2603a84eccabb4d75f6ec8ba23b46bbf441aaeb863d6b83a5887fd51e4" +dependencies = [ + "serde", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "monostate" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67" +dependencies = [ + "monostate-impl", + "serde", + "serde_core", +] + +[[package]] +name = "monostate-impl" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "onig" +version = "6.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2" +dependencies = [ + "bitflags", + "libc", + "once_cell", + "onig_sys", +] + +[[package]] +name = "onig_sys" +version = "69.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e68317604e77e53b85896388e1a803c1d21b74c899ec9e5e1112db90735edd7" +dependencies = [ + "cc", + "pkg-config", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand", + "rand_chacha", + "simd_helpers", + "thiserror", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-cond" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f" +dependencies = [ + "either", + "itertools", + "rayon", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spm_precompiled" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326" +dependencies = [ + "base64 0.13.1", + "nom 7.1.3", + "serde", + "unicode-segmentation", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strata-ctl" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "base64 0.23.1", + "futures", + "http-body-util", + "image", + "minijinja", + "serde", + "serde_json", + "thiserror", + "tokenizers", + "tokio", + "tokio-stream", + "tower", + "tracing", + "ureq", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "tokenizers" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7afbf6e88718afcc138bad01d6ccc3051dbbc3b2ce9793d8b8a3aeb610969cfc" +dependencies = [ + "ahash", + "compact_str", + "daachorse", + "dary_heap", + "derive_builder", + "esaxx-rs", + "getrandom 0.3.4", + "indicatif", + "itertools", + "log", + "macro_rules_attribute", + "monostate", + "onig", + "paste", + "rand", + "rayon", + "rayon-cond", + "regex", + "regex-syntax", + "serde", + "serde_json", + "spm_precompiled", + "thiserror", + "unicode-normalization-alignments", + "unicode-segmentation", + "unicode_categories", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization-alignments" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de" +dependencies = [ + "smallvec", +] + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "unicode_categories" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" + +[[package]] +name = "unit-prefix" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..e2e5c26 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "strata-ctl" +version = "0.1.0" +edition = "2021" +description = "Rust control layer for the Strata inference engine: OpenAI-compatible HTTP API over the engine's line protocol" +license = "MIT" + +[dependencies] +anyhow = "1" +thiserror = "2" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", features = ["rt-multi-thread", "process", "io-util", "sync", "time", "macros", "signal", "net"] } +tracing = "0.1" +axum = "0.8" +futures = "0.3.34" +tokio-stream = "0.1.19" +tokenizers = "0.23.2" +minijinja = { version = "3.1.0", features = ["serde"] } +image = "0.25.10" +base64 = "0.23.1" +ureq = "3.5.2" + +[dev-dependencies] +http-body-util = "0.1.5" +tokio = { version = "1", features = ["full"] } +tower = { version = "0.5", features = ["util"] } diff --git a/examples/serve_mock.rs b/examples/serve_mock.rs new file mode 100644 index 0000000..1e4b00f --- /dev/null +++ b/examples/serve_mock.rs @@ -0,0 +1,93 @@ +//! Live smoke demo of the OpenAI surface over a real TCP socket, driven by the +//! scripted mock engine (tests/mock_engine.py) and a byte-level formatter — so +//! you can `curl` it without a GPU or the Inkling tokenizer. +//! +//! cargo run --example serve_mock # listens on 127.0.0.1:8080 +//! +//! curl -s localhost:8080/v1/models +//! curl -s localhost:8080/v1/chat/completions -H 'content-type: application/json' \ +//! -d '{"model":"mock","messages":[{"role":"user","content":"hi"}]}' +//! # streaming (watch the SSE flush token by token): +//! curl -N localhost:8080/v1/chat/completions -H 'content-type: application/json' \ +//! -d '{"model":"mock","messages":[{"role":"user","content":"hi"}],"stream":true}' + +use std::sync::Arc; +use std::time::Duration; + +use strata_ctl::api::formatter::{Decoder, Formatter, Piece, Prompt}; +use strata_ctl::api::service::ChatService; +use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest}; +use strata_ctl::engine::Engine; + +const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py"); + +struct ByteFormatter; +impl Formatter for ByteFormatter { + fn model_name(&self) -> &str { + "mock" + } + fn build_prompt(&self, req: &ChatRequest) -> Result { + let text = req + .messages + .iter() + .rev() + .find_map(|m| m.text()) + .unwrap_or("") + .to_string(); + Ok(Prompt { + ids: text.bytes().map(u32::from).collect(), + max_new: req.max_new(64), + sampling: Default::default(), + temp_files: Vec::new(), + }) + } + fn decoder(&self) -> Box { + Box::new(ByteDecoder) + } +} +struct ByteDecoder; +impl Decoder for ByteDecoder { + fn push(&mut self, id: u32) -> Vec { + if id < 256 { + vec![Piece::Content(char::from(id as u8).to_string())] + } else { + Vec::new() + } + } + fn finish(&mut self, _reason: Option<&str>) -> Vec { + Vec::new() + } +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let engine = Arc::new( + Engine::start( + "python3", + &[MOCK.to_string()], + None, + Duration::from_secs(15), + ) + .await + .expect("failed to start the mock engine (is python3 available?)"), + ); + println!( + "mock engine READY, context {} tokens", + engine.ready().max_context + ); + + let svc = ChatService::new(engine.clone(), Arc::new(ByteFormatter)); + let app = strata_ctl::api::router(svc); + + let addr = std::env::var("ADDR").unwrap_or_else(|_| "127.0.0.1:8080".into()); + let listener = tokio::net::TcpListener::bind(&addr).await?; + println!("listening on http://{addr} (Ctrl-C to stop)"); + axum::serve(listener, app) + .with_graceful_shutdown(async move { + let _ = tokio::signal::ctrl_c().await; + println!("\nshutting down"); + let _ = engine.shutdown().await; + }) + .await?; + Ok(()) +} diff --git a/src/api/formatter.rs b/src/api/formatter.rs new file mode 100644 index 0000000..68438ac --- /dev/null +++ b/src/api/formatter.rs @@ -0,0 +1,137 @@ +//! The seam between the HTTP/OpenAI layer and the token-level engine. +//! +//! The engine only ever sees and emits **token ids**. Everything that turns +//! chat messages into a token prompt, and the token stream back into text +//! split across reasoning / answer / tool calls, lives behind [`Formatter`] — +//! which the Inkling chat template + HF tokenizer + dialect parser will +//! implement. Keeping it a trait means the whole API layer (routing, +//! streaming, usage, finish reasons) is buildable and testable now, against a +//! trivial formatter, without the tokenizer wired up yet. + +use crate::engine::{EngineError, Sampling}; + +use super::types::{ApiErrorEnvelope, ChatRequest}; + +/// What the engine needs for one generation: the prompt ids, a token budget, +/// and the per-request sampling keys. +#[derive(Debug, Clone)] +pub struct Prompt { + pub ids: Vec, + pub max_new: u32, + pub sampling: Sampling, + /// Per-request temp files (e.g. materialized images) the service removes + /// once generation is done. Empty for text-only requests. + pub temp_files: Vec, +} + +/// A decoded slice of the model's output, already classified. The formatter +/// decides what is thinking and what is the answer; the API layer just routes +/// them to `reasoning_content` vs `content`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Piece { + Reasoning(String), + Content(String), + /// A structured tool call parsed from the model output. `arguments` is the + /// JSON-encoded argument object, as OpenAI's `function.arguments` string. + ToolCall { + name: String, + arguments: String, + }, +} + +impl Piece { + pub fn is_empty(&self) -> bool { + match self { + Piece::Reasoning(s) | Piece::Content(s) => s.is_empty(), + Piece::ToolCall { .. } => false, + } + } +} + +/// Incremental token->text decoder for one in-flight request. Fed one id at a +/// time as the engine streams `T`; may buffer (a BPE/dialect parser rarely +/// yields a whole grapheme per token) and returns zero or more pieces. +pub trait Decoder: Send { + fn push(&mut self, id: u32) -> Vec; + /// Flush any held partial at end of stream. `reason` is the engine's finish + /// word (`"length"`, `"stop"`, ...): some dialects surface truncated + /// thinking only when the budget expired. + fn finish(&mut self, reason: Option<&str>) -> Vec; +} + +/// Messages <-> tokens + output parsing, for a specific model dialect. +pub trait Formatter: Send + Sync { + /// The id this formatter serves (reported in `/v1/models` and responses). + fn model_name(&self) -> &str; + + /// The formatter's default token budget when the request sets none. + fn default_max_new(&self) -> u32 { + 2048 + } + + /// Render the conversation to a prompt and derive the engine request. + /// Errors map straight to an HTTP 400. + fn build_prompt(&self, req: &ChatRequest) -> Result; + + /// A fresh output decoder for one request. + fn decoder(&self) -> Box; +} + +/// Convenience: run a decoder over a whole id slice (the non-streaming path). +pub fn decode_all(dec: &mut dyn Decoder, ids: &[u32], reason: Option<&str>) -> Vec { + let mut out = Vec::new(); + for &id in ids { + out.extend(dec.push(id)); + } + out.extend(dec.finish(reason)); + out +} + +/// Collapse pieces into (reasoning, content) strings. +pub fn split_pieces(pieces: Vec) -> (String, String) { + let mut reasoning = String::new(); + let mut content = String::new(); + for p in pieces { + match p { + Piece::Reasoning(s) => reasoning.push_str(&s), + Piece::Content(s) => content.push_str(&s), + Piece::ToolCall { .. } => {} + } + } + (reasoning, content) +} + +/// Everything a decoder produced, collapsed: reasoning text, answer text, and +/// the structured tool calls (name, JSON-encoded arguments) in emission order. +#[derive(Debug, Clone, Default)] +pub struct Decoded { + pub reasoning: String, + pub content: String, + pub tool_calls: Vec<(String, String)>, +} + +/// Collapse pieces into a [`Decoded`], keeping tool calls structured. +pub fn decode_pieces(pieces: Vec) -> Decoded { + let mut d = Decoded::default(); + for p in pieces { + match p { + Piece::Reasoning(s) => d.reasoning.push_str(&s), + Piece::Content(s) => d.content.push_str(&s), + Piece::ToolCall { name, arguments } => d.tool_calls.push((name, arguments)), + } + } + d +} + +/// Map an engine failure to an OpenAI error envelope + HTTP status code. +pub fn engine_error(err: EngineError) -> (u16, ApiErrorEnvelope) { + use crate::engine::EngineError::*; + let (status, kind, code) = match &err { + Refused(_) => (400, "invalid_request_error", Some("engine_refused")), + Silent(_) => (504, "engine_error", Some("engine_silent")), + Died | Spawn(_) => (503, "engine_error", Some("engine_unavailable")), + Startup(_) => (503, "engine_error", Some("engine_startup")), + }; + let envelope = ApiErrorEnvelope::bad_request(err.to_string(), kind, code.map(str::to_string)); + (status, envelope) +} diff --git a/src/api/mod.rs b/src/api/mod.rs new file mode 100644 index 0000000..c38790e --- /dev/null +++ b/src/api/mod.rs @@ -0,0 +1,16 @@ +//! The OpenAI-compatible HTTP API. +//! +//! Layers on top of [`crate::engine`]: [`types`] is the wire contract, +//! [`formatter`] the token<->text seam, [`service`] the completion logic, and +//! [`routes`] the axum router. + +pub mod formatter; +pub mod routes; +pub mod service; +pub mod stop; +pub mod types; + +pub use formatter::{Decoder, Formatter, Piece, Prompt}; +pub use routes::router; +pub use service::ChatService; +pub use types::{ChatMessage, ChatRequest, ChatResponse, ModelList, Role}; diff --git a/src/api/routes.rs b/src/api/routes.rs new file mode 100644 index 0000000..55a3780 --- /dev/null +++ b/src/api/routes.rs @@ -0,0 +1,130 @@ +//! The HTTP surface: routing, request extraction, and OpenAI-shaped errors. +//! +//! `POST /v1/chat/completions` (stream and non-stream) and `GET /v1/models`, +//! plus a tiny `/health`. The handlers are thin: they delegate all behaviour +//! to [`ChatService`] and only decide status codes and envelopes. + +use axum::extract::State; +use axum::http::StatusCode; +use axum::response::{sse::Sse, IntoResponse, Json}; +use axum::routing::{get, post}; +use axum::Router; +use serde::de::DeserializeOwned; + +use super::service::ChatService; +use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList}; + +/// Build the router. Mount this inside any axum `Router` or serve it directly. +pub fn router(service: ChatService) -> Router { + Router::new() + .route("/health", get(health)) + .route("/v1/models", get(models)) + .route("/v1/chat/completions", post(chat_completions)) + .with_state(AppState { service }) +} + +#[derive(Clone)] +struct AppState { + service: ChatService, +} + +/// An OpenAI error with the HTTP status the code implies. +pub struct Error { + status: StatusCode, + body: ApiErrorEnvelope, +} + +impl Error { + fn new(status: StatusCode, body: ApiErrorEnvelope) -> Self { + Self { status, body } + } + + /// Choose a status from the error's `code`; unknown codes are client 400s. + fn from_envelope(env: ApiErrorEnvelope) -> Self { + let status = match env.error.code.as_deref() { + Some("engine_unavailable") | Some("engine_startup") => StatusCode::SERVICE_UNAVAILABLE, + Some("engine_silent") => StatusCode::GATEWAY_TIMEOUT, + // engine_refused, and any client/parse error, is a 400 + _ => StatusCode::BAD_REQUEST, + }; + Self::new(status, env) + } + + fn bad_request(msg: impl Into) -> Self { + Self::new( + StatusCode::BAD_REQUEST, + ApiErrorEnvelope::new(msg, "invalid_request_error", None), + ) + } +} + +impl IntoResponse for Error { + fn into_response(self) -> axum::response::Response { + (self.status, Json(self.body)).into_response() + } +} + +async fn health() -> &'static str { + "ok" +} + +async fn models(State(st): State) -> Json { + Json(ModelList { + object: "list", + data: vec![ModelCard { + id: st.service.model_name().to_string(), + object: "model", + created: super::types::now_unix(), + owned_by: "strata-ctl".to_string(), + }], + }) +} + +async fn chat_completions( + State(st): State, + raw: axum::extract::Request, +) -> axum::response::Response { + // Parse manually so a malformed body yields an OpenAI-shaped 400 rather + // than axum's default plain-text rejection. + let req: ChatRequest = match json_body(raw).await { + Ok(r) => r, + Err(e) => return e.into_response(), + }; + + if req.messages.is_empty() { + return Error::bad_request("`messages` must not be empty").into_response(); + } + + if req.stream { + match st.service.stream(&req).await { + Ok(stream) => { + use futures::StreamExt; + // Sse wants Stream>; our channel yields + // plain Events, so lift them (errors are infallible here). + let stream = stream.map(Ok::<_, std::convert::Infallible>); + Sse::new(stream) + .keep_alive( + axum::response::sse::KeepAlive::new() + .interval(std::time::Duration::from_secs(10)) + .text("ping"), + ) + .into_response() + } + Err(env) => Error::from_envelope(env).into_response(), + } + } else { + match st.service.complete(&req).await { + Ok(resp) => Json(resp).into_response(), + Err(env) => Error::from_envelope(env).into_response(), + } + } +} + +/// Read and deserialize a JSON body, mapping any failure to our error type. +async fn json_body(req: axum::extract::Request) -> Result { + let bytes = axum::body::to_bytes(req.into_body(), 32 * 1024 * 1024) + .await + .map_err(|e| Error::bad_request(format!("failed to read body: {e}")))?; + serde_json::from_slice::(&bytes) + .map_err(|e| Error::bad_request(format!("invalid JSON body: {e}"))) +} diff --git a/src/api/service.rs b/src/api/service.rs new file mode 100644 index 0000000..9fb8a6b --- /dev/null +++ b/src/api/service.rs @@ -0,0 +1,346 @@ +//! The completion service: turns an OpenAI request into engine calls and +//! back into OpenAI responses, driving the [`Formatter`] seam and the shared +//! [`Engine`]. +//! +//! Non-streaming runs the engine to completion and decodes the whole token +//! list. Streaming bridges the engine's token callback to an SSE stream over a +//! channel: a background task owns the request (and thus the engine's lock) +//! while the HTTP handler just forwards what the task puts on the channel. + +use std::sync::Arc; + +use axum::response::sse::Event; +use futures::Stream; +use tokio::sync::mpsc::UnboundedSender; +use tokio_stream::wrappers::UnboundedReceiverStream; + +use crate::engine::{Engine, EngineLine, Outcome}; + +use super::formatter::{self, Formatter, Piece}; +use super::stop::StopFilter; +use super::types::{ + completion_id, now_unix, tool_call_id, ApiErrorEnvelope, ChatChunk, ChatMessage, ChatRequest, + ChatResponse, Choice, Delta, FinishReason, FunctionCall, Role, StreamChoice, ToolCall, Usage, +}; + +/// Shared handle passed around the HTTP layer. +#[derive(Clone)] +pub struct ChatService { + engine: Arc, + fmt: Arc, +} + +impl ChatService { + pub fn new(engine: Arc, fmt: Arc) -> Self { + Self { engine, fmt } + } + + pub fn model_name(&self) -> &str { + self.fmt.model_name() + } + + /// One-shot completion. + pub async fn complete(&self, req: &ChatRequest) -> Result { + let prompt = self.fmt.build_prompt(req)?; + let outcome = self + .engine + .generate(prompt.max_new, &prompt.sampling, &prompt.ids, |_| {}) + .await + .map_err(formatter_error)?; + + // drop per-request temp files (materialized images) now generation is done + for p in &prompt.temp_files { + let _ = std::fs::remove_file(p); + } + + let mut dec = self.fmt.decoder(); + let reason = outcome.done.as_ref().map(|d| d.finish.as_str()); + let decoded = + formatter::decode_pieces(formatter::decode_all(dec.as_mut(), &outcome.tokens, reason)); + + // Structured tool calls (llama.cpp --jinja behaviour): the client executes + // them; finish_reason becomes "tool_calls" when any were produced. + let tool_calls: Vec = decoded + .tool_calls + .iter() + .map(|(name, arguments)| ToolCall { + id: tool_call_id(), + kind: "function".to_string(), + function: FunctionCall { + name: name.clone(), + arguments: arguments.clone(), + }, + }) + .collect(); + let has_tools = !tool_calls.is_empty(); + let stops = req.stop.clone().map(|s| s.into_vec()).unwrap_or_default(); + let (content, stop_hit) = super::stop::truncate_at_stop(&decoded.content, &stops); + let finish = if has_tools { + FinishReason::ToolCalls + } else if stop_hit { + FinishReason::Stop + } else { + finish_reason(&outcome, prompt.max_new) + }; + + Ok(ChatResponse { + id: completion_id(), + object: "chat.completion", + created: now_unix(), + model: req.model.clone(), + choices: vec![Choice { + index: 0, + message: ChatMessage { + role: Role::Assistant, + content: (!content.is_empty()).then_some(serde_json::Value::String(content)), + tool_call_id: None, + tool_calls: has_tools.then_some(tool_calls), + name: None, + reasoning_content: (!decoded.reasoning.is_empty()).then_some(decoded.reasoning), + }, + finish_reason: finish, + }], + usage: usage_of( + &outcome, + prompt.ids.len() as u32, + outcome.tokens.len() as u32, + ), + }) + } + + /// Streaming completion: an SSE item stream. `build_prompt` errors surface + /// synchronously (as `Err`) so the handler can still answer with a plain + /// HTTP error before any bytes are sent. + pub async fn stream( + &self, + req: &ChatRequest, + ) -> Result + Send + 'static, ApiErrorEnvelope> { + let prompt = self.fmt.build_prompt(req)?; + + let id = completion_id(); + let created = now_unix(); + let model = req.model.clone(); + + // Unbounded: the token callback is synchronous and must never block on + // (or lose events to) backpressure; a request is bounded by max_new. + let (tx, rx) = tokio::sync::mpsc::unbounded_channel::(); + let engine = self.engine.clone(); + let fmt = self.fmt.clone(); + + let (p_ids, p_max, p_sampling, p_temp) = ( + prompt.ids, + prompt.max_new, + prompt.sampling, + prompt.temp_files, + ); + let p_stops = req.stop.clone().map(|s| s.into_vec()).unwrap_or_default(); + tokio::spawn(async move { + // Open the stream the way OpenAI clients expect: role first. + send( + &tx, + &id, + created, + &model, + Delta { + role: Some("assistant"), + ..Default::default() + }, + None, + ); + + let mut dec = fmt.decoder(); + let mut st = EmitState { + tool_idx: 0, + had_tools: false, + stops: StopFilter::new(p_stops), + stop_hit: false, + }; + + // Race generation against client disconnect. `tx.closed()` borrows + // the sender (no clone: a cloned sender would keep the channel open + // and the SSE stream would never end). On disconnect we abort the + // engine, then let the request drain its own DONE. + let mut gen_fut = Box::pin(engine.generate(p_max, &p_sampling, &p_ids, |line| { + if let EngineLine::Token(tok) = line { + for piece in dec.push(*tok) { + send_piece(&tx, &id, created, &model, &piece, &mut st, &engine); + } + } + })); + let mut closed_fut = Box::pin(tx.closed()); + let gen = tokio::select! { + r = gen_fut.as_mut() => r, + _ = closed_fut.as_mut() => { + let _ = engine.abort().await; + gen_fut.as_mut().await + } + }; + drop(gen_fut); + drop(closed_fut); + + // Flush whatever the decoder still holds (with the finish word, so + // the dialect can surface truncated thinking on "length"). + let reason = gen + .as_ref() + .ok() + .and_then(|o| o.done.as_ref()) + .map(|d| d.finish.as_str()); + for piece in dec.finish(reason) { + send_piece(&tx, &id, created, &model, &piece, &mut st, &engine); + } + + // flush any content held back as a possible partial stop match + let tail = st.stops.flush(); + if !tail.is_empty() { + send( + &tx, + &id, + created, + &model, + Delta { + content: Some(tail), + ..Default::default() + }, + None, + ); + } + + // drop per-request temp files (materialized images) + for p in &p_temp { + let _ = std::fs::remove_file(p); + } + + let finish = if st.had_tools { + FinishReason::ToolCalls + } else if st.stop_hit { + FinishReason::Stop + } else { + match &gen { + Ok(out) => finish_reason(out, p_max), + Err(_) => FinishReason::Stop, + } + }; + send(&tx, &id, created, &model, Delta::default(), Some(finish)); + let _ = tx.send(Event::default().data("[DONE]")); + + if let Err(e) = gen { + tracing::warn!(error = %e, "streaming generation ended in error"); + } + }); + + Ok(UnboundedReceiverStream::new(rx)) + } +} + +/// Mutable per-request emit state for the streaming path (kept in one struct so +/// the token callback borrows a single thing). +struct EmitState { + tool_idx: u32, + had_tools: bool, + stops: StopFilter, + stop_hit: bool, +} + +fn send_piece( + tx: &UnboundedSender, + id: &str, + created: u64, + model: &str, + piece: &Piece, + st: &mut EmitState, + abort_engine: &Arc, +) { + let delta = match piece { + Piece::Content(s) => { + // filter the answer through the stop matcher (hold-back included) + let emit = st.stops.feed(s); + if st.stops.hit && !st.stop_hit { + st.stop_hit = true; + // stop reached: abort the engine so we don't keep generating + let e = abort_engine.clone(); + tokio::spawn(async move { + let _ = e.abort().await; + }); + } + if emit.is_empty() { + return; + } + Delta { + content: Some(emit), + ..Default::default() + } + } + Piece::Reasoning(s) if !s.is_empty() => Delta { + reasoning_content: Some(s.clone()), + ..Default::default() + }, + Piece::ToolCall { name, arguments } => { + // llama.cpp wire shape: one delta carries index+id+type+function. + // Emitting the whole call at once is valid; clients accumulate by index. + let tc = serde_json::json!([{ + "index": st.tool_idx, + "id": tool_call_id(), + "type": "function", + "function": { "name": name, "arguments": arguments }, + }]); + st.tool_idx += 1; + st.had_tools = true; + Delta { + tool_calls: Some(tc), + ..Default::default() + } + } + _ => return, + }; + send(tx, id, created, model, delta, None); +} + +/// Push one SSE `data:` event holding a `chat.completion.chunk`. +fn send( + tx: &UnboundedSender, + id: &str, + created: u64, + model: &str, + delta: Delta, + finish: Option, +) { + let body = ChatChunk { + id: id.to_string(), + object: "chat.completion.chunk", + created, + model: model.to_string(), + choices: vec![StreamChoice { + index: 0, + delta, + finish_reason: finish, + }], + }; + match Event::default().json_data(&body) { + Ok(ev) => { + let _ = tx.send(ev); + } + Err(e) => tracing::error!(error = %e, "failed to serialize SSE chunk"), + } +} + +fn finish_reason(outcome: &Outcome, max_new: u32) -> FinishReason { + match &outcome.done { + Some(d) if d.finish == "length" => FinishReason::Length, + Some(d) => FinishReason::from_engine(&d.finish), + // No DONE (e.g. aborted): if we filled the budget, call it length. + None if (outcome.tokens.len() as u32) >= max_new => FinishReason::Length, + None => FinishReason::Stop, + } +} + +fn usage_of(outcome: &Outcome, prompt_len: u32, completion: u32) -> Usage { + match &outcome.done { + Some(d) => Usage::new(d.prompt_tokens.max(prompt_len), d.generated.max(completion)), + None => Usage::new(prompt_len, completion), + } +} + +/// Engine error -> OpenAI error envelope (the status code is applied by routes). +fn formatter_error(err: crate::engine::EngineError) -> ApiErrorEnvelope { + formatter::engine_error(err).1 +} diff --git a/src/api/stop.rs b/src/api/stop.rs new file mode 100644 index 0000000..4e277ac --- /dev/null +++ b/src/api/stop.rs @@ -0,0 +1,173 @@ +//! Stop-sequence filtering for the content channel (OpenAI `stop`). +//! +//! Mirrors the reference's stop matcher: scan the emitted answer text for any +//! stop string, truncate at the first hit, and hold back a trailing partial +//! match so a stop string split across streaming deltas is still caught. The +//! reasoning channel is left untouched (stop applies to the answer). + +/// Incremental stop matcher over the content text. +pub struct StopFilter { + stops: Vec, + pending: String, + /// A full stop string was matched; nothing more should be emitted. + pub hit: bool, +} + +impl StopFilter { + pub fn new(stops: Vec) -> Self { + let stops = stops.into_iter().filter(|s| !s.is_empty()).collect(); + Self { + stops, + pending: String::new(), + hit: false, + } + } + + pub fn active(&self) -> bool { + !self.stops.is_empty() + } + + /// Feed content text; return the safe-to-emit prefix. Sets `hit` when a + /// stop string completes (the returned prefix stops just before it). + pub fn feed(&mut self, text: &str) -> String { + if self.hit { + return String::new(); + } + if self.stops.is_empty() { + return text.to_string(); + } + self.pending.push_str(text); + + // earliest full match across all stop strings + let mut cut: Option = None; + for s in &self.stops { + if let Some(i) = self.pending.find(s.as_str()) { + cut = Some(cut.map_or(i, |c| c.min(i))); + } + } + if let Some(i) = cut { + let emit = self.pending[..i].to_string(); + self.pending.clear(); + self.hit = true; + return emit; + } + + // hold back the longest suffix that is a proper prefix of any stop + let hold = self.hold_suffix_len(); + let emit_len = self.pending.len() - hold; + let emit = self.pending[..emit_len].to_string(); + self.pending.drain(..emit_len); + emit + } + + /// Flush whatever is held at end of stream (empty if a stop was hit). + pub fn flush(&mut self) -> String { + if self.hit { + String::new() + } else { + std::mem::take(&mut self.pending) + } + } + + /// Longest char-aligned suffix of `pending` that is a proper prefix of a + /// stop string (so a stop split across deltas is not emitted prematurely). + fn hold_suffix_len(&self) -> usize { + let max = self.stops.iter().map(|s| s.len()).max().unwrap_or(0); + let mut k = max.saturating_sub(1).min(self.pending.len()); + while k > 0 { + let start = self.pending.len() - k; + if self.pending.is_char_boundary(start) { + let suffix = &self.pending[start..]; + if self.stops.iter().any(|s| s.starts_with(suffix)) { + return k; + } + } + k -= 1; + } + 0 + } +} + +/// Truncate a whole content string at the earliest stop string. Returns the +/// truncated text and whether a stop was hit (the non-streaming path). +pub fn truncate_at_stop(content: &str, stops: &[String]) -> (String, bool) { + let mut cut: Option = None; + for s in stops { + if s.is_empty() { + continue; + } + if let Some(i) = content.find(s.as_str()) { + cut = Some(cut.map_or(i, |c| c.min(i))); + } + } + match cut { + Some(i) => (content[..i].to_string(), true), + None => (content.to_string(), false), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn no_stops_passes_through() { + let mut f = StopFilter::new(vec![]); + assert_eq!(f.feed("hello world"), "hello world"); + assert!(!f.hit); + assert_eq!(f.flush(), ""); + } + + #[test] + fn full_match_truncates() { + let mut f = StopFilter::new(vec!["STOP".into()]); + assert_eq!(f.feed("abcSTOPdef"), "abc"); + assert!(f.hit); + assert_eq!(f.feed("more"), ""); + assert_eq!(f.flush(), ""); + } + + #[test] + fn split_match_is_held_then_caught() { + let mut f = StopFilter::new(vec!["STOP".into()]); + // "ST" is a prefix of STOP: held back, not emitted + assert_eq!(f.feed("abcST"), "abc"); + assert!(!f.hit); + // completing the stop across the next delta + assert_eq!(f.feed("OPdef"), ""); + assert!(f.hit); + } + + #[test] + fn partial_prefix_flushed_at_end() { + let mut f = StopFilter::new(vec!["STOP".into()]); + assert_eq!(f.feed("abcST"), "abc"); + // never completed: the held tail is flushed at end of stream + assert_eq!(f.flush(), "ST"); + assert!(!f.hit); + } + + #[test] + fn earliest_of_many_stops() { + let mut f = StopFilter::new(vec!["zz".into(), "ab".into()]); + assert_eq!(f.feed("xxabzz"), "xx"); + assert!(f.hit); + } + + #[test] + fn multibyte_boundary_safe() { + let mut f = StopFilter::new(vec!["§".into()]); + assert_eq!(f.feed("ciao§mondo"), "ciao"); + assert!(f.hit); + } + + #[test] + fn truncate_whole() { + let (t, hit) = truncate_at_stop("helloSTOPworld", &["STOP".into()]); + assert_eq!(t, "hello"); + assert!(hit); + let (t, hit) = truncate_at_stop("hello", &["STOP".into()]); + assert_eq!(t, "hello"); + assert!(!hit); + } +} diff --git a/src/api/types.rs b/src/api/types.rs new file mode 100644 index 0000000..ed1fb72 --- /dev/null +++ b/src/api/types.rs @@ -0,0 +1,322 @@ +//! Wire types for the OpenAI-compatible surface we expose. +//! +//! Only the subset of `/v1/chat/completions` and `/v1/models` we implement is +//! modelled; request fields we do not act on yet still deserialize (with +//! `#[serde(default)]`) so a standard client never gets a hard parse error for +//! sending them. Field names follow the OpenAI spec exactly (snake_case). + +use serde::{Deserialize, Serialize}; + +/// The role of a chat participant. `Tool` is the OpenAI function/tool result +/// role; `Developer` is the newer spelling of `System`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Role { + System, + Developer, + User, + Assistant, + Tool, +} + +impl Role { + pub fn as_str(self) -> &'static str { + match self { + Role::System | Role::Developer => "system", + Role::User => "user", + Role::Assistant => "assistant", + Role::Tool => "tool", + } + } +} + +/// A tool the assistant asked to call (assistant turn) — parsed from the +/// model output by the formatter. Carried opaquely so the tool-loop decision +/// (server- vs client-side) stays separable from this layer. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ToolCall { + pub id: String, + #[serde(rename = "type", default)] + pub kind: String, + pub function: FunctionCall, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FunctionCall { + pub name: String, + /// JSON-encoded arguments, as the model produced them. + pub arguments: String, +} + +/// One message of the conversation. +/// +/// `content` is a string in the common case but OpenAI allows a parts array +/// (multimodal); we keep it as `serde_json::Value` and let the formatter +/// interpret it, so plain-text and image-part requests both deserialize. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChatMessage { + pub role: Role, + #[serde(default)] + pub content: Option, + /// Present on tool-result messages: the call this message answers for. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_call_id: Option, + /// Assistant turn: calls the model wants made. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_calls: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Our extension: the model's chain-of-thought, when the client asks to + /// receive it (matches several OpenAI-compatible servers). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_content: Option, +} + +impl ChatMessage { + /// The plain-text view of `content`, if it is a string. + pub fn text(&self) -> Option<&str> { + self.content.as_ref().and_then(|c| c.as_str()) + } +} + +/// A `stop` sequence, or list of them, from the request. +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +pub enum Stop { + One(String), + Many(Vec), +} + +impl Stop { + pub fn into_vec(self) -> Vec { + match self { + Stop::One(s) => vec![s], + Stop::Many(v) => v, + } + } +} + +/// `POST /v1/chat/completions` body (the fields we recognise). +#[derive(Debug, Clone, Deserialize)] +pub struct ChatRequest { + #[serde(default)] + pub model: String, + pub messages: Vec, + #[serde(default)] + pub stream: bool, + #[serde(default)] + pub temperature: Option, + #[serde(default)] + pub top_p: Option, + /// Newer spelling; both accepted, `max_completion_tokens` wins if present. + #[serde(default)] + pub max_tokens: Option, + #[serde(default)] + pub max_completion_tokens: Option, + #[serde(default)] + pub frequency_penalty: Option, + #[serde(default)] + pub presence_penalty: Option, + #[serde(default)] + pub seed: Option, + #[serde(default)] + pub stop: Option, + /// Tool definitions. Parsed but not yet acted on: kept so the request + /// round-trips and so the (undecided) tool loop can plug in here. + #[serde(default)] + pub tools: Option, + #[serde(default)] + pub tool_choice: Option, +} + +impl ChatRequest { + pub fn max_new(&self, fallback: u32) -> u32 { + self.max_completion_tokens + .or(self.max_tokens) + .unwrap_or(fallback) + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct Usage { + pub prompt_tokens: u32, + pub completion_tokens: u32, + pub total_tokens: u32, +} + +impl Usage { + pub fn new(prompt_tokens: u32, completion_tokens: u32) -> Self { + Self { + prompt_tokens, + completion_tokens, + total_tokens: prompt_tokens + completion_tokens, + } + } +} + +/// Why generation stopped (OpenAI spelling). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum FinishReason { + Stop, + Length, + ToolCalls, + /// Chain-of-thought ran to its budget before any answer (our extension, + /// mirrors several servers). + #[serde(rename = "content_filter")] + ContentFilter, +} + +impl FinishReason { + /// Map the engine's own `DONE ` word onto OpenAI's vocabulary. + pub fn from_engine(finish: &str) -> Self { + match finish { + "length" => FinishReason::Length, + // stop, eos, im_end, endoftext, ... all mean "the model stopped" + _ => FinishReason::Stop, + } + } +} + +/// `choices[0]` of a non-streaming response. +#[derive(Debug, Clone, Serialize)] +pub struct Choice { + pub index: u32, + pub message: ChatMessage, + pub finish_reason: FinishReason, +} + +/// Full non-streaming response. +#[derive(Debug, Clone, Serialize)] +pub struct ChatResponse { + pub id: String, + #[serde(rename = "object")] + pub object: &'static str, + pub created: u64, + pub model: String, + pub choices: Vec, + pub usage: Usage, +} + +/// Streaming delta: like a message but every field optional, sent incrementally. +#[derive(Debug, Clone, Serialize, Default)] +pub struct Delta { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub role: Option<&'static str>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub content: Option, + /// Streaming tool-call deltas carry an `index` (and partial `function` + /// fragments), so this is kept as raw JSON rather than `Vec`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_calls: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_content: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct StreamChoice { + pub index: u32, + pub delta: Delta, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub finish_reason: Option, +} + +/// One SSE chunk of a streaming completion. +#[derive(Debug, Clone, Serialize)] +pub struct ChatChunk { + pub id: String, + #[serde(rename = "object")] + pub object: &'static str, + pub created: u64, + pub model: String, + pub choices: Vec, +} + +/// `GET /v1/models` element and envelope. +#[derive(Debug, Clone, Serialize)] +pub struct ModelCard { + pub id: String, + #[serde(rename = "object")] + pub object: &'static str, + pub created: u64, + pub owned_by: String, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ModelList { + #[serde(rename = "object")] + pub object: &'static str, + pub data: Vec, +} + +/// OpenAI-standard error envelope: `{"error": {...}}`. +#[derive(Debug, Clone, Serialize)] +pub struct ApiErrorBody { + pub message: String, + #[serde(rename = "type")] + pub kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub param: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub code: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ApiErrorEnvelope { + pub error: ApiErrorBody, +} + +impl ApiErrorEnvelope { + pub fn new(message: impl Into, kind: impl Into, code: Option) -> Self { + Self { + error: ApiErrorBody { + message: message.into(), + kind: kind.into(), + param: None, + code, + }, + } + } + + /// A 400-shaped client error (also used for engine refusals). + pub fn bad_request( + message: impl Into, + kind: impl Into, + code: Option, + ) -> Self { + Self::new(message, kind, code) + } +} + +/// Ids look like `chatcmpl-`; we build one from the wall clock and a +/// process counter rather than pulling a uuid crate. +pub fn completion_id() -> String { + use std::sync::atomic::{AtomicU64, Ordering}; + static SEQ: AtomicU64 = AtomicU64::new(0); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos() as u64) + .unwrap_or(0); + let n = SEQ.fetch_add(1, Ordering::Relaxed); + format!("chatcmpl-{nanos:x}{n:x}") +} + +/// Seconds since the epoch, for the `created` fields. +pub fn now_unix() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// Ids for tool calls look like `call_` (OpenAI spelling). +pub fn tool_call_id() -> String { + use std::sync::atomic::{AtomicU64, Ordering}; + static SEQ: AtomicU64 = AtomicU64::new(0); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos() as u64) + .unwrap_or(0); + let n = SEQ.fetch_add(1, Ordering::Relaxed); + format!("call_{nanos:x}{n:x}") +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..581c3cf --- /dev/null +++ b/src/config.rs @@ -0,0 +1,284 @@ +//! Tolerant loader for the shared model config (`strata-inkling.json`). +//! +//! The same file configures several tools — this control layer, the upstream +//! web shell, and the user's "uostream" front-end. So the contract is: +//! **read what we understand, ignore everything else without failing.** In +//! serde terms that means no `deny_unknown_fields`; every key we don't consume +//! is captured in [`Config::extra`] so `--check` can report exactly what was +//! skipped, and an unknown or future key can never break startup. +//! +//! We deliberately do NOT declare fields we don't act on yet (`arch`, +//! `drafting`, `mcp_servers`, `cors_origins`, `allowed_hosts`, ...): they fall +//! into `extra` untouched, which is precisely the "ignore what isn't ours" +//! behaviour requested. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use serde::Deserialize; + +use crate::engine::protocol::Sampling; + +/// Per-request sampling defaults, the shape found under the JSON's `sampling` +/// key. Extra knobs inside `sampling` are likewise tolerated and kept. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct SamplingDefaults { + #[serde(default)] + pub temperature: Option, + #[serde(default)] + pub top_p: Option, + #[serde(default)] + pub min_p: Option, + #[serde(default)] + pub repetition_penalty: Option, + #[serde(flatten)] + pub extra: BTreeMap, +} + +impl SamplingDefaults { + /// The engine `GEN` sampling keys implied by these defaults. Only + /// meaningful values become keys (e.g. `repetition_penalty = 1.0` is the + /// neutral value and is dropped, matching the engine's own spelling). + pub fn to_sampling(&self) -> Sampling { + Sampling { + temperature: self.temperature, + top_p: self.top_p, + min_p: self.min_p, + repetition_penalty: self.repetition_penalty, + ..Default::default() + } + } +} + +/// The subset of the config this layer acts on; everything else lives in +/// [`Config::extra`]. +#[derive(Debug, Clone, Deserialize)] +pub struct Config { + /// Engine binary to spawn (required). + #[serde(default)] + pub exe: String, + /// Arguments passed verbatim after `--serve`. + #[serde(default)] + pub args: Vec, + #[serde(default)] + pub cwd: Option, + /// HF tokenizer directory (consumed by the Inkling formatter, later). + #[serde(default)] + pub tokenizer: Option, + #[serde(default)] + pub model_name: Option, + /// Bind overrides (a CLI flag still wins over these). + #[serde(default)] + pub host: Option, + #[serde(default)] + pub port: Option, + /// Chain-of-thought effort; the formatter applies it (was the Python + /// launcher's monkey-patch). + #[serde(default)] + pub reasoning_effort: Option, + #[serde(default)] + pub sampling: SamplingDefaults, + + /// Keys we understand but don't act on yet are NOT listed above, so they + /// arrive here untouched — the "ignore what isn't ours" guarantee. + #[serde(flatten)] + pub extra: BTreeMap, +} + +#[derive(Debug, thiserror::Error)] +pub enum ConfigError { + #[error("cannot read {path}: {source}")] + Io { + path: String, + #[source] + source: std::io::Error, + }, + #[error("invalid JSON in {path}: {source}")] + Parse { + path: String, + #[source] + source: serde_json::Error, + }, + #[error("`exe` is required (the Strata engine binary to spawn)")] + MissingExe, +} + +impl Config { + /// Read and validate a config file. + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Io { + path: path.display().to_string(), + source, + })?; + let cfg = Self::parse(&text, &path.display().to_string())?; + Ok(cfg) + } + + /// Parse from a JSON string (the `path` argument is only for error text). + pub fn parse(text: &str, path: &str) -> Result { + let cfg: Config = serde_json::from_str(text).map_err(|source| ConfigError::Parse { + path: path.to_string(), + source, + })?; + if cfg.exe.trim().is_empty() { + return Err(ConfigError::MissingExe); + } + Ok(cfg) + } + + /// Default config location, mirroring the Python launcher. + pub fn default_path() -> PathBuf { + let home = std::env::var("HOME").unwrap_or_default(); + PathBuf::from(home).join(".config/strata-inkling/strata-inkling.json") + } + + /// The full argv for the engine child: `--serve` first (once), then the + /// configured args. Idempotent — many configs already include `--serve`. + pub fn engine_argv(&self) -> Vec { + let mut argv = Vec::with_capacity(self.args.len() + 1); + if !self.args.iter().any(|a| a == "--serve") { + argv.push("--serve".to_string()); + } + argv.extend(self.args.iter().cloned()); + argv + } + + /// Model id to advertise, defaulting to the exe's file name. + pub fn model_name(&self) -> &str { + self.model_name.as_deref().unwrap_or_else(|| { + Path::new(&self.exe) + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or("strata") + }) + } + + /// Effective bind host: CLI override > config > `127.0.0.1`. + pub fn bind_host(&self, cli: Option<&str>) -> String { + cli.or(self.host.as_deref()) + .unwrap_or("127.0.0.1") + .to_string() + } + + /// Effective bind port: CLI override > config > `8095`. + pub fn bind_port(&self, cli: Option) -> u16 { + cli.or(self.port).unwrap_or(8095) + } + + /// The top-level keys present in the file that we are not acting on — + /// reported by `--check` so the shared-file contract stays visible. + pub fn ignored_keys(&self) -> Vec<&str> { + self.extra.keys().map(|k| k.as_str()).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // The user's real config, verbatim shape. + const REAL: &str = r#"{ + "arch": "inkling2_loop", + "exe": "/home/federico/Sviluppo/Progetti/strata/build-inkling/strata-inkling", + "args": ["--serve", "--native", "/mnt/models/Inkling/model.gguf", "--max-context", "262144", "--parallel", "1"], + "cwd": "/home/federico/Sviluppo/Progetti/strata/build-inkling", + "tokenizer": "/home/federico/.config/strata-inkling/inkling-tok", + "model_name": "Inkling-2-Mini", + "host": "0.0.0.0", + "cors_origins": ["*"], + "allowed_hosts": ["*"], + "reasoning_effort": "low", + "drafting": "off", + "mcp_servers": { "web_shell": { "command": "python3", "args": ["web_shell_mcp.py"] } }, + "sampling": { "temperature": 1.0, "top_p": 1.0, "min_p": 0.0, "repetition_penalty": 1.0 } + }"#; + + #[test] + fn reads_the_fields_we_care_about() { + let cfg = Config::parse(REAL, "test").unwrap(); + assert!(cfg.exe.ends_with("strata-inkling")); + assert_eq!(cfg.args.len(), 7); + assert_eq!(cfg.model_name(), "Inkling-2-Mini"); + assert_eq!(cfg.host.as_deref(), Some("0.0.0.0")); + assert_eq!(cfg.reasoning_effort.as_deref(), Some("low")); + assert_eq!(cfg.sampling.temperature, Some(1.0)); + assert_eq!( + cfg.tokenizer.as_deref().unwrap(), + "/home/federico/.config/strata-inkling/inkling-tok" + ); + } + + #[test] + fn foreign_keys_are_captured_not_fatal() { + // the same file also carries uostream / other-tool settings + let with_other = r#"{ + "exe": "/x/strata-inkling", + "uostream": { "theme": "dark", "telemetry": true }, + "future_key": [1, 2, 3], + "args": ["--serve"] + }"#; + let cfg = Config::parse(with_other, "test").unwrap(); + assert_eq!(cfg.exe, "/x/strata-inkling"); + assert!(cfg.extra.contains_key("uostream")); + assert!(cfg.extra.contains_key("future_key")); + let ignored = cfg.ignored_keys(); + assert!(ignored.contains(&"uostream") && ignored.contains(&"future_key")); + } + + #[test] + fn known_but_unused_fields_report_as_ignored() { + let cfg = Config::parse(REAL, "test").unwrap(); + // we don't act on these yet, so they must not be lost or cause errors + for k in [ + "arch", + "cors_origins", + "allowed_hosts", + "drafting", + "mcp_servers", + ] { + assert!(cfg.extra.contains_key(k), "{k} should be in ignored extras"); + } + } + + #[test] + fn engine_argv_adds_serve_once() { + // REAL args already contain --serve -> no duplicate + let cfg = Config::parse(REAL, "test").unwrap(); + let argv = cfg.engine_argv(); + assert_eq!(argv.iter().filter(|a| *a == "--serve").count(), 1); + + // a config without --serve gets it prepended + let no_serve = r#"{"exe":"/x/e","args":["--native","m.gguf"]}"#; + let argv = Config::parse(no_serve, "test").unwrap().engine_argv(); + assert_eq!(argv, vec!["--serve", "--native", "m.gguf"]); + } + + #[test] + fn missing_exe_is_an_error() { + let err = Config::parse(r#"{"args":["--serve"]}"#, "test").unwrap_err(); + assert!(matches!(err, ConfigError::MissingExe)); + let err = Config::parse(r#"{"exe":" "}"#, "test").unwrap_err(); + assert!(matches!(err, ConfigError::MissingExe)); + } + + #[test] + fn bind_precedence_cli_over_config_over_default() { + let cfg = Config::parse(REAL, "test").unwrap(); + assert_eq!(cfg.bind_host(None), "0.0.0.0"); + assert_eq!(cfg.bind_host(Some("127.0.0.1")), "127.0.0.1"); + assert_eq!(cfg.bind_port(None), 8095); // not in JSON -> default + assert_eq!(cfg.bind_port(Some(1234)), 1234); + } + + #[test] + fn sampling_defaults_map_to_engine_keys() { + let cfg = Config::parse(REAL, "test").unwrap(); + let s = cfg.sampling.to_sampling(); + // temperature 1.0 is > 0 so it is sent; repetition_penalty 1.0 is the + // neutral value so the engine-spelling builder drops it; min_p 0.0 off. + assert_eq!(s.temperature, Some(1.0)); + assert_eq!(s.repetition_penalty, Some(1.0)); + let keys = s.keys(); + assert_eq!(keys, " temperature=1.0"); + } +} diff --git a/src/engine/mod.rs b/src/engine/mod.rs new file mode 100644 index 0000000..e2e3fc2 --- /dev/null +++ b/src/engine/mod.rs @@ -0,0 +1,8 @@ +//! The engine side: line protocol ([`protocol`]) and process supervisor +//! ([`supervisor`]). + +pub mod protocol; +pub mod supervisor; + +pub use protocol::{EngineLine, Sampling}; +pub use supervisor::{Engine, EngineError, Outcome, Ready}; diff --git a/src/engine/protocol.rs b/src/engine/protocol.rs new file mode 100644 index 0000000..828614f --- /dev/null +++ b/src/engine/protocol.rs @@ -0,0 +1,386 @@ +//! Line protocol spoken by `strata --serve` on its stdin/stdout. +//! +//! The engine is a resident child process. We write one command per line and +//! it answers with one line per event, per request: +//! +//! - out: `GEN [key=value...] ,,...` (also `BGEN ...`, `STOP`, `QUIT`) +//! - in: `READY [stop] [hold] [holdb]`, `INFO k=v ...`, `T `, +//! `PP [ms] [tok_s]`, `RESUME `, +//! `DONE [...]`, `ERR ` +//! +//! This module is pure parsing/formatting: no IO, so the semantics of every +//! shape the engine can answer with are testable without a GPU. The field +//! layout mirrors `StrataEngine` in `strata/terminal/serve/server.py` (the +//! living spec) — in particular `DONE` grows extra positional fields across +//! engine versions, so we only commit to the first five and keep the tail raw. + +use std::collections::BTreeMap; + +/// One decoded line of engine stdout. Unknown prefixes are preserved as +/// [`EngineLine::Other`] rather than dropped: the protocol grows, and a +/// supervisor must not lose facts it does not model yet. +#[derive(Debug, Clone, PartialEq)] +pub enum EngineLine { + /// First line after startup: the engine's real context size and which + /// optional controls it honours (`stop`, `hold`, `holdb`). + Ready { + max_context: u32, + can_stop: bool, + can_hold: bool, + can_hold_batch: bool, + }, + /// `INFO key=value ...` — engine facts (version, expert slots, ...). + Info(BTreeMap), + /// `T ` — one generated token id. + Token(u32), + /// `PP [ms] [tok_s]` — prompt prefill progress, one per chunk. + Prefill { + read: u32, + total: u32, + ms: f64, + tok_s_mean: Option, + }, + /// `RESUME ` — prompt tokens taken from the conversation cache, not re-read. + Resume(u32), + /// `DONE` — end of request, with the engine's figures. See [`Done`]. + Done(Done), + /// `ERR ` — the request (or command) failed. + Err(String), + /// Anything else the engine printed, verbatim. + Other(String), +} + +/// The figures of a `DONE` line. Positional fields 1..=5 are stable across +/// engine versions; 6+ arrived incrementally (drafts, cache hits, expert +/// tiers, ...) and are kept in [`Done::extra`] rather than being guessed at. +#[derive(Debug, Clone, PartialEq)] +pub struct Done { + pub generated: u32, + pub prompt_tokens: u32, + pub prompt_ms: f64, + pub decode_ms: f64, + /// `stop` / `length` / `nonfinite` / ... — the engine's own word. + pub finish: String, + /// Raw remaining tokens of the line (draft stats, cache hits, kv pairs). + pub extra: Vec, +} + +/// The kind of a protocol line, for matches that do not need the payload. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LineKind { + Ready, + Info, + Token, + Prefill, + Resume, + Done, + Err, + Other, +} + +impl EngineLine { + /// Decodes one line of engine stdout (no trailing newline). + pub fn parse(line: &str) -> EngineLine { + let trimmed = line.trim(); + let mut it = trimmed.split_whitespace(); + match it.next() { + Some("READY") => EngineLine::Ready { + max_context: it.next().and_then(|v| v.parse().ok()).unwrap_or(0), + can_stop: it.clone().any(|f| f == "stop"), + can_hold: it.clone().any(|f| f == "hold"), + can_hold_batch: it.any(|f| f == "holdb"), + }, + Some("INFO") => EngineLine::Info( + it.map(|kv| { + let (k, v) = kv.split_once('=').unwrap_or((kv, "")); + (k.to_string(), v.to_string()) + }) + .collect(), + ), + Some("T") => EngineLine::Token(it.next().and_then(|v| v.parse().ok()).unwrap_or(0)), + Some("PP") => { + let f: Vec<&str> = it.collect(); + EngineLine::Prefill { + read: f.first().and_then(|v| v.parse().ok()).unwrap_or(0), + total: f.get(1).and_then(|v| v.parse().ok()).unwrap_or(0), + ms: f.get(2).and_then(|v| v.parse().ok()).unwrap_or(0.0), + tok_s_mean: f.get(3).and_then(|v| v.parse().ok()), + } + } + Some("RESUME") => { + EngineLine::Resume(it.next().and_then(|v| v.parse().ok()).unwrap_or(0)) + } + Some("DONE") => { + let f: Vec<&str> = it.collect(); + EngineLine::Done(Done { + generated: f.first().and_then(|v| v.parse().ok()).unwrap_or(0), + prompt_tokens: f.get(1).and_then(|v| v.parse().ok()).unwrap_or(0), + prompt_ms: f.get(2).and_then(|v| v.parse().ok()).unwrap_or(0.0), + decode_ms: f.get(3).and_then(|v| v.parse().ok()).unwrap_or(0.0), + finish: f.get(4).copied().unwrap_or("unknown").to_string(), + extra: f.into_iter().skip(5).map(String::from).collect(), + }) + } + Some("ERR") => EngineLine::Err( + trimmed + .strip_prefix("ERR") + .map(|r| r.trim().to_string()) + .unwrap_or_default(), + ), + _ => EngineLine::Other(trimmed.to_string()), + } + } + + /// Just the kind of the line, consuming it. + pub fn into_kind(self) -> LineKind { + match self { + EngineLine::Ready { .. } => LineKind::Ready, + EngineLine::Info(_) => LineKind::Info, + EngineLine::Token(_) => LineKind::Token, + EngineLine::Prefill { .. } => LineKind::Prefill, + EngineLine::Resume(_) => LineKind::Resume, + EngineLine::Done(_) => LineKind::Done, + EngineLine::Err(_) => LineKind::Err, + EngineLine::Other(_) => LineKind::Other, + } + } +} + +/// Per-request sampling and engine knobs, in the engine's own spelling. +/// A field left `None` is not sent, so the engine default applies — matching +/// `StrataEngine.sampling_keys`. +#[derive(Debug, Clone, Default)] +pub struct Sampling { + pub temperature: Option, + pub top_p: Option, + pub top_k: Option, + pub min_p: Option, + /// OpenAI `repetition_penalty` -> engine `penalty_repeat`. + pub repetition_penalty: Option, + pub frequency_penalty: Option, + pub presence_penalty: Option, + pub penalty_last_n: Option, + pub seed: Option, + /// Inkling/Hy4 vision: an `image=` key per picture, in prompt order. + pub images: Vec, +} + +impl Sampling { + /// Formats the ` key=value...` fragment of a GEN line (leading space when + /// any key is set). Floats print like Python's `repr` (always a decimal + /// point); the engine's parser expects that spelling. + pub fn keys(&self) -> String { + let mut out = String::new(); + let mut key = |k: &str, v: String| { + out.push(' '); + out.push_str(k); + out.push('='); + out.push_str(&v); + }; + if let Some(t) = self.temperature.filter(|t| *t > 0.0) { + key("temperature", fmt_float(t)); + } + if let Some(tp) = self.top_p.filter(|tp| *tp < 1.0) { + key("top_p", fmt_float(tp)); + } + if let Some(tk) = self.top_k { + // the engine's sampled path keeps at most 64 candidates + key("top_k", (tk.clamp(1, 64)).to_string()); + } + if let Some(mp) = self.min_p.filter(|mp| *mp > 0.0 && *mp <= 1.0) { + key("min_p", fmt_float(mp)); + } + let any_penalty = self.repetition_penalty.is_some_and(|p| p != 1.0) + || self.frequency_penalty.is_some_and(|p| p != 0.0) + || self.presence_penalty.is_some_and(|p| p != 0.0); + if let Some(rp) = self.repetition_penalty.filter(|p| *p != 1.0) { + key("penalty_repeat", fmt_float(rp)); + } + if let Some(pf) = self.frequency_penalty.filter(|p| *p != 0.0) { + key("penalty_freq", fmt_float(pf)); + } + if let Some(pp) = self.presence_penalty.filter(|p| *p != 0.0) { + key("penalty_present", fmt_float(pp)); + } + if any_penalty { + // a penalty without a window counts over nothing: default to 64 + let n = self.penalty_last_n.filter(|n| *n > 0).unwrap_or(64); + key("penalty_last_n", n.to_string()); + } + if let Some(seed) = self.seed.filter(|s| *s > 0) { + key("seed", seed.to_string()); + } + for path in &self.images { + key("image", path.clone()); + } + out + } +} + +fn fmt_float(v: f64) -> String { + // Python repr: 1.0 -> "1.0", 0.7 -> "0.7". Rust `{}` on an f64 already + // keeps ".0" for integral values, so it matches for our ranges. + let s = format!("{v}"); + if s.contains('.') { + s + } else { + format!("{s}.0") + } +} + +/// Builds a `GEN [keys] ` line. +pub fn gen_line(max_new: u32, sampling: &Sampling, ids: &[u32]) -> String { + format!( + "GEN {max_new}{} {}\n", + sampling.keys(), + ids.iter() + .map(|i| i.to_string()) + .collect::>() + .join(",") + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ready_flags() { + assert_eq!( + EngineLine::parse("READY 262144 stop hold"), + EngineLine::Ready { + max_context: 262144, + can_stop: true, + can_hold: true, + can_hold_batch: false, + } + ); + assert_eq!( + EngineLine::parse("READY 4096"), + EngineLine::Ready { + max_context: 4096, + can_stop: false, + can_hold: false, + can_hold_batch: false, + } + ); + } + + #[test] + fn info_pairs() { + let EngineLine::Info(m) = EngineLine::parse("INFO version=0.1.39 expert_slots=64") else { + panic!("not INFO"); + }; + assert_eq!(m["version"], "0.1.39"); + assert_eq!(m["expert_slots"], "64"); + } + + #[test] + fn token_and_resume() { + assert_eq!(EngineLine::parse("T 151645"), EngineLine::Token(151645)); + assert_eq!(EngineLine::parse("RESUME 512"), EngineLine::Resume(512)); + } + + #[test] + fn prefill_progress() { + assert_eq!( + EngineLine::parse("PP 1024 8192 431.5 2373.2"), + EngineLine::Prefill { + read: 1024, + total: 8192, + ms: 431.5, + tok_s_mean: Some(2373.2), + } + ); + } + + #[test] + fn done_five_fields() { + let EngineLine::Done(d) = EngineLine::parse("DONE 41 128 90.5 310.25 stop") else { + panic!("not DONE"); + }; + assert_eq!(d.generated, 41); + assert_eq!(d.prompt_tokens, 128); + assert_eq!(d.finish, "stop"); + assert!(d.extra.is_empty()); + } + + #[test] + fn done_extra_fields_stay_raw() { + // engine 0.1.3+: drafts/reused; 0.1.31+: expert tiers; then kv tails + let EngineLine::Done(d) = EngineLine::parse( + "DONE 41 128 90.5 310.25 length 7 10 55 3 40 1 2 3.5 120 9 chunk=2048", + ) else { + panic!("not DONE"); + }; + assert_eq!(d.extra.len(), 11); + assert_eq!(d.extra.last().unwrap(), "chunk=2048"); + } + + #[test] + fn err_message() { + assert_eq!( + EngineLine::parse("ERR GEN: unknown/unsupported key pen_from"), + EngineLine::Err("GEN: unknown/unsupported key pen_from".into()) + ); + } + + #[test] + fn unknown_line_preserved() { + assert_eq!( + EngineLine::parse("SOMETHING_NEW 1 2"), + EngineLine::Other("SOMETHING_NEW 1 2".into()) + ); + } + + #[test] + fn sampling_keys_match_engine_spelling() { + let s = Sampling { + temperature: Some(1.0), + top_p: Some(0.9), + top_k: Some(200), // clamped to the engine's 64-candidate path + min_p: Some(0.0), // not sent: 0 means off + seed: Some(42), + ..Default::default() + }; + assert_eq!(s.keys(), " temperature=1.0 top_p=0.9 top_k=64 seed=42"); + } + + #[test] + fn penalties_drag_the_window() { + let s = Sampling { + repetition_penalty: Some(1.1), + ..Default::default() + }; + assert_eq!(s.keys(), " penalty_repeat=1.1 penalty_last_n=64"); + // penalty 1.0 is the neutral value: nothing is sent, no window either + let neutral = Sampling { + repetition_penalty: Some(1.0), + ..Default::default() + }; + assert_eq!(neutral.keys(), ""); + } + + #[test] + fn greedy_temperature_not_sent() { + // temperature=0 is the engine's default (greedy): forwarding it is noise + let s = Sampling { + temperature: Some(0.0), + ..Default::default() + }; + assert_eq!(s.keys(), ""); + } + + #[test] + fn gen_line_shape() { + let s = Sampling { + temperature: Some(0.8), + images: vec!["%2Fmnt%2Fpic.png".into()], + ..Default::default() + }; + assert_eq!( + gen_line(512, &s, &[1, 2, 300]), + "GEN 512 temperature=0.8 image=%2Fmnt%2Fpic.png 1,2,300\n" + ); + } +} diff --git a/src/engine/supervisor.rs b/src/engine/supervisor.rs new file mode 100644 index 0000000..5dfad71 --- /dev/null +++ b/src/engine/supervisor.rs @@ -0,0 +1,341 @@ +//! Supervisor of the resident `strata --serve` child process. +//! +//! The engine speaks a line protocol on stdin/stdout (see [`super::protocol`]). +//! This module owns the process: start, one request at a time (the Python +//! layer serializes requests on a FIFO too — a `--parallel 1` engine has one +//! control stream and one conversation cache), STOP-then-drain when a request +//! ends early, and a clean QUIT on shutdown. + +use std::collections::BTreeMap; +use std::process::Stdio; +use std::time::Duration; + +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::process::Command; +use tokio::process::{Child, ChildStdin, ChildStdout}; +use tokio::sync::Mutex; + +use super::protocol::{gen_line, Done, EngineLine, LineKind, Sampling}; + +#[derive(Debug, thiserror::Error)] +pub enum EngineError { + #[error("failed to spawn the engine: {0}")] + Spawn(std::io::Error), + #[error("the engine did not become ready: {0}")] + Startup(String), + #[error("the engine stopped unexpectedly")] + Died, + #[error("the engine refused the request: {0}")] + Refused(String), + #[error("the engine produced no output for {0:?}")] + Silent(Duration), +} + +/// What the engine advertised on its `READY` line. +#[derive(Debug, Clone, Copy)] +pub struct Ready { + pub max_context: u32, + pub can_stop: bool, + pub can_hold: bool, + pub can_hold_batch: bool, +} + +/// Everything one request collected from the engine's answer. +#[derive(Debug, Default)] +pub struct Outcome { + /// The generated token ids, in order. + pub tokens: Vec, + /// The engine's figures from its `DONE` line. + pub done: Option, + /// Prompt tokens served from the conversation cache (`RESUME`). + pub resumed: u32, +} + +/// A running engine plus the mutex that keeps one request on the wires at a +/// time. Cheap to share: wrap in `Arc` and every HTTP handler contends on it. +pub struct Engine { + pipes: Mutex, + /// The in-flight request's cancel flag and a second handle on stdin, so + /// `abort` works while a request holds the lock (Python's `cancel` event + /// and the STOP write from another thread). + ctl: Abort, + ready: Ready, + info: Mutex>, + silence: Duration, +} + +struct Abort { + flag: std::sync::atomic::AtomicBool, + stdin: tokio::sync::Mutex, +} + +/// The child and its pipes, handed to whoever holds the request lock. +struct Guarded { + child: Child, + stdout: BufReader, + dead: bool, +} + +impl Engine { + /// Spawns ` ` (the supervisor is generic: the config layer + /// builds the full argv, e.g. `["--serve", "--native", model, ...]` for the + /// real engine) and waits, up to `ready_timeout`, for the `READY` line, + /// logging the startup `INFO` facts on the way. + pub async fn start( + exe: &str, + args: &[String], + cwd: Option<&str>, + ready_timeout: Duration, + ) -> Result { + let mut cmd = Command::new(exe); + cmd.args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .kill_on_drop(true); + if let Some(cwd) = cwd { + cmd.current_dir(cwd); + } + let mut child = cmd.spawn().map_err(EngineError::Spawn)?; + let stdin = child.stdin.take().expect("stdin piped"); + let stdout = BufReader::new(child.stdout.take().expect("stdout piped")); + let mut guarded = Guarded { + child, + stdout, + dead: false, + }; + let ctl = Abort { + flag: std::sync::atomic::AtomicBool::new(false), + stdin: Mutex::new(stdin), + }; + + // Everything before READY is startup chatter; a protocol line that is + // neither READY nor INFO means the engine refused to start (bad model + // path, no VRAM, ...): surface it instead of timing out. + let mut unexpected: Vec = Vec::new(); + let mut startup_info: BTreeMap = BTreeMap::new(); + let ready = match tokio::time::timeout(ready_timeout, async { + loop { + let line = match read_line(&mut guarded.stdout).await { + Ok(l) => l, + Err(e) => return Err(e), + }; + match EngineLine::parse(&line) { + EngineLine::Ready { + max_context, + can_stop, + can_hold, + can_hold_batch, + } => { + return Ok(Ready { + max_context, + can_stop, + can_hold, + can_hold_batch, + }) + } + EngineLine::Info(kv) => { + startup_info.extend(kv); + } + EngineLine::Err(msg) => { + return Err(EngineError::Startup(format!( + "the engine refused to start: {msg}" + ))) + } + _ => unexpected.push(line.trim().to_string()), + } + } + }) + .await + { + Err(_) => { + return Err(EngineError::Startup(format!( + "timed out waiting for READY (saw: {unexpected:?})" + ))) + } + Ok(r) => r, + }?; + + for (k, v) in &startup_info { + tracing::info!(key = %k, value = %v, "engine info"); + } + Ok(Self { + pipes: Mutex::new(guarded), + ctl, + ready, + info: Mutex::new(startup_info), + silence: Duration::from_secs(600), + }) + } + + pub fn ready(&self) -> Ready { + self.ready + } + + pub async fn info(&self) -> BTreeMap { + self.info.lock().await.clone() + } + + /// Runs one generation to completion, forwarding each engine line to + /// `on_event` as it arrives. Returns when the engine prints `DONE`, or on + /// refusal/death. Requests queue on the engine's lock — like the Python + /// service's FIFO — since one engine has one control stream and one + /// conversation cache. + pub async fn generate( + &self, + max_new: u32, + sampling: &Sampling, + ids: &[u32], + mut on_event: F, + ) -> Result + where + F: FnMut(&EngineLine), + { + let mut g = self.pipes.lock().await; + if g.dead { + return Err(EngineError::Died); + } + + let line = gen_line(max_new, sampling, ids); + self.ctl + .flag + .store(false, std::sync::atomic::Ordering::Relaxed); + if let Err(e) = self.send(&line).await { + g.dead = true; + return Err(e); + } + + let mut out = Outcome::default(); + loop { + // `abort` (client gone, caller gave up) only needs to set the flag + // and reach the engine's stdin: the DONE it triggers is drained + // here, inside the request that owns the wires. + if self.ctl.flag.load(std::sync::atomic::Ordering::Relaxed) { + self.send("STOP\n").await?; + drain_to_done(&mut g.stdout).await?; + return Err(EngineError::Refused("aborted".into())); + } + let raw = match tokio::time::timeout(self.silence, read_line(&mut g.stdout)).await { + Err(_) => { + // Computing a huge prompt or hung, we cannot tell: stop it + // and report, like Python's silence watchdog. The DONE we + // trigger is drained here, so the wires stay usable. + let _ = self.send("STOP\n").await; + let _ = drain_to_done(&mut g.stdout).await; + return Err(EngineError::Silent(self.silence)); + } + Ok(Err(e)) => { + g.dead = true; + return Err(e); + } + Ok(Ok(raw)) => raw, + }; + let parsed = EngineLine::parse(&raw); + match &parsed { + EngineLine::Token(id) => out.tokens.push(*id), + EngineLine::Resume(n) => out.resumed = *n, + EngineLine::Info(kv) => { + self.info.lock().await.extend(kv.clone()); + } + EngineLine::Done(done) => { + out.done = Some(done.clone()); + on_event(&parsed); + return Ok(out); + } + EngineLine::Err(msg) => { + // An engine that ends a request on ERR may still print its + // DONE: swallow it, or the next request would read it as + // its own (serve/server.py `_swallow_trailing_done`). + swallow_trailing_done(&mut g.stdout).await; + return Err(EngineError::Refused(msg.clone())); + } + _ => {} + } + on_event(&parsed); + } + } + + /// Writes one command to the engine's stdin (shared with `abort`, which + /// may run while a request holds the read lock). + async fn send(&self, line: &str) -> Result<(), EngineError> { + let mut stdin = self.ctl.stdin.lock().await; + write(&mut stdin, line).await + } + + /// Signals the in-flight request to stop (like Python's `cancel` event): + /// sets the flag and pokes the engine with STOP. The request's own future + /// drains to DONE, so this returns promptly even while a request holds the + /// wires. `Ok(false)` when nothing is running to abort. + pub async fn abort(&self) -> Result { + // If we can grab the read lock, no request owns the wires: nothing to + // abort. Otherwise flag the running request (it drains) and send STOP. + if self.pipes.try_lock().is_ok() { + return Ok(false); + } + self.ctl + .flag + .store(true, std::sync::atomic::Ordering::Relaxed); + self.send("STOP\n").await?; + Ok(true) + } + + /// True when no request owns the wires (non-mutating probe, unlike abort). + pub fn is_idle(&self) -> bool { + self.pipes.try_lock().is_ok() + } + + /// `QUIT` and reap the child. + pub async fn shutdown(&self) -> Result<(), EngineError> { + let mut g = self.pipes.lock().await; + if g.dead { + return Ok(()); + } + let _ = self.send("QUIT\n").await; + let _ = tokio::time::timeout(Duration::from_secs(5), g.child.wait()).await; + let _ = g.child.start_kill(); + g.dead = true; + Ok(()) + } +} + +async fn drain_to_done(stdout: &mut BufReader) -> Result<(), EngineError> { + loop { + match EngineLine::parse(&read_line(stdout).await?).into_kind() { + LineKind::Done | LineKind::Err => return Ok(()), + _ => continue, + } + } +} + +async fn swallow_trailing_done(stdout: &mut BufReader) { + for _ in 0..4 { + let Ok(Ok(raw)) = tokio::time::timeout(Duration::from_millis(300), read_line(stdout)).await + else { + return; + }; + match EngineLine::parse(&raw).into_kind() { + LineKind::Done | LineKind::Err => return, + _ => continue, + } + } +} + +async fn write(stdin: &mut ChildStdin, line: &str) -> Result<(), EngineError> { + stdin + .write_all(line.as_bytes()) + .await + .map_err(|_| EngineError::Died)?; + stdin.flush().await.map_err(|_| EngineError::Died) +} + +/// Reads one line; EOF (the engine exited) is [`EngineError::Died`]. +async fn read_line(stdout: &mut BufReader) -> Result { + let mut line = String::new(); + let n = stdout + .read_line(&mut line) + .await + .map_err(|_| EngineError::Died)?; + if n == 0 { + return Err(EngineError::Died); + } + Ok(line) +} diff --git a/src/inkling/dialect.rs b/src/inkling/dialect.rs new file mode 100644 index 0000000..39bc061 --- /dev/null +++ b/src/inkling/dialect.rs @@ -0,0 +1,572 @@ +//! The Inkling-2-Mini output channel dialect, ported faithfully from +//! `serve/inkling_dialect.py` **as patched by the launcher `run_strata_cot.py`**. +//! +//! The model emits special *channel tokens* that segment its output. The engine +//! streams them to us as detokenized pieces, and the server drives us once per +//! token via [`InklingDialect::feed_token`] with `is_special` set for the channel +//! tokens (mirrors `server.py`: `parser.feed_token(piece, is_special=(t in +//! inkling_special_ids))`). We translate that into typed pieces: reasoning +//! (chain-of-thought) and content (the answer, plus tool invocations rendered as +//! JSON inside a tool-call frame). +//! +//! Two behaviours come from the launcher patch, not the base class: thinking is +//! streamed live as it arrives (rather than accumulated and hidden), and the +//! reasoning effort is whatever the config sets. We reproduce that patched +//! behaviour, which is what actually runs on this machine. + +use serde_json::{Map, Value}; + +/// Channel tag literals, exactly as the detokenizer spells them. +pub mod tag { + pub const MESSAGE_MODEL: &str = "<|message_model|>"; + pub const CONTENT_THINKING: &str = "<|content_thinking|>"; + pub const CONTENT_TEXT: &str = "<|content_text|>"; + pub const CONTENT_INVOKE_TOOL_JSON: &str = "<|content_invoke_tool_json|>"; + pub const CONTENT_INVOKE_TOOL_TEXT: &str = "<|content_invoke_tool_text|>"; + pub const CONTENT_XML: &str = "<|content_xml|>"; + pub const END_MESSAGE: &str = "<|end_message|>"; + pub const END_SAMPLING: &str = "<|content_model_end_sampling|>"; + pub const ENDOFTEXT: &str = "<|endoftext|>"; + /// The downstream OpenAI tool layer reads frames delimited by these; JSON + /// inside them preserves arbitrary characters losslessly. + pub const TOOL_CALL_OPEN: &str = ""; + pub const TOOL_CALL_CLOSE: &str = ""; +} + +/// Which output channel a piece belongs to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Reasoning, + Content, +} + +/// A typed output chunk produced by the dialect. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Out { + pub kind: Kind, + pub text: String, +} + +impl Out { + fn reasoning(text: impl Into) -> Self { + Out { + kind: Kind::Reasoning, + text: text.into(), + } + } + fn content(text: impl Into) -> Self { + Out { + kind: Kind::Content, + text: text.into(), + } + } +} + +/// The channel/structural tokens. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tag { + MessageModel, + ContentThinking, + ContentText, + ContentInvokeToolJson, + ContentInvokeToolText, + ContentXml, + EndMessage, + EndSampling, + EndOfText, +} + +impl Tag { + pub fn as_str(self) -> &'static str { + use tag::*; + match self { + Tag::MessageModel => MESSAGE_MODEL, + Tag::ContentThinking => CONTENT_THINKING, + Tag::ContentText => CONTENT_TEXT, + Tag::ContentInvokeToolJson => CONTENT_INVOKE_TOOL_JSON, + Tag::ContentInvokeToolText => CONTENT_INVOKE_TOOL_TEXT, + Tag::ContentXml => CONTENT_XML, + Tag::EndMessage => END_MESSAGE, + Tag::EndSampling => END_SAMPLING, + Tag::EndOfText => ENDOFTEXT, + } + } + + pub fn parse(s: &str) -> Option { + use tag::*; + Some(match s { + MESSAGE_MODEL => Tag::MessageModel, + CONTENT_THINKING => Tag::ContentThinking, + CONTENT_TEXT => Tag::ContentText, + CONTENT_INVOKE_TOOL_JSON => Tag::ContentInvokeToolJson, + CONTENT_INVOKE_TOOL_TEXT => Tag::ContentInvokeToolText, + CONTENT_XML => Tag::ContentXml, + END_MESSAGE => Tag::EndMessage, + END_SAMPLING => Tag::EndSampling, + ENDOFTEXT => Tag::EndOfText, + _ => return None, + }) + } +} + +const ALL_TAGS: [Tag; 9] = [ + Tag::MessageModel, + Tag::ContentThinking, + Tag::ContentText, + Tag::ContentInvokeToolJson, + Tag::ContentInvokeToolText, + Tag::ContentXml, + Tag::EndMessage, + Tag::EndSampling, + Tag::EndOfText, +]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +enum State { + #[default] + Idle, + Header, + Think, + ThinkEnd, + Text, + TextEnd, + ToolJson, + ToolText, +} + +const MAX_HEADER_CHARS: usize = 128; +const MAX_THINK_ACC: usize = 65536; + +/// The tags valid as transitions in each state (mirrors `_tags_for`). +fn tags_for(state: State) -> &'static [Tag] { + use State::*; + match state { + Idle | Header | ThinkEnd | TextEnd => &ALL_TAGS, + Think => &[ + Tag::EndMessage, + Tag::ContentText, + Tag::EndSampling, + Tag::EndOfText, + ], + Text => &[Tag::EndMessage, Tag::EndSampling, Tag::EndOfText], + ToolJson | ToolText => &[Tag::EndMessage, Tag::EndSampling, Tag::EndOfText], + } +} + +/// One instance per assistant reply: consumes the engine's token stream and +/// yields typed reasoning/content pieces. +#[derive(Debug, Default)] +pub struct InklingDialect { + state: State, + header_acc: String, + tool_acc: String, + think_acc: String, + end_ws: String, + emitted_visible: bool, + /// How many tool frames have been rendered (diagnostics). + pub calls: u32, +} + +impl InklingDialect { + pub fn new() -> Self { + Self::default() + } + + /// Current state name, for tests and diagnostics. + pub fn state(&self) -> &'static str { + match self.state { + State::Idle => "idle", + State::Header => "header", + State::Think => "think", + State::ThinkEnd => "think_end", + State::Text => "text", + State::TextEnd => "text_end", + State::ToolJson => "tool_json", + State::ToolText => "tool_text", + } + } + + /// Token-aware entry: `piece` is one detokenized token; ordinary BPE text + /// (`is_special = false`) is literal content and can never drive a channel + /// transition, even if it spells a tag. Real channel tokens do. + pub fn feed_token(&mut self, piece: &str, is_special: bool) -> Vec { + let mut out = Vec::new(); + if piece.is_empty() { + return out; + } + if is_special { + if let Some(tag) = Tag::parse(piece) { + if tags_for(self.state).contains(&tag) { + self.handle_tag(tag, &mut out); + } else { + // A real channel tag illegal in this state is emitted + // verbatim in the current channel (e.g. quoted in thinking). + self.emit(piece, &mut out); + } + return out; + } + } + self.emit(piece, &mut out); + out + } + + /// Flush at end of stream. `reason` is the finish word (`"length"`, ...). + pub fn finish(&mut self, reason: Option<&str>) -> Vec { + let mut out = Vec::new(); + self.finish_into(&mut out, reason); + out + } + + /// `_emit_typed`, patched: live reasoning for the thinking states; base + /// behaviour for everything else. + fn emit(&mut self, chunk: &str, out: &mut Vec) { + if chunk.is_empty() { + return; + } + match self.state { + // patched: thinking streams live instead of being hidden + State::Think => { + self.append_think(chunk); + out.push(Out::reasoning(chunk)); + } + State::ThinkEnd => { + if chunk.trim().is_empty() { + self.end_ws.push_str(chunk); + return; + } + let combined = format!("{}{}{}", tag::END_MESSAGE, self.end_ws, chunk); + self.append_think(&combined); + out.push(Out::reasoning(combined)); + self.end_ws.clear(); + self.state = State::Think; + } + // ---- base `_emit_typed` for the remaining states ---- + State::TextEnd => { + if chunk.trim().is_empty() { + self.end_ws.push_str(chunk); + return; + } + out.push(Out::content(format!( + "{}{}{}", + tag::END_MESSAGE, + self.end_ws, + chunk + ))); + self.emitted_visible = true; + self.end_ws.clear(); + self.state = State::Text; + } + State::Idle => { + out.push(Out::content(chunk)); + if !chunk.trim().is_empty() { + self.emitted_visible = true; + self.state = State::Text; + } + } + State::Text => { + out.push(Out::content(chunk)); + if !chunk.trim().is_empty() { + self.emitted_visible = true; + } + } + State::Header => { + self.header_acc.push_str(chunk); + // A real tool-name header is short and single-line; newlines or + // an over-long run mean the model skipped content_text and is + // writing plain text (#6620). + if self.header_acc.contains('\n') + || self.header_acc.chars().count() > MAX_HEADER_CHARS + { + let acc = std::mem::take(&mut self.header_acc); + out.push(Out::content(acc)); + self.emitted_visible = true; + self.state = State::Text; + } + } + State::ToolJson | State::ToolText => { + self.tool_acc.push_str(chunk); + } + } + } + + fn append_think(&mut self, chunk: &str) { + if !chunk.is_empty() && self.think_acc.len() < MAX_THINK_ACC { + let room = MAX_THINK_ACC - self.think_acc.len(); + let take = room.min(chunk.len()); + // slice on a char boundary + let mut end = take; + while end > 0 && !chunk.is_char_boundary(end) { + end -= 1; + } + self.think_acc.push_str(&chunk[..end]); + } + } + + fn handle_tag(&mut self, tag: Tag, out: &mut Vec) { + match tag { + Tag::EndSampling | Tag::EndOfText => { + self.close_channel(out); + self.state = State::Idle; + } + Tag::EndMessage => match self.state { + State::Think => { + self.end_ws.clear(); + self.state = State::ThinkEnd; + } + // Second end-message after a quoted one in thinking: absorb the + // first, hold the second (#6675). + State::ThinkEnd => { + let held = format!("{}{}", tag::END_MESSAGE, self.end_ws); + self.append_think(&held); + self.end_ws.clear(); + } + State::Text => { + self.end_ws.clear(); + self.state = State::TextEnd; + } + // Adjacent quoted + real end-message in visible text: emit the + // first, hold the second (#6675). + State::TextEnd => { + out.push(Out::content(format!("{}{}", tag::END_MESSAGE, self.end_ws))); + self.emitted_visible = true; + self.end_ws.clear(); + } + _ => { + self.close_channel(out); + self.state = State::Idle; + } + }, + Tag::MessageModel => { + self.close_channel(out); + self.state = State::Header; + self.header_acc.clear(); + } + Tag::ContentThinking => { + self.close_channel(out); + self.header_acc.clear(); + self.think_acc.clear(); + self.state = State::Think; + } + Tag::ContentText => { + if matches!(self.state, State::Think | State::ThinkEnd | State::TextEnd) { + self.close_channel(out); + } + self.header_acc.clear(); + self.state = State::Text; + } + Tag::ContentInvokeToolJson => { + if matches!(self.state, State::Think | State::ThinkEnd | State::TextEnd) { + self.close_channel(out); + } + self.state = State::ToolJson; + self.tool_acc.clear(); + } + Tag::ContentInvokeToolText | Tag::ContentXml => { + if matches!(self.state, State::Think | State::ThinkEnd | State::TextEnd) { + self.close_channel(out); + } + self.state = State::ToolText; + self.tool_acc.clear(); + } + } + } + + fn close_channel(&mut self, out: &mut Vec) { + // Snapshot to avoid holding a borrow of self across the mutation. + let state = self.state; + let header = std::mem::take(&mut self.header_acc); + let tool = std::mem::take(&mut self.tool_acc); + match state { + State::ToolJson | State::ToolText => { + let rendered = parse_tool_body(&header, &tool, state, false); + if !rendered.is_empty() { + if rendered.contains(tag::TOOL_CALL_OPEN) { + self.calls += 1; + } + out.push(Out::content(rendered)); + self.emitted_visible = true; + } + } + State::Header => { + if !header.is_empty() { + out.push(Out::content(header)); + self.emitted_visible = true; + } + } + State::Think | State::ThinkEnd => { + self.end_ws.clear(); + } + State::TextEnd => self.end_ws.clear(), + _ => {} + } + } + + fn finish_into(&mut self, out: &mut Vec, reason: Option<&str>) { + let state = self.state; + let header = std::mem::take(&mut self.header_acc); + let tool = std::mem::take(&mut self.tool_acc); + let think = std::mem::take(&mut self.think_acc); + + match state { + State::Header if !header.is_empty() => { + out.push(Out::content(header)); + self.emitted_visible = true; + } + State::ToolJson | State::ToolText + if !tool.trim().is_empty() || !header.trim().is_empty() => + { + let rendered = parse_tool_body(&header, &tool, state, true); + if !rendered.is_empty() { + if rendered.contains(tag::TOOL_CALL_OPEN) { + self.calls += 1; + } + out.push(Out::content(rendered)); + self.emitted_visible = true; + } + } + // #6682: budget expired inside thinking with no visible answer yet: + // surface the truncated thinking rather than an empty 200 OK. + State::Think | State::ThinkEnd + if reason == Some("length") + && !self.emitted_visible + && !think.trim().is_empty() => + { + out.push(Out::reasoning(think)); + } + _ => {} + } + self.end_ws.clear(); + self.state = State::Idle; + } +} + +/// Serialize a call as OPEN newline json newline CLOSE, escaping the sequence +/// " String { + let mut obj = Map::new(); + obj.insert("name".into(), Value::String(name.to_string())); + obj.insert("arguments".into(), arguments); + let payload = Value::Object(obj).to_string().replace(" Option<&str> { + let start = raw.find('{')?; + let end = raw.rfind('}')?; + if end >= start { + Some(&raw[start..=end]) + } else { + None + } +} + +/// Normalize an arguments value: a JSON string parses to an object (or a +/// {"raw": ...} wrapper); a non-object becomes {"value": ...}. +fn normalize_args(value: Value) -> Value { + match value { + Value::String(s) => match serde_json::from_str::(&s) { + Ok(parsed) if parsed.is_object() => parsed, + _ => Value::Object(Map::from_iter([("raw".to_string(), Value::String(s))])), + }, + v if v.is_object() => v, + other => Value::Object(Map::from_iter([("value".to_string(), other)])), + } +} + +/// Render the body of a tool channel into a tool-call frame. +/// +/// Faithful for the JSON channel (the form Inkling emits: an object with a +/// name and args/arguments). `tool_text` / `content_xml` bodies that are JSON +/// or already carry a function marker are handled; the exotic XML attribute +/// recovery is intentionally reduced to a raw payload (documented, not silent) +/// since the OpenAI tool layer is not wired yet. +fn parse_tool_body(header_name: &str, body: &str, kind: State, truncated: bool) -> String { + let raw = body.trim(); + let fallback = header_name.trim(); + + if kind == State::ToolJson { + // parse `raw`, recovering a `{...}` object if the whole thing is dirty + let obj = serde_json::from_str::(raw) + .ok() + .or_else(|| extract_object(raw).and_then(|s| serde_json::from_str::(s).ok())); + if let Some(Value::Object(map)) = obj { + let name = map + .get("name") + .and_then(|v| v.as_str()) + .map(str::to_string) + .filter(|s| !s.trim().is_empty()) + .unwrap_or_else(|| fallback.to_string()); + let args = if map.contains_key("args") { + normalize_args(map["args"].clone()) + } else if map.contains_key("arguments") { + normalize_args(map["arguments"].clone()) + } else if map.contains_key("name") { + // args are the remaining keys + let rest: Map = map + .iter() + .filter(|(k, _)| k.as_str() != "name") + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + Value::Object(rest) + } else { + Value::Object(Map::new()) + }; + if !name.trim().is_empty() { + return safe_json_call(name.trim(), args); + } + } + if truncated && !raw.is_empty() && !raw.starts_with('{') { + return raw.to_string(); + } + if !fallback.is_empty() { + let args = if raw.is_empty() { + Value::Object(Map::new()) + } else { + Value::Object(Map::from_iter([( + "raw".to_string(), + Value::String(raw.to_string()), + )])) + }; + return safe_json_call(fallback, args); + } + return raw.to_string(); + } + + // tool_text / content_xml + if raw.starts_with('{') { + if let Ok(Value::Object(map)) = serde_json::from_str::(raw) { + let name = map + .get("name") + .and_then(|v| v.as_str()) + .map(str::to_string) + .unwrap_or_else(|| fallback.to_string()); + if let Some(args) = map.get("args").or(map.get("arguments")) { + if args.is_object() && !name.trim().is_empty() { + return safe_json_call(name.trim(), args.clone()); + } + } + } + } + if raw.contains(", + template: ChatTemplate, + model: String, + effort: Option, + max_new_default: u32, +} + +impl InklingFormatter { + pub fn new( + tok: Arc, + template: ChatTemplate, + model: String, + effort: Option, + ) -> Self { + Self { + tok, + template, + model, + effort, + max_new_default: 2048, + } + } + + /// OpenAI messages -> the JSON the template expects, normalizing the newer + /// `developer` role to `system` (the template's role map has no developer). + fn messages_json(req: &ChatRequest) -> Json { + let mut v = serde_json::to_value(&req.messages).unwrap_or_else(|_| Json::Array(vec![])); + if let Some(arr) = v.as_array_mut() { + for m in arr.iter_mut() { + if m.get("role").and_then(|r| r.as_str()) == Some("developer") { + m["role"] = Json::String("system".to_string()); + } + } + } + v + } +} + +impl Formatter for InklingFormatter { + fn model_name(&self) -> &str { + &self.model + } + + fn default_max_new(&self) -> u32 { + self.max_new_default + } + + fn build_prompt(&self, req: &ChatRequest) -> Result { + let mut msgs = Self::messages_json(req); + prepare_messages(&mut msgs); + + let tools = tools_for_choice(req)?; + let rendered = self + .template + .render(&msgs, tools, self.effort.as_deref()) + .map_err(|e| ApiErrorEnvelope::new(e.to_string(), "invalid_request_error", None))?; + + let has_tools = tools + .and_then(|t| t.as_array()) + .map(|a| !a.is_empty()) + .unwrap_or(false); + let prompt = finish_prompt(&rendered, has_tools, false); + + let ids = self + .tok + .encode(&prompt) + .map_err(|e| ApiErrorEnvelope::new(e.to_string(), "invalid_request_error", None))?; + + // Images: materialize the conversation's image parts to local files the + // engine reads via `image=` keys, in the same order the template + // rendered its placeholders. + let sources = super::images::extract_sources(&msgs); + let temp_files = if sources.is_empty() { + Vec::new() + } else { + super::images::materialize(&sources) + .map_err(|e| ApiErrorEnvelope::new(e.to_string(), "invalid_request_error", None))? + }; + let images = temp_files + .iter() + .map(|p| super::images::encode_path(&p.to_string_lossy())) + .collect(); + + let sampling = Sampling { + temperature: req.temperature, + top_p: req.top_p, + frequency_penalty: req.frequency_penalty, + presence_penalty: req.presence_penalty, + seed: req.seed, + images, + ..Default::default() + }; + Ok(Prompt { + ids, + max_new: req.max_new(self.max_new_default), + sampling, + temp_files, + }) + } + + fn decoder(&self) -> Box { + Box::new(InklingDecoder { + tok: self.tok.clone(), + detok: Detok::new(self.tok.clone()), + dialect: InklingDialect::new(), + }) + } +} + +/// Output decoder: detokenize each id, classify special vs text, drive the +/// channel state machine, and map its typed output to API pieces. +struct InklingDecoder { + tok: Arc, + detok: Detok, + dialect: InklingDialect, +} + +/// Resolve `tool_choice` to the tools actually offered to the model. `none` +/// hides them (the model cannot call); `auto`/absent offers them. Forcing +/// (`required` or a named function) needs a prompt-opener the Inkling template +/// does not provide, so it is rejected honestly rather than silently ignored. +fn tools_for_choice(req: &ChatRequest) -> Result, ApiErrorEnvelope> { + let unsupported = |msg: &str| { + Err(ApiErrorEnvelope::new( + msg.to_string(), + "invalid_request_error", + None, + )) + }; + match req.tool_choice.as_ref() { + None => Ok(req.tools.as_ref()), + Some(Json::String(s)) => match s.as_str() { + "auto" => Ok(req.tools.as_ref()), + "none" => Ok(None), + "required" => unsupported( + "tool_choice \"required\" (forced calling) is not supported by this model yet", + ), + other => unsupported(&format!("unknown tool_choice: {other}")), + }, + Some(Json::Object(_)) => unsupported( + "tool_choice forcing a specific function is not supported by this model yet", + ), + Some(_) => unsupported("invalid tool_choice"), + } +} + +/// Parse a rendered tool frame (`...\n{"name":...,"arguments":{...}}\n`) +/// back into a structured call. This is the OpenAI tool layer the reference +/// keeps in a separate JsonOutputParser; non-frame text stays content. +fn frame_to_call(text: &str) -> Option<(String, String)> { + let t = text.trim(); + let inner = t + .strip_prefix(super::dialect::tag::TOOL_CALL_OPEN)? + .strip_suffix(super::dialect::tag::TOOL_CALL_CLOSE)? + .trim(); + let v: Json = serde_json::from_str(inner).ok()?; + let name = v.get("name")?.as_str()?.trim().to_string(); + if name.is_empty() { + return None; + } + let args = v + .get("arguments") + .cloned() + .unwrap_or_else(|| Json::Object(Default::default())); + Some((name, args.to_string())) +} + +/// Map one dialect output to API pieces: a tool frame becomes a structured +/// `ToolCall`, anything else stays reasoning/content. +fn out_to_pieces(o: Out) -> Vec { + match o.kind { + Kind::Reasoning if !o.text.is_empty() => vec![Piece::Reasoning(o.text)], + Kind::Content => { + if let Some((name, arguments)) = frame_to_call(&o.text) { + vec![Piece::ToolCall { name, arguments }] + } else if !o.text.is_empty() { + vec![Piece::Content(o.text)] + } else { + vec![] + } + } + _ => vec![], + } +} + +impl Decoder for InklingDecoder { + fn push(&mut self, id: u32) -> Vec { + let piece = self.detok.push(id); + let is_special = self.tok.is_special(id); + self.dialect + .feed_token(&piece, is_special) + .into_iter() + .flat_map(out_to_pieces) + .collect() + } + + fn finish(&mut self, reason: Option<&str>) -> Vec { + // flush any held partial text, then let the dialect close its channels + let tail = self.detok.finish(); + let mut out: Vec = self + .dialect + .feed_token(&tail, false) + .into_iter() + .flat_map(out_to_pieces) + .collect(); + out.extend( + self.dialect + .finish(reason) + .into_iter() + .flat_map(out_to_pieces), + ); + out + } +} diff --git a/src/inkling/images.rs b/src/inkling/images.rs new file mode 100644 index 0000000..7c1c14c --- /dev/null +++ b/src/inkling/images.rs @@ -0,0 +1,166 @@ +//! Image bridge for Inkling's in-process Vision. +//! +//! OpenAI/Anthropic image parts (base64 data URLs, http(s) URLs, local paths) +//! are materialized to local files the engine reads itself via `image=` +//! keys, in prompt order — mirroring `serve.write_images` + `inkling_kind`. +//! Unsupported formats (WebP/TIFF/AVIF, which agents like omp send) are +//! normalized to PNG; JPEG/PNG/BMP/GIF pass through untouched. + +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use base64::Engine; +use serde_json::Value as Json; + +#[derive(Debug, thiserror::Error)] +pub enum ImageError { + #[error("unsupported image source: {0}")] + Unsupported(String), + #[error("image decode failed: {0}")] + Decode(String), + #[error("image io: {0}")] + Io(String), + #[error("image fetch failed: {0}")] + Fetch(String), +} + +static SEQ: AtomicU64 = AtomicU64::new(0); + +/// `inkling_kind.encode_path`: the engine only decodes `%20` and `%25`, so we +/// encode exactly those two — not a full percent-encoding (slashes stay literal). +pub fn encode_path(path: &str) -> String { + path.replace('%', "%25").replace(' ', "%20") +} + +/// Image source strings of the conversation, in prompt order (one per image +/// content part, message by message) — the order the template renders its +/// `<|content_image|><|unused_200054|>` placeholders. +pub fn extract_sources(messages: &Json) -> Vec { + let mut out = Vec::new(); + let Some(arr) = messages.as_array() else { + return out; + }; + for m in arr { + let Some(content) = m.get("content").and_then(|c| c.as_array()) else { + continue; + }; + for part in content { + if let Some(src) = part_source(part) { + out.push(src); + } + } + } + out +} + +/// Pull the source string out of one content part, across the OpenAI, Responses +/// and Anthropic shapes. Anthropic base64 blocks are folded into a data URL. +fn part_source(part: &Json) -> Option { + let ty = part.get("type")?.as_str()?; + match ty { + "image_url" => { + let iu = part.get("image_url")?; + if let Some(s) = iu.as_str() { + return Some(s.to_string()); + } + iu.get("url")?.as_str().map(str::to_string) + } + "input_image" => part + .get("image_url") + .and_then(|v| v.as_str()) + .map(str::to_string), + "image" => { + let src = part.get("source")?; + if let Some(s) = src.as_str() { + return Some(s.to_string()); + } + if src.get("type").and_then(|t| t.as_str()) == Some("base64") { + let mt = src + .get("media_type") + .and_then(|m| m.as_str()) + .unwrap_or("image/png"); + let data = src.get("data")?.as_str()?; + return Some(format!("data:{mt};base64,{data}")); + } + src.get("url").and_then(|u| u.as_str()).map(str::to_string) + } + _ => None, + } +} + +/// Materialize sources to unique local files under `strata-inkling-images`. +/// Returns the paths (to hand the engine, in order); the caller removes them +/// once the request is done. +pub fn materialize(sources: &[String]) -> Result, ImageError> { + let base = std::env::temp_dir().join("strata-inkling-images"); + std::fs::create_dir_all(&base).map_err(|e| ImageError::Io(e.to_string()))?; + let nonce = format!( + "{}-{}", + std::process::id(), + SEQ.fetch_add(1, Ordering::Relaxed) + ); + let mut out = Vec::new(); + for (idx, src) in sources.iter().enumerate() { + let raw = load_bytes(src)?; + let (data, ext) = normalize(raw)?; + let p = base.join(format!("{nonce}-{idx}{ext}")); + std::fs::write(&p, &data).map_err(|e| ImageError::Io(e.to_string()))?; + out.push(p); + } + Ok(out) +} + +/// Bytes of one source: base64 data URL, http(s) fetch, or local file path. +fn load_bytes(src: &str) -> Result, ImageError> { + if let Some(rest) = src.strip_prefix("data:") { + let (meta, data) = rest + .split_once(',') + .ok_or_else(|| ImageError::Unsupported("malformed data URL".into()))?; + if !meta.ends_with(";base64") { + return Err(ImageError::Unsupported( + "only base64 data URLs are supported".into(), + )); + } + return base64::engine::general_purpose::STANDARD + .decode(data) + .map_err(|e| ImageError::Decode(e.to_string())); + } + if src.starts_with("http://") || src.starts_with("https://") { + let mut resp = ureq::get(src) + .call() + .map_err(|e| ImageError::Fetch(e.to_string()))?; + return resp + .body_mut() + .read_to_vec() + .map_err(|e| ImageError::Fetch(e.to_string())); + } + let path = src.strip_prefix("file://").unwrap_or(src); + std::fs::read(path).map_err(|e| ImageError::Io(format!("{path}: {e}"))) +} + +/// Keep JPEG/PNG/BMP/GIF as-is; convert anything else to PNG via the image crate. +fn normalize(data: Vec) -> Result<(Vec, &'static str), ImageError> { + if let Some(ext) = sniff(&data) { + return Ok((data, ext)); + } + let img = image::load_from_memory(&data).map_err(|e| ImageError::Decode(e.to_string()))?; + let mut buf = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png) + .map_err(|e| ImageError::Decode(e.to_string()))?; + Ok((buf, ".png")) +} + +/// Magic-byte sniff for the formats the engine reads directly. +fn sniff(data: &[u8]) -> Option<&'static str> { + if data.starts_with(&[0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n']) { + Some(".png") + } else if data.starts_with(&[0xff, 0xd8, 0xff]) { + Some(".jpg") + } else if data.starts_with(b"BM") { + Some(".bmp") + } else if data.starts_with(b"GIF") { + Some(".gif") + } else { + None + } +} diff --git a/src/inkling/mod.rs b/src/inkling/mod.rs new file mode 100644 index 0000000..dac1c50 --- /dev/null +++ b/src/inkling/mod.rs @@ -0,0 +1,16 @@ +//! Inkling-2-Mini model dialect: the output channel state machine. +//! +//! [`dialect`] ports the streaming reasoning/content/tool translator. The +//! tokenizer + chat template (prompt side) land here next, so `InklingFormatter` +//! can implement [`crate::api::formatter::Formatter`] end to end. + +pub mod dialect; +pub mod formatter; +pub mod images; +pub mod template; +pub mod tokenizer; + +pub use dialect::{InklingDialect, Kind, Out, Tag}; +pub use formatter::InklingFormatter; +pub use template::{finish_prompt, prepare_messages, ChatTemplate, TemplateError}; +pub use tokenizer::{Detok, InklingTokenizer, TokError}; diff --git a/src/inkling/template.rs b/src/inkling/template.rs new file mode 100644 index 0000000..26da146 --- /dev/null +++ b/src/inkling/template.rs @@ -0,0 +1,215 @@ +//! Inkling chat template: renders `chat_template.jinja` to the prompt string +//! the tokenizer then encodes. +//! +//! The template is HF-flavoured Jinja: it uses `namespace`, macros, `dictsort`, +//! `tojson(sort_keys=…, separators=…)`, a `raise_exception` global, and HF's +//! `{% generation %}` blocks. minijinja covers most of it; we supply a `tojson` +//! that honours those kwargs, a `raise_exception` that fails the render, and we +//! strip the (transparent-for-inference) generation tags before parsing. + +use minijinja::value::{Kwargs, Serde}; +use minijinja::{Environment, Error, ErrorKind, Value}; +use serde_json::Value as Json; + +use super::dialect::tag; + +#[derive(Debug, thiserror::Error)] +pub enum TemplateError { + #[error("template parse/render failed: {0}")] + Render(String), +} + +/// A compiled chat template. +pub struct ChatTemplate { + env: Environment<'static>, +} + +impl ChatTemplate { + /// Compile from the template source (the contents of chat_template.jinja). + pub fn new(source: &str) -> Result { + let cleaned = strip_generation(source); + let mut env = Environment::new(); + env.add_filter("tojson", tojson); + env.add_function("raise_exception", raise_exception); + env.add_template_owned("chat", cleaned) + .map_err(|e| TemplateError::Render(e.to_string()))?; + Ok(Self { env }) + } + + /// Render with the conversation. `messages`/`tools` are OpenAI-shaped JSON + /// (see [`prepare_messages`]); `reasoning_effort` is the config string. + pub fn render( + &self, + messages: &Json, + tools: Option<&Json>, + reasoning_effort: Option<&str>, + ) -> Result { + let ctx = minijinja::context! { + messages => Value::from(Serde(messages)), + tools => Value::from(Serde(tools.unwrap_or(&Json::Null))), + reasoning_effort => reasoning_effort, + }; + self.env + .get_template("chat") + .and_then(|t| t.render(ctx)) + .map_err(|e| TemplateError::Render(e.to_string())) + } +} + +/// HF `{% generation %}` / `{% endgeneration %}` mark the assistant span for +/// training loss; at inference they are transparent, so remove them (keeping +/// their inner content) before minijinja parses the source. +fn strip_generation(src: &str) -> String { + src.replace("{%- generation -%}", "") + .replace("{%- endgeneration -%}", "") + .replace("{% generation %}", "") + .replace("{% endgeneration %}", "") +} + +/// `raise_exception(msg)` global: abort the render with the model's own message. +fn raise_exception(msg: String) -> Result { + Err(Error::new(ErrorKind::InvalidOperation, msg)) +} + +/// `tojson` honouring `sort_keys` and `separators` (the template passes +/// `separators=(",", ":")`, i.e. compact). Defaults mirror Python json.dumps. +fn tojson(value: Value, kwargs: Kwargs) -> Result { + let sort_keys = kwargs.get::>("sort_keys")?.unwrap_or(false); + let separators = kwargs.get::>("separators")?; + let (item_sep, kv_sep) = match separators { + Some(seq) => { + let a = seq.get_item_by_index(0).ok(); + let b = seq.get_item_by_index(1).ok(); + ( + a.and_then(|v| v.as_str().map(str::to_string)) + .unwrap_or_else(|| ", ".into()), + b.and_then(|v| v.as_str().map(str::to_string)) + .unwrap_or_else(|| ": ".into()), + ) + } + None => (", ".to_string(), ": ".to_string()), + }; + kwargs.assert_all_used()?; + + let json: Json = serde_json::to_value(&value) + .map_err(|e| Error::new(ErrorKind::InvalidOperation, e.to_string()))?; + let mut out = String::new(); + write_json(&json, sort_keys, &item_sep, &kv_sep, &mut out); + Ok(Value::from_safe_string(out)) +} + +/// Recursive JSON writer with explicit separators and optional key sorting. +fn write_json(v: &Json, sort: bool, item_sep: &str, kv_sep: &str, out: &mut String) { + match v { + Json::Object(map) => { + let mut entries: Vec<(&String, &Json)> = map.iter().collect(); + if sort { + entries.sort_by(|a, b| a.0.cmp(b.0)); + } + out.push('{'); + for (i, (k, val)) in entries.iter().enumerate() { + if i > 0 { + out.push_str(item_sep); + } + out.push_str(&Json::String((*k).clone()).to_string()); + out.push_str(kv_sep); + write_json(val, sort, item_sep, kv_sep, out); + } + out.push('}'); + } + Json::Array(arr) => { + out.push('['); + for (i, val) in arr.iter().enumerate() { + if i > 0 { + out.push_str(item_sep); + } + write_json(val, sort, item_sep, kv_sep, out); + } + out.push(']'); + } + // scalars: serde_json's own compact spelling (strings escaped, numbers, + // booleans, null) is exactly what we want. + other => out.push_str(&other.to_string()), + } +} + +/// Canonicalize assistant tool-call arguments from JSON strings to objects, so +/// the template's `args is string -> raise` never fires (mirrors +/// `inkling_dialect.prepare_messages`). Mutates the messages JSON in place. +pub fn prepare_messages(messages: &mut Json) { + let Some(arr) = messages.as_array_mut() else { + return; + }; + for m in arr.iter_mut() { + let Some(calls) = m.get_mut("tool_calls").and_then(|c| c.as_array_mut()) else { + continue; + }; + for tc in calls.iter_mut() { + let Some(fn_obj) = tc.get_mut("function").and_then(|f| f.as_object_mut()) else { + continue; + }; + match fn_obj.get("arguments") { + Some(Json::String(s)) => { + let parsed = if s.trim().is_empty() { + Json::Object(Default::default()) + } else { + match serde_json::from_str::(s) { + Ok(v) if v.is_object() => v, + Ok(v) => Json::Object([("value".to_string(), v)].into_iter().collect()), + Err(_) => Json::Object( + [("raw".to_string(), Json::String(s.clone()))] + .into_iter() + .collect(), + ), + } + }; + fn_obj.insert("arguments".to_string(), parsed); + } + None | Some(Json::Null) => { + fn_obj.insert("arguments".to_string(), Json::Object(Default::default())); + } + _ => {} + } + } + } +} + +/// Append the non-thinking turn opener, **as patched by run_strata_cot.py**: +/// only when the prompt carries `Thinking effort level: 0` (effort none). With +/// a positive effort the model opens its own thinking, so the prompt is left +/// untouched. Idempotent; `forced` (a forced tool opener) is left as-is. +pub fn finish_prompt(prompt: &str, has_tools: bool, forced: bool) -> String { + if prompt.is_empty() || forced { + return prompt.to_string(); + } + if !prompt.contains("Thinking effort level: 0<|end_message|>") { + return prompt.to_string(); + } + let empty_think = format!( + "{}{}{}", + tag::MESSAGE_MODEL, + tag::CONTENT_THINKING, + tag::END_MESSAGE + ); + if prompt.ends_with(tag::CONTENT_TEXT) + || prompt.ends_with(tag::CONTENT_INVOKE_TOOL_JSON) + || prompt.ends_with(tag::CONTENT_INVOKE_TOOL_TEXT) + || prompt.ends_with(&empty_think) + { + return prompt.to_string(); + } + if prompt.ends_with(tag::MESSAGE_MODEL) { + let tail = if has_tools { + format!("{}{}", tag::CONTENT_THINKING, tag::END_MESSAGE) + } else { + tag::CONTENT_TEXT.to_string() + }; + return format!("{prompt}{tail}"); + } + let tail = if has_tools { + empty_think + } else { + format!("{}{}", tag::MESSAGE_MODEL, tag::CONTENT_TEXT) + }; + format!("{prompt}{tail}") +} diff --git a/src/inkling/tokenizer.rs b/src/inkling/tokenizer.rs new file mode 100644 index 0000000..545f984 --- /dev/null +++ b/src/inkling/tokenizer.rs @@ -0,0 +1,158 @@ +//! Inkling tokenizer: loads the real HF tokenizer (`tokenizer.hf.json`, an +//! o200k BPE) via the `tokenizers` crate, and provides the three things the +//! formatter needs: +//! - encode a rendered prompt string to ids (special channel tokens are matched +//! as single ids by the added-token trie); +//! - the `id -> Tag` table for the channel tokens (the dialect's `is_special`); +//! - incremental, UTF-8-safe detokenization of the engine's output ids. + +use std::collections::{HashMap, HashSet}; +use std::path::Path; +use std::sync::Arc; + +use tokenizers::Tokenizer; + +use super::dialect::Tag; + +#[derive(Debug, thiserror::Error)] +pub enum TokError { + #[error("cannot load tokenizer {path}: {msg}")] + Load { path: String, msg: String }, + #[error("encode failed: {0}")] + Encode(String), + #[error("decode failed: {0}")] + Decode(String), +} + +/// A loaded Inkling tokenizer plus its channel/special id tables. +pub struct InklingTokenizer { + tok: Tokenizer, + /// Channel-token id -> dialect tag (the nine structural tokens). + channel: HashMap, + /// Every added (atomic) token id, special or not. + added: HashSet, +} + +impl InklingTokenizer { + /// Load `/tokenizer.hf.json` (the real HF file; `tokenizer.json` in the + /// same dir is only a summary and is not loadable). + pub fn load_dir(dir: &Path) -> Result { + Self::from_file(&dir.join("tokenizer.hf.json")) + } + + pub fn from_file(path: &Path) -> Result { + let tok = Tokenizer::from_file(path).map_err(|e| TokError::Load { + path: path.display().to_string(), + msg: e.to_string(), + })?; + let mut channel = HashMap::new(); + let mut added = HashSet::new(); + for (id, at) in tok.get_added_tokens_decoder() { + added.insert(id); + if let Some(tag) = Tag::parse(&at.content) { + channel.insert(id, tag); + } + } + Ok(Self { + tok, + channel, + added, + }) + } + + /// Encode a prompt string. `add_special_tokens = false`: the rendered chat + /// template already carries every structural token explicitly. + pub fn encode(&self, text: &str) -> Result, TokError> { + let enc = self + .tok + .encode(text, false) + .map_err(|e| TokError::Encode(e.to_string()))?; + Ok(enc.get_ids().to_vec()) + } + + /// Decode a whole id slice (specials kept, so channel tokens come back as + /// their literal strings). + pub fn decode_all(&self, ids: &[u32]) -> Result { + self.tok + .decode(ids, false) + .map_err(|e| TokError::Decode(e.to_string())) + } + + /// The dialect tag for a channel-token id, if any. + pub fn channel_tag(&self, id: u32) -> Option { + self.channel.get(&id).copied() + } + + /// Whether an id is an added (atomic) token — the `is_special` flag. + pub fn is_special(&self, id: u32) -> bool { + self.added.contains(&id) + } + + /// The literal string of a token id (for diagnostics / special tokens). + pub fn token_str(&self, id: u32) -> Option { + self.tok.id_to_token(id) + } +} + +/// Incremental detokenizer over a growing id buffer. Decodes the whole buffer +/// each step and emits only the newly-stable suffix, holding back a trailing +/// incomplete code point (which the ByteLevel decoder renders as U+FFFD) until +/// more bytes arrive. Specials are atomic and emit immediately. +pub struct Detok { + tok: Arc, + ids: Vec, + emitted: usize, +} + +impl Detok { + pub fn new(tok: Arc) -> Self { + Self { + tok, + ids: Vec::new(), + emitted: 0, + } + } + + /// Feed one id; returns the newly-complete text (possibly empty). + pub fn push(&mut self, id: u32) -> String { + self.ids.push(id); + let full = match self.tok.decode_all(&self.ids) { + Ok(s) => s, + Err(_) => return String::new(), + }; + let stable = full.len() - trailing_replacement_bytes(&full); + if stable > self.emitted && full.is_char_boundary(self.emitted) { + let piece = full[self.emitted..stable].to_string(); + self.emitted = stable; + piece + } else { + String::new() + } + } + + /// Flush whatever is left (including any held replacement) at end of stream. + pub fn finish(&mut self) -> String { + let full = self.tok.decode_all(&self.ids).unwrap_or_default(); + if full.len() > self.emitted { + let piece = full[self.emitted..].to_string(); + self.emitted = full.len(); + piece + } else { + String::new() + } + } +} + +/// Byte length of a trailing run of U+FFFD (the replacement char), which marks +/// an incomplete code point we must not emit yet. +fn trailing_replacement_bytes(s: &str) -> usize { + let mut n = 0; + for c in s.chars().rev() { + if c == '\u{FFFD}' { + n += c.len_utf8(); + } else { + break; + } + } + n +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..2598dee --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,13 @@ +//! strata-ctl: a Rust control layer for the Strata inference engine. +//! +//! - [`engine`]: spawn `strata --serve` and speak its line protocol. +//! - [`api`]: the OpenAI-compatible HTTP surface (types, formatter seam, +//! completion service, axum routes). +//! +//! Next: the Inkling formatter (chat template + tokenizer), then wiring a +//! binary that reads the existing `strata-inkling.json` and serves. + +pub mod api; +pub mod config; +pub mod engine; +pub mod inkling; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..e354c03 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,230 @@ +//! strata-ctl CLI. +//! +//! Resolves the shared JSON config and either reports the launch plan (default) +//! or serves the OpenAI-compatible API (`--serve`): config -> Inkling +//! tokenizer + chat template -> formatter -> engine supervisor -> axum router. + +use std::path::Path; +use std::process::ExitCode; +use std::sync::Arc; +use std::time::Duration; + +use strata_ctl::api::{router, ChatService}; +use strata_ctl::config::{Config, ConfigError}; +use strata_ctl::engine::Engine; +use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer}; + +const USAGE: &str = "\ +strata-ctl — Rust control layer for the Strata engine (OpenAI-compatible API) + +USAGE: + strata-ctl [OPTIONS] + +OPTIONS: + --config model config JSON (default: ~/.config/strata-inkling/strata-inkling.json) + --host override the bind host from the config + --port override the bind port from the config + --serve start the engine and serve the API (default: print the launch plan) + -h, --help show this help +"; + +struct Args { + config: Option, + host: Option, + port: Option, + serve: bool, + help: bool, +} + +/// Hand-rolled flag parser: the surface mirrors the Python launcher and is far +/// smaller than a dependency on a CLI framework would justify. +fn parse_args>(mut it: I) -> Result { + let mut args = Args { + config: None, + host: None, + port: None, + serve: false, + help: false, + }; + while let Some(a) = it.next() { + match a.as_str() { + "-h" | "--help" => args.help = true, + "--serve" => args.serve = true, + "--config" => args.config = Some(it.next().ok_or("--config needs a value")?), + "--host" => args.host = Some(it.next().ok_or("--host needs a value")?), + "--port" => { + let v = it.next().ok_or("--port needs a value")?; + args.port = Some(v.parse().map_err(|_| format!("invalid --port: {v}"))?); + } + other if other.starts_with("--config=") => { + args.config = Some(other["--config=".len()..].to_string()) + } + other if other.starts_with("--host=") => { + args.host = Some(other["--host=".len()..].to_string()) + } + other if other.starts_with("--port=") => { + let v = &other["--port=".len()..]; + args.port = Some(v.parse().map_err(|_| format!("invalid --port: {v}"))?); + } + other => return Err(format!("unknown argument: {other}")), + } + } + Ok(args) +} + +#[tokio::main] +async fn main() -> ExitCode { + let args = match parse_args(std::env::args().skip(1)) { + Ok(a) => a, + Err(e) => { + eprintln!("error: {e}\n\n{USAGE}"); + return ExitCode::FAILURE; + } + }; + if args.help { + print!("{USAGE}"); + return ExitCode::SUCCESS; + } + + let path = match &args.config { + Some(p) => std::path::PathBuf::from(p), + None => Config::default_path(), + }; + let cfg = match Config::load(&path) { + Ok(c) => c, + Err(e) => return report_config_error(&path, e), + }; + + print_plan(&cfg, &path, args.host.as_deref(), args.port); + + if args.serve { + serve(&cfg, args.host.as_deref(), args.port).await + } else { + ExitCode::SUCCESS + } +} + +/// Start the engine from the config and serve the OpenAI-compatible API. +async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option) -> ExitCode { + let dir = match &cfg.tokenizer { + Some(d) => d.clone(), + None => { + eprintln!("error: config has no `tokenizer` directory; cannot build the formatter"); + return ExitCode::FAILURE; + } + }; + let tok = match InklingTokenizer::load_dir(Path::new(&dir)) { + Ok(t) => Arc::new(t), + Err(e) => { + eprintln!("error: {e}"); + return ExitCode::FAILURE; + } + }; + let tpl_path = Path::new(&dir).join("chat_template.jinja"); + let src = match std::fs::read_to_string(&tpl_path) { + Ok(s) => s, + Err(e) => { + eprintln!("error: cannot read {}: {e}", tpl_path.display()); + return ExitCode::FAILURE; + } + }; + let template = match ChatTemplate::new(&src) { + Ok(t) => t, + Err(e) => { + eprintln!("error: chat template: {e}"); + return ExitCode::FAILURE; + } + }; + let fmt = Arc::new(InklingFormatter::new( + tok, + template, + cfg.model_name().to_string(), + cfg.reasoning_effort.clone(), + )); + + let engine = match Engine::start( + &cfg.exe, + &cfg.engine_argv(), + cfg.cwd.as_deref(), + Duration::from_secs(600), + ) + .await + { + Ok(e) => Arc::new(e), + Err(e) => { + eprintln!("error: the engine failed to start: {e}"); + return ExitCode::FAILURE; + } + }; + println!( + "\nengine READY (context {} tokens); serving model {}", + engine.ready().max_context, + cfg.model_name() + ); + + let svc = ChatService::new(engine.clone(), fmt); + let app = router(svc); + let addr = format!("{}:{}", cfg.bind_host(cli_host), cfg.bind_port(cli_port)); + let listener = match tokio::net::TcpListener::bind(&addr).await { + Ok(l) => l, + Err(e) => { + eprintln!("error: cannot bind {addr}: {e}"); + return ExitCode::FAILURE; + } + }; + println!("listening on http://{addr} (Ctrl-C to stop)"); + + let shutdown_engine = engine.clone(); + let result = axum::serve(listener, app) + .with_graceful_shutdown(async move { + let _ = tokio::signal::ctrl_c().await; + println!("\nshutting down"); + let _ = shutdown_engine.shutdown().await; + }) + .await; + if let Err(e) = result { + eprintln!("error: server: {e}"); + return ExitCode::FAILURE; + } + ExitCode::SUCCESS +} + +fn print_plan(cfg: &Config, path: &std::path::Path, cli_host: Option<&str>, cli_port: Option) { + let host = cfg.bind_host(cli_host); + let port = cfg.bind_port(cli_port); + let ignored = cfg.ignored_keys(); + + println!("config: {}", path.display()); + println!("model: {}", cfg.model_name()); + println!("bind: {host}:{port}"); + println!("cwd: {}", cfg.cwd.as_deref().unwrap_or("(process cwd)")); + println!( + "tokenizer: {}", + cfg.tokenizer.as_deref().unwrap_or("(none configured)") + ); + println!( + "reasoning_effort: {}", + cfg.reasoning_effort.as_deref().unwrap_or("(default)") + ); + println!( + "sampling: temp={:?} top_p={:?} min_p={:?} rep_pen={:?}", + cfg.sampling.temperature, + cfg.sampling.top_p, + cfg.sampling.min_p, + cfg.sampling.repetition_penalty + ); + println!("\nwould spawn:"); + println!(" {} {}", cfg.exe, cfg.engine_argv().join(" ")); + if !ignored.is_empty() { + println!("\nignored keys (left for other tools / not yet acted on):"); + println!(" {}", ignored.join(", ")); + } +} + +fn report_config_error(path: &std::path::Path, err: ConfigError) -> ExitCode { + eprintln!("error: {err}"); + if let ConfigError::MissingExe = err { + eprintln!(" (check the `exe` field in {})", path.display()); + } + ExitCode::FAILURE +} diff --git a/tests/api_openai.rs b/tests/api_openai.rs new file mode 100644 index 0000000..4aeeaac --- /dev/null +++ b/tests/api_openai.rs @@ -0,0 +1,340 @@ +//! End-to-end tests of the OpenAI surface: HTTP request -> engine (mock) -> +//! HTTP response, non-stream and stream, driven through a trivial formatter so +//! the whole API layer is exercised without the real tokenizer. + +use std::sync::Arc; +use std::time::Duration; + +use axum::body::Body; +use axum::http::{header::CONTENT_TYPE, Method, Request, StatusCode}; +use tower::ServiceExt; // for `oneshot` + +use strata_ctl::api::formatter::{Decoder, Formatter, Piece, Prompt}; +use strata_ctl::api::service::ChatService; +use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest}; +use strata_ctl::engine::Engine; + +const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py"); + +/// A formatter with no dialect: the prompt is the last message's bytes; each +/// token id < 256 decodes to that byte as a char, always as "content". +struct ByteFormatter; + +impl Formatter for ByteFormatter { + fn model_name(&self) -> &str { + "test-model" + } + fn build_prompt(&self, req: &ChatRequest) -> Result { + let text = req + .messages + .iter() + .rev() + .find_map(|m| m.text()) + .unwrap_or("") + .to_string(); + Ok(Prompt { + ids: text.bytes().map(u32::from).collect(), + max_new: req.max_new(64), + sampling: Default::default(), + temp_files: Vec::new(), + }) + } + fn decoder(&self) -> Box { + Box::new(ByteDecoder) + } +} + +struct ByteDecoder; +impl Decoder for ByteDecoder { + fn push(&mut self, id: u32) -> Vec { + if id < 256 { + vec![Piece::Content(char::from(id as u8).to_string())] + } else { + Vec::new() + } + } + fn finish(&mut self, _reason: Option<&str>) -> Vec { + Vec::new() + } +} + +/// Drives the mock's long, STOP-interruptible generation (ids contain 888888). +struct LongFormatter; +impl Formatter for LongFormatter { + fn model_name(&self) -> &str { + "test-model" + } + fn build_prompt(&self, _req: &ChatRequest) -> Result { + Ok(Prompt { + ids: vec![888888], + max_new: 100000, + sampling: Default::default(), + temp_files: Vec::new(), + }) + } + fn decoder(&self) -> Box { + Box::new(ByteDecoder) + } +} + +async fn build_app() -> axum::Router { + let engine = Arc::new( + Engine::start( + "python3", + &[MOCK.to_string()], + None, + Duration::from_secs(10), + ) + .await + .expect("mock engine starts"), + ); + let svc = ChatService::new(engine, Arc::new(ByteFormatter)); + strata_ctl::api::router(svc) +} + +async fn post_json(app: &axum::Router, body: serde_json::Value) -> (StatusCode, String) { + let req = Request::builder() + .method(Method::POST) + .uri("/v1/chat/completions") + .header(CONTENT_TYPE, "application/json") + .body(Body::from(body.to_string())) + .unwrap(); + let resp = app.clone().oneshot(req).await.unwrap(); + let status = resp.status(); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + (status, String::from_utf8_lossy(&bytes).into_owned()) +} + +#[tokio::test] +async fn models_lists_the_served_model() { + let app = build_app().await; + let resp = app + .oneshot( + Request::builder() + .uri("/v1/models") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let body = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(json["object"], "list"); + assert_eq!(json["data"][0]["id"], "test-model"); +} + +#[tokio::test] +async fn non_stream_completion() { + let app = build_app().await; + let (status, text) = post_json( + &app, + serde_json::json!({ + "model": "test-model", + "messages": [{"role": "user", "content": "hi"}] + }), + ) + .await; + assert_eq!(status, StatusCode::OK, "body: {text}"); + let json: serde_json::Value = serde_json::from_str(&text).unwrap(); + + assert_eq!(json["object"], "chat.completion"); + // the mock's default path emits ids 101..105 -> 'e','f','g','h','i' + assert_eq!(json["choices"][0]["message"]["content"], "efghi"); + assert_eq!(json["choices"][0]["message"]["role"], "assistant"); + assert_eq!(json["choices"][0]["finish_reason"], "stop"); + assert_eq!(json["usage"]["completion_tokens"], 5); + assert_eq!( + json["usage"]["total_tokens"], + json["usage"]["prompt_tokens"].as_u64().unwrap() + 5 + ); + assert!(json["id"].as_str().unwrap().starts_with("chatcmpl-")); +} + +#[tokio::test] +async fn stream_completion_is_sse() { + let app = build_app().await; + let (status, text) = post_json( + &app, + serde_json::json!({ + "model": "test-model", + "messages": [{"role": "user", "content": "hi"}], + "stream": true + }), + ) + .await; + assert_eq!(status, StatusCode::OK, "body: {text}"); + + // every payload line is `data: ...`; the stream ends with `data: [DONE]` + let data_lines: Vec<&str> = text + .lines() + .filter(|l| l.starts_with("data: ")) + .map(|l| &l["data: ".len()..]) + .collect(); + assert!( + data_lines.last().copied() == Some("[DONE]"), + "no [DONE]: {text}" + ); + + // first chunk announces the role, the last (before [DONE]) the finish reason + let first: serde_json::Value = serde_json::from_str(data_lines[0]).unwrap(); + assert_eq!(first["object"], "chat.completion.chunk"); + assert_eq!(first["choices"][0]["delta"]["role"], "assistant"); + + // reassemble content across the middle chunks + let mut content = String::new(); + let mut finish = None; + for line in &data_lines[..data_lines.len() - 1] { + let v: serde_json::Value = serde_json::from_str(line).unwrap(); + if let Some(c) = v["choices"][0]["delta"]["content"].as_str() { + content.push_str(c); + } + if let Some(f) = v["choices"][0]["finish_reason"].as_str() { + finish = Some(f.to_string()); + } + } + assert_eq!(content, "efghi"); + assert_eq!(finish.as_deref(), Some("stop")); +} + +#[tokio::test] +async fn empty_messages_is_bad_request() { + let app = build_app().await; + let (status, text) = post_json( + &app, + serde_json::json!({"model": "test-model", "messages": []}), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let json: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(json["error"]["type"], "invalid_request_error"); +} + +#[tokio::test] +async fn malformed_json_is_openai_error() { + let app = build_app().await; + let req = Request::builder() + .method(Method::POST) + .uri("/v1/chat/completions") + .header(CONTENT_TYPE, "application/json") + .body(Body::from("{not json")) + .unwrap(); + let resp = app.oneshot(req).await.unwrap(); + assert_eq!(resp.status(), StatusCode::BAD_REQUEST); + let body = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!(json["error"]["message"] + .as_str() + .unwrap() + .contains("invalid JSON")); +} + +#[tokio::test] +async fn stream_aborts_on_client_disconnect() { + let engine = Arc::new( + Engine::start( + "python3", + &[MOCK.to_string()], + None, + Duration::from_secs(10), + ) + .await + .expect("mock engine starts"), + ); + let svc = ChatService::new(engine.clone(), Arc::new(LongFormatter)); + let app = strata_ctl::api::router(svc); + + let req = Request::builder() + .method(Method::POST) + .uri("/v1/chat/completions") + .header(CONTENT_TYPE, "application/json") + .body(Body::from( + serde_json::json!({ + "model": "test-model", + "messages": [{"role": "user", "content": "go"}], + "stream": true + }) + .to_string(), + )) + .unwrap(); + let resp = app.oneshot(req).await.unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + + // Simulate the client vanishing: drop the SSE body without reading it. The + // receiver is dropped, the disconnect select fires, the engine is aborted. + drop(resp); + + // Poll (non-mutating) until the engine is idle: the long generation must + // have been stopped, not left running for the full 100000 tokens. Bounded + // wait so the test is robust under parallel load. + let mut idle = false; + for _ in 0..100 { + if engine.is_idle() { + idle = true; + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert!(idle, "engine still busy after client disconnect"); + let _ = engine.shutdown().await; +} + +#[tokio::test] +async fn stop_sequence_truncates_content() { + let app = build_app().await; + // the mock's default answer is "efghi"; stop "gh" cuts it to "ef" + let (status, text) = post_json( + &app, + serde_json::json!({ + "model": "test-model", + "messages": [{"role": "user", "content": "hi"}], + "stop": ["gh"] + }), + ) + .await; + assert_eq!(status, StatusCode::OK, "body: {text}"); + let json: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(json["choices"][0]["message"]["content"], "ef"); + assert_eq!(json["choices"][0]["finish_reason"], "stop"); +} + +#[tokio::test] +async fn stop_sequence_truncates_stream() { + let app = build_app().await; + let (status, text) = post_json( + &app, + serde_json::json!({ + "model": "test-model", + "messages": [{"role": "user", "content": "hi"}], + "stop": ["gh"], + "stream": true + }), + ) + .await; + assert_eq!(status, StatusCode::OK, "body: {text}"); + let data_lines: Vec<&str> = text + .lines() + .filter(|l| l.starts_with("data: ")) + .map(|l| &l["data: ".len()..]) + .collect(); + assert_eq!(data_lines.last().copied(), Some("[DONE]")); + let mut content = String::new(); + let mut finish = None; + for line in &data_lines[..data_lines.len() - 1] { + let v: serde_json::Value = serde_json::from_str(line).unwrap(); + if let Some(c) = v["choices"][0]["delta"]["content"].as_str() { + content.push_str(c); + } + if let Some(f) = v["choices"][0]["finish_reason"].as_str() { + finish = Some(f.to_string()); + } + } + assert_eq!(content, "ef"); + assert_eq!(finish.as_deref(), Some("stop")); +} diff --git a/tests/engine_supervisor.rs b/tests/engine_supervisor.rs new file mode 100644 index 0000000..7d2640f --- /dev/null +++ b/tests/engine_supervisor.rs @@ -0,0 +1,121 @@ +//! End-to-end tests of the supervisor against a scripted mock engine +//! (tests/mock_engine.py), which speaks the protocol exactly as `strata +//! --serve` prints it. + +use std::time::Duration; + +use strata_ctl::engine::{Engine, EngineError, EngineLine, Sampling}; + +fn mock() -> (String, Vec) { + let script = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py"); + ( + "python3".into(), + vec![script.into(), "--marker".to_string()], + ) +} + +async fn start_mock() -> Engine { + let (exe, args) = mock(); + Engine::start(&exe, &args[0..1], None, Duration::from_secs(10)) + .await + .expect("mock engine starts") +} + +#[tokio::test] +async fn start_reads_ready() { + let engine = start_mock().await; + let ready = engine.ready(); + assert_eq!(ready.max_context, 8192); + assert!(ready.can_stop); + assert!(ready.can_hold); + assert!(!ready.can_hold_batch); + assert_eq!( + engine.info().await.get("version").map(String::as_str), + Some("0.0.0-mock") + ); + engine.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn generate_streams_and_finishes() { + let engine = start_mock().await; + let mut seen = Vec::new(); + let out = engine + .generate(16, &Sampling::default(), &[1, 2, 3, 4], |line| { + if let EngineLine::Prefill { read, total, .. } = line { + seen.push((*read, *total)); + } + }) + .await + .unwrap(); + assert_eq!(out.tokens, vec![101, 102, 103, 104, 105]); + assert_eq!(out.resumed, 1); + assert_eq!(seen, vec![(2, 4)]); + let done = out.done.unwrap(); + assert_eq!((done.generated, done.prompt_tokens), (5, 4)); + assert_eq!(done.finish, "stop"); + assert_eq!(done.extra, ["3", "4", "1"]); + engine.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn refusal_is_reported_and_trailing_done_swallowed() { + let engine = start_mock().await; + let err = engine + .generate(8, &Sampling::default(), &[1, 999999], |_| {}) + .await + .unwrap_err(); + assert!(matches!(&err, EngineError::Refused(m) if m.contains("out of range"))); + // the mock printed a DONE after the ERR: it must not leak to the next request + let out = engine + .generate(8, &Sampling::default(), &[1, 2], |_| {}) + .await + .unwrap(); + assert_eq!(out.tokens.len(), 5); + engine.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn abort_reaches_a_running_request_and_frees_the_wires() { + let exe_mock = mock(); + let engine = std::sync::Arc::new( + Engine::start( + &exe_mock.0, + &[exe_mock.1[0].clone()], + None, + Duration::from_secs(10), + ) + .await + .unwrap(), + ); + let holder = { + let engine = engine.clone(); + tokio::spawn(async move { + engine + .generate(1000, &Sampling::default(), &[888888], |_| {}) + .await + }) + }; + // a second request queues behind the first (FIFO, not a refusal) + let waiter = { + let engine = engine.clone(); + tokio::spawn(async move { + engine + .generate(8, &Sampling::default(), &[1, 2], |_| {}) + .await + }) + }; + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(engine.abort().await.unwrap(), "a request was running"); + let held = holder.await.unwrap(); + assert!( + matches!(&held, Err(EngineError::Refused(m)) if m == "aborted"), + "the held request should end aborted: {held:?}" + ); + // the queued waiter ran on the same engine and finished normally + let waited = waiter.await.unwrap(); + assert_eq!(waited.unwrap().tokens.len(), 5); + // nothing running now: abort is a no-op + assert!(!engine.abort().await.unwrap()); + engine.shutdown().await.unwrap(); +} diff --git a/tests/inkling_dialect.rs b/tests/inkling_dialect.rs new file mode 100644 index 0000000..57aac28 --- /dev/null +++ b/tests/inkling_dialect.rs @@ -0,0 +1,246 @@ +//! Tests for the Inkling output dialect, driving the public token stream the +//! way `server.py` does (one `feed_token` per engine token) and asserting the +//! reasoning/content framing the launcher-patched reference produces. + +use strata_ctl::inkling::dialect::{tag, InklingDialect, Kind, Out}; + +/// Feed a scripted sequence of tokens; `special` marks channel tokens. +fn run(tokens: &[(&str, bool)], finish: Option<&str>) -> Vec { + let mut d = InklingDialect::new(); + let mut out = Vec::new(); + for (piece, is_special) in tokens { + out.extend(d.feed_token(piece, *is_special)); + } + out.extend(d.finish(finish)); + out +} + +fn content_of(outs: &[Out]) -> String { + outs.iter() + .filter(|o| o.kind == Kind::Content) + .map(|o| o.text.as_str()) + .collect() +} +fn reasoning_of(outs: &[Out]) -> String { + outs.iter() + .filter(|o| o.kind == Kind::Reasoning) + .map(|o| o.text.as_str()) + .collect() +} + +#[test] +fn plain_text_answer() { + let outs = run( + &[ + (tag::MESSAGE_MODEL, true), + (tag::CONTENT_TEXT, true), + ("Hello world", false), + (tag::END_MESSAGE, true), + ], + None, + ); + assert_eq!(content_of(&outs), "Hello world"); + assert_eq!(reasoning_of(&outs), ""); +} + +#[test] +fn thinking_is_streamed_live_then_answers() { + let mut d = InklingDialect::new(); + let mut reasoning = Vec::new(); + let mut content = Vec::new(); + let feed = |d: &mut InklingDialect, + p: &str, + s: bool, + reasoning: &mut Vec, + content: &mut Vec| { + for o in d.feed_token(p, s) { + match o.kind { + Kind::Reasoning => reasoning.push(o.text), + Kind::Content => content.push(o.text), + } + } + }; + feed( + &mut d, + tag::MESSAGE_MODEL, + true, + &mut reasoning, + &mut content, + ); + feed( + &mut d, + tag::CONTENT_THINKING, + true, + &mut reasoning, + &mut content, + ); + feed(&mut d, "Let me ", false, &mut reasoning, &mut content); + feed(&mut d, "think. ", false, &mut reasoning, &mut content); + feed(&mut d, tag::END_MESSAGE, true, &mut reasoning, &mut content); + feed( + &mut d, + tag::MESSAGE_MODEL, + true, + &mut reasoning, + &mut content, + ); + feed( + &mut d, + tag::CONTENT_TEXT, + true, + &mut reasoning, + &mut content, + ); + feed(&mut d, "The answer.", false, &mut reasoning, &mut content); + feed(&mut d, tag::END_MESSAGE, true, &mut reasoning, &mut content); + d.finish(None); + + // reasoning arrived as discrete live deltas, not one blob at the end + assert_eq!(reasoning, vec!["Let me ", "think. "]); + assert_eq!(content.join(""), "The answer."); +} + +#[test] +fn quoted_end_message_stays_in_thinking() { + // #6675: the model literally writes `<|end_message|>` inside its thinking; + // it must not leak to content nor end thinking early. + let outs = run( + &[ + (tag::MESSAGE_MODEL, true), + (tag::CONTENT_THINKING, true), + ("before ", false), + (tag::END_MESSAGE, true), // quoted, not a real channel end + ("after", false), // ordinary text proves it was quoted + (tag::ENDOFTEXT, true), + ], + None, + ); + assert_eq!(content_of(&outs), ""); + let r = reasoning_of(&outs); + assert!(r.contains("before "), "{r}"); + assert!( + r.contains(tag::END_MESSAGE), + "quoted tag kept in reasoning: {r}" + ); + assert!(r.contains("after"), "{r}"); +} + +#[test] +fn header_overflow_becomes_plain_text() { + // #6620: no `<|content_text|>`; a newline in the "header" means it is text. + let outs = run( + &[ + (tag::MESSAGE_MODEL, true), + ("Just prose\ncontinued", false), + (tag::END_MESSAGE, true), + ], + None, + ); + assert_eq!(content_of(&outs), "Just prose\ncontinued"); +} + +#[test] +fn tool_json_renders_a_frame() { + let outs = run( + &[ + (tag::MESSAGE_MODEL, true), + ("get_weather", false), + (tag::CONTENT_INVOKE_TOOL_JSON, true), + (r#"{"name":"get_weather","args":{"city":"Rome"}}"#, false), + (tag::END_MESSAGE, true), + ], + None, + ); + let c = content_of(&outs); + assert!(c.contains(tag::TOOL_CALL_OPEN), "{c}"); + assert!(c.contains(tag::TOOL_CALL_CLOSE), "{c}"); + // the JSON inside round-trips name + arguments + let json_start = c.find('{').unwrap(); + let json_end = c.rfind('}').unwrap(); + let v: serde_json::Value = serde_json::from_str(&c[json_start..=json_end]).unwrap(); + assert_eq!(v["name"], "get_weather"); + assert_eq!(v["arguments"]["city"], "Rome"); +} + +#[test] +fn tool_json_args_as_json_string_is_parsed() { + // arguments shipped as a JSON *string* must be parsed into an object + let outs = run( + &[ + (tag::MESSAGE_MODEL, true), + (tag::CONTENT_INVOKE_TOOL_JSON, true), + (r#"{"name":"f","args":"{\"a\":1}"}"#, false), + (tag::END_MESSAGE, true), + ], + None, + ); + let c = content_of(&outs); + let v: serde_json::Value = + serde_json::from_str(&c[c.find('{').unwrap()..=c.rfind('}').unwrap()]).unwrap(); + assert_eq!(v["arguments"]["a"], 1); +} + +#[test] +fn truncated_tool_falls_back_to_header_name() { + let mut d = InklingDialect::new(); + let mut content = String::new(); + for (p, s) in [ + (tag::MESSAGE_MODEL, true), + ("lookup", false), + (tag::CONTENT_INVOKE_TOOL_JSON, true), + ( + "{\"a\":1", // unterminated + false, + ), + ] { + for o in d.feed_token(p, s) { + if o.kind == Kind::Content { + content.push_str(&o.text); + } + } + } + for o in d.finish(Some("length")) { + if o.kind == Kind::Content { + content.push_str(&o.text); + } + } + assert!(content.contains(tag::TOOL_CALL_OPEN), "{content}"); + let v: serde_json::Value = + serde_json::from_str(&content[content.find('{').unwrap()..=content.rfind('}').unwrap()]) + .unwrap(); + assert_eq!(v["name"], "lookup"); + assert_eq!(d.calls, 1); +} + +#[test] +fn thinking_only_at_length_surfaces_reasoning() { + // #6682: budget expires mid-thinking with no answer. + let outs = run( + &[ + (tag::MESSAGE_MODEL, true), + (tag::CONTENT_THINKING, true), + ("pondering", false), + ], + Some("length"), + ); + assert!(content_of(&outs).is_empty()); + // the live delta plus the finish-time accumulation both carry it (faithful + // to the reference: patched emit + _finish_typed #6682) + assert!(reasoning_of(&outs).contains("pondering")); +} + +#[test] +fn end_sampling_returns_to_idle() { + // after END_SAMPLING a new turn can open; ensure a following MessageModel + // does not double-emit the prior content. + let outs = run( + &[ + (tag::MESSAGE_MODEL, true), + (tag::CONTENT_TEXT, true), + ("first", false), + (tag::END_SAMPLING, true), + ], + None, + ); + assert_eq!(content_of(&outs), "first"); +} diff --git a/tests/inkling_formatter.rs b/tests/inkling_formatter.rs new file mode 100644 index 0000000..581c529 --- /dev/null +++ b/tests/inkling_formatter.rs @@ -0,0 +1,222 @@ +//! End-to-end test of the assembled InklingFormatter: prompt build (template + +//! encode) and output decode (detok + channel dialect -> API pieces), using a +//! host-independent fixture tokenizer whose decoder concatenates without spaces +//! (like the real ByteLevel decoder), so channel tags match exactly. + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::json; +use tokenizers::decoders::fuse::Fuse; +use tokenizers::models::wordlevel::WordLevel; +use tokenizers::{AddedToken, Tokenizer}; + +use strata_ctl::api::formatter::{Formatter, Piece}; +use strata_ctl::api::types::ChatRequest; +use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer}; + +static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +fn fixture_tokenizer() -> (Arc, std::path::PathBuf) { + let mut vocab = HashMap::new(); + vocab.insert("think".to_string(), 0u32); + vocab.insert("answer".to_string(), 1u32); + vocab.insert("hello".to_string(), 2u32); + vocab.insert("[UNK]".to_string(), 3u32); + vocab.insert(TOOL_BODY.to_string(), 4u32); + let model = WordLevel::builder() + .vocab(vocab.into_iter().collect()) + .unk_token("[UNK]".to_string()) + .build() + .unwrap(); + let mut tok = Tokenizer::new(model); + // no pre-tokenizer: each whole segment maps to one vocab word (the JSON tool + // body must not be split on punctuation), specials still match via the trie + tok.with_pre_tokenizer(None::); + // concatenate without separators, mirroring the real ByteLevel decoder + tok.with_decoder(Some(Fuse::new())); + let _ = tok.add_special_tokens([ + AddedToken::from("<|message_model|>", true), + AddedToken::from("<|content_thinking|>", true), + AddedToken::from("<|content_text|>", true), + AddedToken::from("<|end_message|>", true), + AddedToken::from("<|content_model_end_sampling|>", true), + AddedToken::from("<|content_invoke_tool_json|>", true), + ]); + let path = std::env::temp_dir().join(format!( + "strata-ctl-fmt-{}-{}.json", + std::process::id(), + SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + tok.save(&path, false).unwrap(); + (Arc::new(InklingTokenizer::from_file(&path).unwrap()), path) +} + +const TEMPLATE: &str = + "{%- for m in messages -%}<|content_text|>{{ m.content }}<|end_message|>{%- endfor -%}"; + +/// A tool-call body as one whitespace-free word (the fixture is WordLevel). +const TOOL_BODY: &str = r#"{"name":"get_weather","args":{"city":"Roma"}}"#; + +fn formatter() -> (InklingFormatter, Arc, std::path::PathBuf) { + let (tok, path) = fixture_tokenizer(); + let template = ChatTemplate::new(TEMPLATE).unwrap(); + let fmt = InklingFormatter::new( + tok.clone(), + template, + "test-model".into(), + Some("low".into()), + ); + (fmt, tok, path) +} + +#[test] +fn build_prompt_renders_and_encodes() { + let (fmt, tok, path) = formatter(); + let req: ChatRequest = serde_json::from_value( + json!({"model": "test-model", "messages": [{"role": "user", "content": "hello"}]}), + ) + .unwrap(); + let prompt = fmt.build_prompt(&req).unwrap(); + // the rendered prompt is "<|content_text|>hello<|end_message|>" + let text_id = tok.encode("<|content_text|>").unwrap()[0]; + let end_id = tok.encode("<|end_message|>").unwrap()[0]; + assert!(prompt.ids.contains(&text_id)); + assert!(prompt.ids.contains(&2)); // "hello" + assert!(prompt.ids.contains(&end_id)); + assert_eq!(prompt.max_new, 2048); // default + let _ = std::fs::remove_file(&path); +} + +#[test] +fn decoder_splits_reasoning_and_content() { + let (fmt, tok, path) = formatter(); + let mut dec = fmt.decoder(); + + // a scripted assistant reply: thinking, then the answer + let script = [ + "<|message_model|>", + "<|content_thinking|>", + "think", + "<|end_message|>", + "<|message_model|>", + "<|content_text|>", + "answer", + "<|end_message|>", + ]; + let mut reasoning = String::new(); + let mut content = String::new(); + for seg in script { + for id in tok.encode(seg).unwrap() { + for p in dec.push(id) { + match p { + Piece::Reasoning(s) => reasoning.push_str(&s), + Piece::Content(s) => content.push_str(&s), + Piece::ToolCall { .. } => {} + } + } + } + } + for p in dec.finish(None) { + match p { + Piece::Reasoning(s) => reasoning.push_str(&s), + Piece::Content(s) => content.push_str(&s), + Piece::ToolCall { .. } => {} + } + } + assert_eq!(reasoning, "think"); + assert_eq!(content, "answer"); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn max_tokens_override_is_honored() { + let (fmt, _tok, path) = formatter(); + let req: ChatRequest = serde_json::from_value(json!({ + "model": "test-model", + "messages": [{"role": "user", "content": "hello"}], + "max_tokens": 77 + })) + .unwrap(); + assert_eq!(fmt.build_prompt(&req).unwrap().max_new, 77); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn decoder_emits_structured_tool_call() { + let (fmt, tok, path) = formatter(); + let mut dec = fmt.decoder(); + + // assistant opens a JSON tool channel, emits the call body, closes it + let script = [ + "<|message_model|>", + "<|content_invoke_tool_json|>", + TOOL_BODY, + "<|end_message|>", + ]; + let mut calls: Vec<(String, String)> = Vec::new(); + let mut content = String::new(); + for seg in script { + for id in tok.encode(seg).unwrap() { + for p in dec.push(id) { + match p { + Piece::ToolCall { name, arguments } => calls.push((name, arguments)), + Piece::Content(s) => content.push_str(&s), + Piece::Reasoning(_) => {} + } + } + } + } + for p in dec.finish(None) { + if let Piece::ToolCall { name, arguments } = p { + calls.push((name, arguments)); + } + } + assert_eq!(calls.len(), 1, "content was: {content}"); + assert_eq!(calls[0].0, "get_weather"); + assert_eq!(calls[0].1, r#"{"city":"Roma"}"#); + // the raw frame must NOT leak into content + assert!(content.is_empty(), "frame leaked into content: {content}"); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn tool_choice_forcing_is_rejected() { + let (fmt, _tok, path) = formatter(); + for choice in [ + json!("required"), + json!({"type": "function", "function": {"name": "f"}}), + json!("bogus"), + ] { + let req: ChatRequest = serde_json::from_value(json!({ + "model": "m", + "messages": [{"role": "user", "content": "hello"}], + "tool_choice": choice + })) + .unwrap(); + assert!( + fmt.build_prompt(&req).is_err(), + "choice {choice} should be rejected" + ); + } + let _ = std::fs::remove_file(&path); +} + +#[test] +fn tool_choice_none_and_auto_accepted() { + let (fmt, _tok, path) = formatter(); + for choice in [json!("none"), json!("auto")] { + let req: ChatRequest = serde_json::from_value(json!({ + "model": "m", + "messages": [{"role": "user", "content": "hello"}], + "tools": [{"type": "function", "function": {"name": "f"}}], + "tool_choice": choice + })) + .unwrap(); + assert!( + fmt.build_prompt(&req).is_ok(), + "choice {choice} should be accepted" + ); + } + let _ = std::fs::remove_file(&path); +} diff --git a/tests/inkling_images.rs b/tests/inkling_images.rs new file mode 100644 index 0000000..e6af540 --- /dev/null +++ b/tests/inkling_images.rs @@ -0,0 +1,109 @@ +//! Tests for the Inkling image bridge: path encoding, source extraction across +//! OpenAI/Responses/Anthropic shapes, and materialization (PNG passthrough, +//! WebP->PNG normalization, local path). Host-independent: images are built in +//! memory with the image crate. + +use base64::Engine; +use serde_json::json; +use strata_ctl::inkling::images::{encode_path, extract_sources, materialize}; + +fn png_bytes() -> Vec { + let img = image::DynamicImage::ImageRgba8(image::RgbaImage::new(2, 2)); + let mut buf = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png) + .unwrap(); + buf +} + +fn webp_bytes() -> Vec { + let img = image::DynamicImage::ImageRgba8(image::RgbaImage::new(2, 2)); + let mut buf = Vec::new(); + img.write_to( + &mut std::io::Cursor::new(&mut buf), + image::ImageFormat::WebP, + ) + .unwrap(); + buf +} + +fn data_url(mime: &str, bytes: &[u8]) -> String { + format!( + "data:{mime};base64,{}", + base64::engine::general_purpose::STANDARD.encode(bytes) + ) +} + +#[test] +fn encode_path_only_percent_and_space() { + assert_eq!(encode_path("/mnt/my pic.png"), "/mnt/my%20pic.png"); + assert_eq!(encode_path("/a%b.png"), "/a%25b.png"); + assert_eq!(encode_path("/a %b.png"), "/a%20%25b.png"); + // slashes stay literal (the engine only decodes %20 and %25) + assert_eq!(encode_path("/mnt/x/y.png"), "/mnt/x/y.png"); +} + +#[test] +fn extract_sources_shapes_and_order() { + let msgs = json!([ + {"role": "user", "content": [ + {"type": "text", "text": "guarda"}, + {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAA"}}, + {"type": "image_url", "image_url": "/local/a.png"} + ]}, + {"role": "user", "content": [ + {"type": "input_image", "image_url": "https://x/b.png"}, + {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "BBB"}} + ]} + ]); + let srcs = extract_sources(&msgs); + assert_eq!( + srcs, + vec![ + "data:image/png;base64,AAA", + "/local/a.png", + "https://x/b.png", + "data:image/jpeg;base64,BBB", + ] + ); +} + +#[test] +fn extract_ignores_text_only() { + let msgs = json!([{"role": "user", "content": "ciao"}]); + assert!(extract_sources(&msgs).is_empty()); +} + +#[test] +fn materialize_png_passthrough() { + let png = png_bytes(); + let paths = materialize(&[data_url("image/png", &png)]).unwrap(); + assert_eq!(paths.len(), 1); + assert_eq!(paths[0].extension().unwrap(), "png"); + assert_eq!(std::fs::read(&paths[0]).unwrap(), png); + let _ = std::fs::remove_file(&paths[0]); +} + +#[test] +fn materialize_webp_normalizes_to_png() { + let webp = webp_bytes(); + let paths = materialize(&[data_url("image/webp", &webp)]).unwrap(); + assert_eq!(paths.len(), 1); + assert_eq!(paths[0].extension().unwrap(), "png"); + let out = std::fs::read(&paths[0]).unwrap(); + assert!( + out.starts_with(&[0x89, b'P', b'N', b'G']), + "not converted to PNG" + ); + let _ = std::fs::remove_file(&paths[0]); +} + +#[test] +fn materialize_local_path() { + let png = png_bytes(); + let src = std::env::temp_dir().join(format!("strata-ctl-img-src-{}.png", std::process::id())); + std::fs::write(&src, &png).unwrap(); + let paths = materialize(&[src.to_string_lossy().to_string()]).unwrap(); + assert_eq!(std::fs::read(&paths[0]).unwrap(), png); + let _ = std::fs::remove_file(&paths[0]); + let _ = std::fs::remove_file(&src); +} diff --git a/tests/inkling_template.rs b/tests/inkling_template.rs new file mode 100644 index 0000000..2897378 --- /dev/null +++ b/tests/inkling_template.rs @@ -0,0 +1,111 @@ +//! Tests for the Inkling chat-template layer: the custom tojson/raise_exception +//! and generation-strip (deterministic, inline template), prepare_messages / +//! finish_prompt (pure), and an #[ignore] render of the real chat_template.jinja. + +use serde_json::json; +use strata_ctl::inkling::dialect::tag; +use strata_ctl::inkling::template::{finish_prompt, prepare_messages, ChatTemplate}; + +#[test] +fn tojson_compact_and_sorted() { + let t = + ChatTemplate::new("{{ {'b': 1, 'a': 2} | tojson(sort_keys=true, separators=(',', ':')) }}") + .unwrap(); + assert_eq!( + t.render(&json!([]), None, None).unwrap(), + "{\"a\":2,\"b\":1}" + ); +} + +#[test] +fn generation_blocks_are_transparent() { + let t = ChatTemplate::new("A{% generation %}B{% endgeneration %}C").unwrap(); + assert_eq!(t.render(&json!([]), None, None).unwrap(), "ABC"); +} + +#[test] +fn namespace_and_dictsort_work() { + let src = "{%- set s = namespace(x=[]) -%}\ + {%- set s.x = s.x + [1, 2] -%}\ + {{ s.x | tojson(separators=(',', ':')) }}|\ + {%- for k, v in {'b': 1, 'a': 2} | dictsort(case_sensitive=true) -%}\ + {{ k }}={{ v }};{%- endfor -%}"; + let t = ChatTemplate::new(src).unwrap(); + assert_eq!(t.render(&json!([]), None, None).unwrap(), "[1,2]|a=2;b=1;"); +} + +#[test] +fn raise_exception_fails_render() { + let t = ChatTemplate::new("{{ raise_exception('boom') }}").unwrap(); + let err = t.render(&json!([]), None, None).unwrap_err(); + assert!(err.to_string().contains("boom"), "{err}"); +} + +#[test] +fn prepare_messages_parses_string_arguments() { + let mut msgs = json!([ + {"role": "assistant", "tool_calls": [ + {"id": "c1", "type": "function", + "function": {"name": "f", "arguments": "{\"a\": 1}"}} + ]}, + {"role": "assistant", "tool_calls": [ + {"id": "c2", "function": {"name": "g", "arguments": null}} + ]} + ]); + prepare_messages(&mut msgs); + assert_eq!( + msgs[0]["tool_calls"][0]["function"]["arguments"], + json!({"a": 1}) + ); + assert_eq!(msgs[1]["tool_calls"][0]["function"]["arguments"], json!({})); +} + +#[test] +fn finish_prompt_only_for_effort_zero() { + // positive effort: untouched (model opens its own thinking) + let p = "<|message_system|><|content_text|>Thinking effort level: 0.2<|end_message|>"; + assert_eq!(finish_prompt(p, false, false), p); + + // effort zero, no opener yet: append the text opener (no tools) + let z = "<|message_system|><|content_text|>Thinking effort level: 0<|end_message|>"; + let expect = format!("{z}{}{}", tag::MESSAGE_MODEL, tag::CONTENT_TEXT); + assert_eq!(finish_prompt(z, false, false), expect); + + // with tools: the empty-thinking opener + let expect_tools = format!( + "{z}{}{}{}", + tag::MESSAGE_MODEL, + tag::CONTENT_THINKING, + tag::END_MESSAGE + ); + assert_eq!(finish_prompt(z, true, false), expect_tools); + + // idempotent: already ends with the text opener + assert_eq!(finish_prompt(&expect, false, false), expect); +} + +/// Render the REAL template (host file). Run with: +/// STRATA_TOK_DIR=~/.config/strata-inkling/inkling-tok cargo test -- --ignored +#[test] +#[ignore = "needs the real Inkling chat_template.jinja"] +fn real_template_renders_a_turn() { + let dir = std::env::var("STRATA_TOK_DIR") + .unwrap_or_else(|_| "/home/federico/.config/strata-inkling/inkling-tok".to_string()); + let src = std::fs::read_to_string(format!("{dir}/chat_template.jinja")).unwrap(); + let t = ChatTemplate::new(&src).unwrap(); + + let msgs = json!([{"role": "user", "content": "ciao"}]); + let out = t.render(&msgs, None, Some("low")).unwrap(); + assert!(out.contains("Thinking effort level: 0.2"), "{out}"); + assert!( + out.contains("<|message_user|><|content_text|>ciao<|end_message|>"), + "{out}" + ); + + // effort none renders level 0 + let out0 = t.render(&msgs, None, Some("none")).unwrap(); + assert!( + out0.contains("Thinking effort level: 0<|end_message|>"), + "{out0}" + ); +} diff --git a/tests/inkling_tokenizer.rs b/tests/inkling_tokenizer.rs new file mode 100644 index 0000000..50459e4 --- /dev/null +++ b/tests/inkling_tokenizer.rs @@ -0,0 +1,133 @@ +//! Tests for the Inkling tokenizer wrapper. +//! +//! The deterministic tests build a tiny fixture tokenizer with the `tokenizers` +//! crate (no host files), so the suite is green anywhere. A separate `#[ignore]` +//! test exercises the REAL o200k tokenizer when STRATA_TOK_DIR is set; run it +//! with `cargo test -- --ignored`. + +use std::collections::HashMap; +use std::sync::Arc; + +use tokenizers::models::wordlevel::WordLevel; +use tokenizers::AddedToken; +use tokenizers::Tokenizer; + +use strata_ctl::inkling::dialect::Tag; +use strata_ctl::inkling::tokenizer::{Detok, InklingTokenizer}; + +/// Unique suffix so parallel tests never share a fixture file. +static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Build a small WordLevel tokenizer with a few Inkling channel tokens added, +/// save it, and load it through our wrapper. Returns (wrapper, path, ids). +fn fixture() -> (InklingTokenizer, std::path::PathBuf) { + let mut vocab = HashMap::new(); + vocab.insert("hello".to_string(), 0u32); + vocab.insert("world".to_string(), 1u32); + vocab.insert("[UNK]".to_string(), 2u32); + let model = WordLevel::builder() + .vocab(vocab.into_iter().collect()) + .unk_token("[UNK]".to_string()) + .build() + .unwrap(); + let mut tok = Tokenizer::new(model); + tok.with_pre_tokenizer(Some(tokenizers::pre_tokenizers::whitespace::Whitespace)); + let _ = tok.add_special_tokens([ + AddedToken::from("<|message_model|>", true), + AddedToken::from("<|content_text|>", true), + AddedToken::from("<|content_thinking|>", true), + AddedToken::from("<|end_message|>", true), + ]); + let path = std::env::temp_dir().join(format!( + "strata-ctl-tok-{}-{}.json", + std::process::id(), + SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + tok.save(&path, false).unwrap(); + let wrapped = InklingTokenizer::from_file(&path).unwrap(); + (wrapped, path) +} + +#[test] +fn encode_decode_roundtrip() { + let (t, path) = fixture(); + let ids = t.encode("hello world").unwrap(); + assert_eq!(ids, vec![0, 1]); + let decoded = t.decode_all(&ids).unwrap(); + assert!( + decoded.contains("hello") && decoded.contains("world"), + "{decoded}" + ); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn channel_tokens_map_to_tags() { + let (t, path) = fixture(); + // a channel token encodes to a single id and maps back to its dialect tag + let ids = t.encode("<|content_thinking|>").unwrap(); + assert_eq!(ids.len(), 1); + assert!(t.is_special(ids[0])); + assert_eq!(t.channel_tag(ids[0]), Some(Tag::ContentThinking)); + + let ids = t.encode("<|end_message|>").unwrap(); + assert_eq!(t.channel_tag(ids[0]), Some(Tag::EndMessage)); + // an ordinary word is not special + assert!(!t.is_special(0)); + assert_eq!(t.channel_tag(0), None); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn detok_streams_incrementally() { + let (t, path) = fixture(); + let mut d = Detok::new(Arc::new(t)); + let a = d.push(0); + let b = d.push(1); + let c = d.finish(); + // WordLevel decode re-inserts the whitespace between words + assert_eq!(format!("{a}{b}{c}"), "hello world"); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn detok_emits_special_tokens_immediately() { + let (t, path) = fixture(); + let think_id = t.encode("<|content_thinking|>").unwrap()[0]; + let mut d = Detok::new(Arc::new(t)); + // ordinary word then a channel token: both surface as text pieces + let a = d.push(0); + let b = d.push(think_id); + assert_eq!(a, "hello"); + assert!(b.contains("<|content_thinking|>"), "{b}"); + let _ = std::fs::remove_file(&path); +} + +/// Real-tokenizer check, ignored by default (host files). Run with: +/// STRATA_TOK_DIR=~/.config/strata-inkling/inkling-tok cargo test -- --ignored +#[test] +#[ignore = "needs the real Inkling tokenizer dir"] +fn real_tokenizer_channel_ids() { + let dir = std::env::var("STRATA_TOK_DIR") + .unwrap_or_else(|_| "/home/federico/.config/strata-inkling/inkling-tok".to_string()); + let t = InklingTokenizer::load_dir(std::path::Path::new(&dir)).expect("load real tokenizer"); + + // the exact ids observed in tokenizer.hf.json's added_tokens + assert_eq!(t.channel_tag(200001), Some(Tag::MessageModel)); + assert_eq!(t.channel_tag(200004), Some(Tag::ContentText)); + assert_eq!(t.channel_tag(200006), Some(Tag::EndSampling)); + assert_eq!(t.channel_tag(200008), Some(Tag::ContentThinking)); + assert_eq!(t.channel_tag(200010), Some(Tag::EndMessage)); + assert_eq!(t.channel_tag(200024), Some(Tag::ContentXml)); + assert_eq!(t.channel_tag(200049), Some(Tag::ContentInvokeToolJson)); + assert_eq!(t.channel_tag(200057), Some(Tag::ContentInvokeToolText)); + assert_eq!(t.channel_tag(199999), Some(Tag::EndOfText)); + + // a channel token in a rendered prompt encodes to its single id + let ids = t + .encode("<|message_model|><|content_text|>ciao<|end_message|>") + .unwrap(); + assert_eq!(ids.first().copied(), Some(200001)); + assert_eq!(ids.last().copied(), Some(200010)); + assert!(t.decode_all(&ids).unwrap().contains("ciao")); +} diff --git a/tests/mock_engine.py b/tests/mock_engine.py new file mode 100644 index 0000000..46623be --- /dev/null +++ b/tests/mock_engine.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""A scripted stand-in for `strata --serve`, for strata-ctl's integration tests. + +Speaks the line protocol exactly as the engine's parser emits it: +READY/INFO at start, then per GEN: optional RESUME, PP lines, T lines, DONE. + +Faithful to the real engine's key invariant: **one DONE per request**. A STOP +arriving mid-request ends that request with a single DONE and is not answered +again; a STOP arriving while idle is ignored (no request to abort). Stdin is +read on a background thread so STOP can interrupt a long generation, exactly +as the resident engine's own stdin reader does. + +Scenarios, keyed by the prompt ids sent: + * 999999 in ids -> ERR then DONE (a refused id) + * 888888 in ids -> long generation (many tokens), interruptible by STOP + * 777777 in ids -> total silence (the supervisor's watchdog must fire) + * otherwise -> echo five tokens and finish +""" +import queue +import sys +import threading +import time + + +def out(line: str) -> None: + sys.stdout.write(line + "\n") + sys.stdout.flush() + + +def reader(cmds: "queue.Queue[str]") -> None: + for raw in sys.stdin: + cmds.put(raw.strip()) + cmds.put(None) # EOF + + +out("INFO version=0.0.0-mock build=test") +out("READY 8192 stop hold") + +cmds: "queue.Queue[str | None]" = queue.Queue() +threading.Thread(target=reader, args=(cmds,), daemon=True).start() + +while True: + cmd = cmds.get() + if cmd is None or cmd == "QUIT": + break + if cmd == "STOP": + continue # idle STOP: nothing to abort, no reply (as the real engine) + if not cmd.startswith("GEN"): + out("ERR unknown command") + continue + parts = cmd.split() + if len(parts) < 3: + out("ERR GEN: missing ids") + continue + try: + ids = [int(t) for t in parts[-1].split(",")] + except ValueError: + out("ERR GEN: bad id") + continue + keys = " ".join(parts[1:-1]) + + if "bad_key" in keys: + out("ERR GEN: unknown/unsupported key bad_key") + out("DONE 0 0 0.0 0.0 error") + continue + if 999999 in ids: + out("ERR GEN: id out of range") + out("DONE 0 0 0.0 0.0 error") + continue + if 777777 in ids: + # total silence for this request: swallow commands until a STOP ends it + while True: + nxt = cmds.get() + if nxt is None or nxt == "QUIT": + sys.exit(0) + if nxt == "STOP": + out("DONE 0 0 0.0 0.0 abort") + break + continue + if 888888 in ids: + out("RESUME 3") + out("PP 5 5 1.5 3333.3") + n = 0 + stopped = False + while n < 100000: + nxt = cmds.get_nowait() if not cmds.empty() else None + if nxt == "STOP": + stopped = True + break + n += 1 + out(f"T {n}") + if n % 50 == 0: + time.sleep(0.001) + out(f"DONE {n} {len(ids)} 1.0 2.0 {'abort' if stopped else 'length'}") + continue + + out("RESUME 1") + out("PP 2 4 0.9 2222.2") + for t in (101, 102, 103, 104, 105): + out(f"T {t}") + out("DONE 5 4 12.5 34.0 stop 3 4 1")