diff --git a/Cargo.lock b/Cargo.lock index 09a0b20..584c27c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -52,6 +52,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -82,10 +91,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] -name = "base64" -version = "0.23.1" +name = "base64ct" +version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "bitflags" @@ -172,20 +181,10 @@ dependencies = [ ] [[package]] -name = "codex-connector" -version = "0.1.0" -source = "git+https://github.com/GameCult/CodexConnector.git?rev=68fe94b9475823de92ed766a97ea962d48723708#68fe94b9475823de92ed766a97ea962d48723708" -dependencies = [ - "aes-gcm", - "base64 0.23.1", - "rand_core 0.6.4", - "rmp-serde", - "serde", - "serde_json", - "sha2", - "thiserror", - "zeroize", -] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" [[package]] name = "core-foundation-sys" @@ -238,7 +237,7 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a01 dependencies = [ "anyhow", "chrono", - "cultcache-rs-derive", + "cultcache-rs-derive 0.1.0", "fs2", "redb", "rmp-serde", @@ -249,6 +248,26 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "cultcache-rs" +version = "0.3.1" +source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" +dependencies = [ + "anyhow", + "chrono", + "cultcache-rs-derive 0.2.0", + "fs2", + "redb", + "rmp-serde", + "serde", + "serde_bytes", + "serde_json", + "serde_stacker", + "stacker", + "uuid", + "windows-sys 0.59.0", +] + [[package]] name = "cultcache-rs-derive" version = "0.1.0" @@ -259,6 +278,78 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "cultcache-rs-derive" +version = "0.2.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "cultnet-rs" +version = "0.2.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" +dependencies = [ + "aes-gcm", + "anyhow", + "base64", + "chrono", + "cultcache-rs 0.3.1", + "ed25519-dalek", + "hmac", + "rand 0.9.5", + "rmp-serde", + "rmpv", + "serde", + "serde_bytes", + "serde_json", + "sha2", + "socket2 0.5.10", + "uuid", + "windows-sys 0.61.2", + "zeroize", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + [[package]] name = "digest" version = "0.10.7" @@ -267,6 +358,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -280,6 +372,36 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + [[package]] name = "errno" version = "0.3.14" @@ -296,6 +418,12 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "find-msvc-tools" version = "0.1.11" @@ -404,6 +532,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -413,7 +553,7 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", + "r-efi 6.0.0", "rand_core 0.10.1", "wasm-bindgen", ] @@ -434,9 +574,9 @@ version = "0.1.0" dependencies = [ "async-trait", "chrono", - "codex-connector", - "cultcache-rs", + "cultcache-rs 0.1.0", "ghostlight-persona-projection", + "model-connector", "reqwest", "rmp-serde", "rmpv", @@ -475,6 +615,15 @@ dependencies = [ "tokio", ] +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "http" version = "1.5.0" @@ -556,7 +705,7 @@ version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ - "base64 0.22.1", + "base64", "bytes", "futures-channel", "futures-util", @@ -567,7 +716,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2", + "socket2 0.6.5", "tokio", "tower-service", "tracing", @@ -789,6 +938,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "model-connector" +version = "0.1.0" +source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=edf2f8e03cbb61df385b9b145b46f676ce3b70d5#edf2f8e03cbb61df385b9b145b46f676ce3b70d5" +dependencies = [ + "aes-gcm", + "base64", + "cultnet-rs", + "rand_core 0.6.4", + "rmp-serde", + "rmpv", + "schemars", + "serde", + "serde_bytes", + "serde_json", + "sha2", + "thiserror", + "zeroize", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -798,6 +967,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -845,6 +1023,16 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "polyval" version = "0.6.2" @@ -866,6 +1054,15 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -875,6 +1072,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quinn" version = "0.11.11" @@ -888,7 +1095,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls", - "socket2", + "socket2 0.6.5", "thiserror", "tokio", "tracing", @@ -904,7 +1111,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand", + "rand 0.10.2", "rand_pcg", "ring", "rustc-hash", @@ -926,7 +1133,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2", + "socket2 0.6.5", "tracing", "windows-sys 0.61.2", ] @@ -940,12 +1147,28 @@ 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 0.9.5", +] + [[package]] name = "rand" version = "0.10.2" @@ -957,6 +1180,16 @@ dependencies = [ "rand_core 0.10.1", ] +[[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 0.9.5", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -966,6 +1199,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[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 = "rand_core" version = "0.10.1" @@ -999,13 +1241,33 @@ dependencies = [ "bitflags", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "reqwest" version = "0.12.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ - "base64 0.22.1", + "base64", "bytes", "futures-core", "futures-util", @@ -1080,6 +1342,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417" dependencies = [ "rmp", + "serde", + "serde_bytes", ] [[package]] @@ -1088,6 +1352,15 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.4" @@ -1148,12 +1421,43 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.3", +] + [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -1194,6 +1498,17 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "serde_json" version = "1.0.151" @@ -1207,6 +1522,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_stacker" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a" +dependencies = [ + "serde", + "serde_core", + "stacker", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -1246,6 +1572,15 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "slab" version = "0.4.12" @@ -1258,6 +1593,16 @@ version = "1.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "socket2" version = "0.6.5" @@ -1268,12 +1613,35 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "subtle" version = "2.6.1" @@ -1392,7 +1760,7 @@ dependencies = [ "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.6.5", "tokio-macros", "windows-sys 0.61.2", ] @@ -1613,6 +1981,15 @@ 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.127" @@ -1882,6 +2259,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "writeable" version = "0.6.4" @@ -1911,6 +2294,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" diff --git a/Cargo.toml b/Cargo.toml index aa81258..4af483e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,7 @@ version = "0.1.0" anyhow = "1" async-trait = "0.1" chrono = { version = "0.4", features = ["serde"] } -codex-connector = { git = "https://github.com/GameCult/CodexConnector.git", rev = "68fe94b9475823de92ed766a97ea962d48723708" } +model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5" } cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } rmp-serde = "1.3" diff --git a/crates/ghostlight-verse/src/main.rs b/crates/ghostlight-verse/src/main.rs index 9c70d06..29e93fc 100644 --- a/crates/ghostlight-verse/src/main.rs +++ b/crates/ghostlight-verse/src/main.rs @@ -341,6 +341,9 @@ fn lane_fault(error: &ControllerOpenError) -> &'static str { "--key-file is unreadable, empty, or not one run of visible ASCII" } ControllerOpenError::SharedModelPrefix { .. } => "two inference lanes claim one model prefix", + ControllerOpenError::SidecarClaimsConnectorModel { .. } => { + "the SDK sidecar prefix claims a connector model" + } ControllerOpenError::EmptyModelPrefix { .. } => "an inference lane's model prefix is empty", } } diff --git a/crates/ghostlight/Cargo.toml b/crates/ghostlight/Cargo.toml index 7fca500..f366f56 100644 --- a/crates/ghostlight/Cargo.toml +++ b/crates/ghostlight/Cargo.toml @@ -7,7 +7,7 @@ license.workspace = true [dependencies] async-trait.workspace = true chrono.workspace = true -codex-connector.workspace = true +model-connector.workspace = true cultcache-rs.workspace = true ghostlight-persona-projection = { path = "../ghostlight-persona-projection" } reqwest.workspace = true diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 97d7edd..19df3df 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -31,11 +31,12 @@ use crate::{ }; use async_trait::async_trait; use chrono::Utc; -use codex_connector::{ - CodexConnectorClient, CodexConnectorClientError, CodexInputItem, CodexProviderRequest, - CodexRefusal, CodexToolChoice, CodexToolDefinition, CodexTransportDisposition, - CodexTransportEventPayload, CodexTransportInvocation, CodexTransportOutcome, - provider_request_sha256, +use model_connector::{ + ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest, ReasoningEffort, + Refusal, + ToolChoice, ToolDefinition, TransportDisposition, TransportEventPayload, TransportInvocation, + TransportResult, + TransportOutcome, provider_request_sha256, }; use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; use ghostlight_persona_projection::{ @@ -78,11 +79,11 @@ pub(super) const CELL_TOOL_STEP_BUDGET: usize = 2; /// carried by tool identity, never by a model-written argument. const HANDLE_SEPARATOR: &str = "__"; const PERSONA_WORD_BUDGET: usize = 180; -const CONTROLLER_WORK_ROW: &str = "controller_work.v18"; +const CONTROLLER_WORK_ROW: &str = "controller_work.v19"; /// The `controller-work` state slot's schema. `pub` so a deploy recipe (or a /// test pinning one) can check /// itself against this constant instead of hand-copying the version number. -pub const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v18"; +pub const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v19"; /// The Interpreter's byte-span capture tool. It is not the generated `speak` /// affordance tool: one captures an utterance out of preserved prose, the other @@ -124,7 +125,7 @@ pub enum InferencePurpose { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct InferenceRequest { purpose: InferencePurpose, - provider: CodexProviderRequest, + provider: ProviderRequest, } impl InferenceRequest { @@ -141,7 +142,7 @@ impl InferenceRequest { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct PreparedInference { pub purpose: InferencePurpose, - pub(super) invocation: CodexTransportInvocation, + pub(super) invocation: TransportInvocation, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -253,6 +254,28 @@ pub enum InferenceFaultClass { /// A recording port refused the call because it could pass the run's /// token cap. Nothing was sent; the run stops and does not retry. BudgetExhausted, + /// The connector does not allow the requested model. Terminal: the lane's + /// model name is wrong for this connector. + ModelNotAllowed, + /// The requested output allowance exceeds the connector's bound. + OutputBound, + /// The request is larger than the connector will carry. + PayloadBound, + /// The connector found another provider's reasoning state in the request. + ForeignReasoningState, + /// The provider is refusing requests until its own window resets. + ProviderRejected, + /// The provider answered that the request is too frequent. + RateLimited, + /// The provider could not be reached or answered with an outage. + Unavailable, + /// The provider judged the request itself invalid. Terminal. + InvalidRequest, + /// The provider rejected the connector's credential. Terminal. + Authentication, + /// The provider failed in a way it did not type, or its result could not + /// be carried. Terminal. + ProviderFailed, Unclassified, } @@ -340,7 +363,7 @@ impl InferenceFault { } /// A call id the connector's own validators would refuse cannot be persisted: -/// the evaluator rebuilds these into `CodexInputItem`s that `validate()` will +/// the evaluator rebuilds these into `InputItem`s that `validate()` will /// see again. Both the local and SDK ports police a provider reply against /// this one rule, so there is one copy rather than two that can drift. pub(super) fn call_id_is_valid(call_id: &str) -> bool { @@ -416,16 +439,17 @@ impl TracingInferencePort { out.push_str("-- input --\n"); for item in &request.input { match item { - CodexInputItem::UserText { text } => out.push_str(&format!("[user]\n{text}\n")), - CodexInputItem::AssistantText { text } => { + InputItem::UserText { text } => out.push_str(&format!("[user]\n{text}\n")), + InputItem::AssistantText { text } => { out.push_str(&format!("[assistant]\n{text}\n")); } - CodexInputItem::ToolCall { + InputItem::ToolCall { name, arguments, .. } => out.push_str(&format!("[tool call {name}]\n{arguments}\n")), - CodexInputItem::ToolResult { output, .. } => { + InputItem::ToolResult { output, .. } => { out.push_str(&format!("[tool result]\n{output}\n")); } + InputItem::ReasoningState { .. } => out.push_str("[reasoning state]\n"), } } if !request.tools.is_empty() { @@ -501,7 +525,7 @@ impl PreparedInference { serde_json::to_vec(&request) .map_err(|_| InferenceFault::new("an inference request could not be serialized"))?; let purpose = request.purpose; - let invocation = CodexTransportInvocation::new( + let invocation = TransportInvocation::new( caller_runtime_id, expires_at_unix_ms, Sha256::digest(request_bytes).into(), @@ -515,16 +539,20 @@ impl PreparedInference { } } -/// Production lowering to CodexConnector. There is deliberately no retry, -/// fallback model, output repair, or stage registry here; transport failure is -/// returned to the owning controller flow with its pending evidence intact. +/// Production lowering to claude-connector over the model-connector v4 +/// contract. The port is one shot: it makes no retry, fallback model or output +/// repair. Whether a fault may be tried again is the fault's own disposition, +/// derived here from the typed refusal or failure kind and never from a +/// transport string; the owning flow decides when, and a run's token cap bounds +/// it. This is the only code that reads the connector key or speaks to the +/// connector. #[derive(Clone)] -struct CodexConnectorInferencePort { - client: CodexConnectorClient, +struct ConnectorInferencePort { + client: ConnectorClient, caller_runtime_id: String, } -impl CodexConnectorInferencePort { +impl ConnectorInferencePort { fn new( endpoint: SocketAddr, connection_key: String, @@ -533,16 +561,16 @@ impl CodexConnectorInferencePort { let caller_runtime_id = caller_runtime_id.into(); if caller_runtime_id.trim().is_empty() || caller_runtime_id.trim() != caller_runtime_id { return Err(InferenceFault::new( - "CodexConnector caller runtime must be one exact nonempty identity", + "the connector caller runtime must be one exact nonempty identity", )); } - let client = CodexConnectorClient::new( + let client = ConnectorClient::new( endpoint, connection_key, MAX_CONNECTOR_FRAME_BYTES, Some(RESPONSE_TIMEOUT), ) - .map_err(|_| InferenceFault::new("the CodexConnector client could not be built"))?; + .map_err(|_| InferenceFault::new("the connector client could not be built"))?; Ok(Self { client, caller_runtime_id, @@ -556,14 +584,14 @@ impl CodexConnectorInferencePort { ) -> Result { let bytes = Zeroizing::new( std::fs::read(path.as_ref()) - .map_err(|_| InferenceFault::new("the CodexConnector key file could not be read"))?, + .map_err(|_| InferenceFault::new("the connector key file could not be read"))?, ); let raw = std::str::from_utf8(bytes.as_slice()) - .map_err(|_| InferenceFault::new("the CodexConnector key file is not UTF-8"))?; + .map_err(|_| InferenceFault::new("the connector key file is not UTF-8"))?; let key = raw.trim_end_matches(['\r', '\n']); if key.is_empty() || key.len() != raw.trim().len() { return Err(InferenceFault::new( - "CodexConnector key file is empty or has surrounding whitespace", + "the connector key file is empty or has surrounding whitespace", )); } Self::new(endpoint, key.to_owned(), caller_runtime_id) @@ -575,84 +603,169 @@ impl CodexConnectorInferencePort { "persisted inference caller does not match the configured runtime identity", )); } - let result = self - .client - .execute(&request.invocation) - .map_err(|error| match error { - CodexConnectorClientError::Connection(_) => { - InferenceFault::retryable("the CodexConnector connection failed") - } - CodexConnectorClientError::InvalidConfig - | CodexConnectorClientError::FrameSize - | CodexConnectorClientError::Encoding - | CodexConnectorClientError::Transport(_) => { - InferenceFault::integrity_violation("the CodexConnector transport failed") - } - })?; - let (events, receipt) = match result.disposition { - CodexTransportDisposition::Refused(reason) => { - return Err(match reason { - CodexRefusal::InFlight => { - InferenceFault::retryable("CodexConnector refused request: in flight") - } - CodexRefusal::Capacity => { - InferenceFault::retryable("CodexConnector refused request: at capacity") - } - CodexRefusal::Expired => { - InferenceFault::new("CodexConnector refused request: expired") - } - CodexRefusal::Indeterminate => { - InferenceFault::new("CodexConnector refused request: indeterminate") - } - CodexRefusal::IdentitySubstitution => InferenceFault::integrity_violation( - "CodexConnector refused request: identity substitution", - ), - CodexRefusal::ProviderDigestSubstitution => InferenceFault::integrity_violation( - "CodexConnector refused request: provider digest substitution", - ), - CodexRefusal::Policy => { - InferenceFault::integrity_violation("CodexConnector refused request: policy") - } - CodexRefusal::ReplayConflict => InferenceFault::integrity_violation( - "CodexConnector refused request: replay conflict", - ), - CodexRefusal::Malformed => InferenceFault::integrity_violation( - "CodexConnector refused request: malformed", - ), - }); - } - CodexTransportDisposition::Transported { events, receipt } => (events, receipt), - }; - if let CodexTransportOutcome::Failed { .. } = &receipt.outcome { - return Err(InferenceFault::new("the Codex provider reported a failed outcome")); + lift_result( + self.client + .execute(&request.invocation) + .map_err(client_fault)?, + ) + } +} + +/// What a connector result becomes: events and reported usage, or the typed +/// fault its refusal or failure kind names. +fn lift_result(result: TransportResult) -> Result { + let (events, receipt) = match result.disposition { + TransportDisposition::Refused(reason) => return Err(refusal_fault(reason)), + TransportDisposition::Transported { events, receipt } => (events, receipt), + }; + let usage = match &receipt.outcome { + TransportOutcome::Completed { usage, .. } => TokenUsage { + // The whole prompt, cache traffic included, as `TokenUsage` + // defines it; the provider counts cache reads and writes apart + // from plain input. + prompt: usage + .input_tokens + .saturating_add(usage.cache_read_tokens) + .saturating_add(usage.cache_write_tokens), + completion: usage.output_tokens, + cached_prompt: Some(usage.cache_read_tokens), + }, + TransportOutcome::Failed { kind, message, .. } => { + // The provider's own words go to the operator log, never into + // the fault: a fault's detail is fixed text. + tracing::warn!(kind = ?kind, message = %message, "the connector reported a failed outcome"); + return Err(failure_fault(*kind)); } - let events = events - .into_iter() - .map(|event| match event.payload { - CodexTransportEventPayload::TextDelta { text } => InferenceEvent::Text(text), - CodexTransportEventPayload::ToolCall { - call_id, - name, - arguments, - } => InferenceEvent::ToolCall { - call_id, - name, - arguments, - }, - }) - .collect(); - let receipt_bytes = rmp_serde::to_vec_named(&receipt) - .map_err(|_| InferenceFault::new("the CodexConnector receipt could not be encoded"))?; - Ok(InferenceOutput { - events, - receipt_digest: format!("sha256:{:x}", Sha256::digest(&receipt_bytes)), - usage: None, + }; + // A reasoning block is opaque and Ghostlight replays no provider + // state, so only text and tool calls become events. + let events = events + .into_iter() + .filter_map(|event| match event.payload { + TransportEventPayload::TextDelta { text } => Some(InferenceEvent::Text(text)), + TransportEventPayload::ToolCall { + call_id, + name, + arguments, + } => Some(InferenceEvent::ToolCall { + call_id, + name, + arguments, + }), + TransportEventPayload::ReasoningState { .. } => None, }) + .collect(); + let receipt_bytes = rmp_serde::to_vec_named(&receipt) + .map_err(|_| InferenceFault::new("the connector receipt could not be encoded"))?; + Ok(InferenceOutput { + events, + receipt_digest: format!("sha256:{:x}", Sha256::digest(&receipt_bytes)), + usage: Some(usage), + }) +} + +/// A client-side failure. A connection that closed, reset, timed out or never +/// opened is retryable: a connector replays a completed request by its id, so +/// asking again cannot double-spend. Everything else means the exchange itself +/// is wrong. +fn client_fault(error: ConnectorClientError) -> InferenceFault { + use std::io::ErrorKind; + match error { + ConnectorClientError::Connection(io) => match io.kind() { + ErrorKind::TimedOut | ErrorKind::WouldBlock => { + InferenceFault::retryable("the connector did not answer in time") + .classed(InferenceFaultClass::Timeout) + } + ErrorKind::UnexpectedEof + | ErrorKind::ConnectionReset + | ErrorKind::ConnectionAborted + | ErrorKind::BrokenPipe => { + InferenceFault::retryable("the connector closed the connection before a reply") + .classed(InferenceFaultClass::NoResponse) + } + _ => InferenceFault::retryable("the connector connection failed") + .classed(InferenceFaultClass::Connect), + }, + ConnectorClientError::InvalidConfig + | ConnectorClientError::FrameSize + | ConnectorClientError::RequestIdTooLong + | ConnectorClientError::Transport(_) => { + InferenceFault::integrity_violation("the connector transport failed") + } + } +} + +/// One fault class per refusal the connector can name. Capacity and in-flight +/// are the connector asking to be tried later. The identity, digest, replay +/// and framing refusals mean the exchange is not what it claims. A model, size +/// or provider refusal is final for this request and stays visible: it is +/// recoverable by an operator, never retried, and not an integrity breach. +fn refusal_fault(reason: Refusal) -> InferenceFault { + match reason { + Refusal::InFlight => InferenceFault::retryable("the connector refused the request: in flight"), + Refusal::Capacity => InferenceFault::retryable("the connector refused the request: at capacity"), + Refusal::Expired => InferenceFault::new("the connector refused the request: expired"), + Refusal::Indeterminate => InferenceFault::new("the connector refused the request: indeterminate"), + Refusal::IdentitySubstitution => InferenceFault::integrity_violation( + "the connector refused the request: identity substitution", + ), + Refusal::ProviderDigestSubstitution => InferenceFault::integrity_violation( + "the connector refused the request: provider digest substitution", + ), + Refusal::ReplayConflict => InferenceFault::integrity_violation( + "the connector refused the request: replay conflict", + ), + Refusal::Malformed => { + InferenceFault::integrity_violation("the connector refused the request: malformed") + } + Refusal::ForeignReasoningState => InferenceFault::integrity_violation( + "the connector refused the request: foreign reasoning state", + ) + .classed(InferenceFaultClass::ForeignReasoningState), + Refusal::ModelNotAllowed => { + InferenceFault::new("the connector does not allow the requested model") + .classed(InferenceFaultClass::ModelNotAllowed) + } + Refusal::OutputBound => { + InferenceFault::new("the requested output exceeds the connector's bound") + .classed(InferenceFaultClass::OutputBound) + } + Refusal::PayloadBound => { + InferenceFault::new("the request exceeds the connector's payload bound") + .classed(InferenceFaultClass::PayloadBound) + } + Refusal::ProviderRejected => { + InferenceFault::new("the provider is refusing requests right now") + .classed(InferenceFaultClass::ProviderRejected) + } + } +} + +/// A provider failure outcome by its typed kind. Rate limits, an unavailable +/// provider and a provider timeout clear with time and are retryable. An +/// invalid request, a failed credential or a provider fault will answer the +/// same way again, so they are terminal. +fn failure_fault(kind: FailureKind) -> InferenceFault { + match kind { + FailureKind::RateLimited => InferenceFault::retryable("the provider rate-limited the request") + .classed(InferenceFaultClass::RateLimited), + FailureKind::Unavailable => InferenceFault::retryable("the provider is unavailable") + .classed(InferenceFaultClass::Unavailable), + FailureKind::Timeout => InferenceFault::retryable("the provider timed out") + .classed(InferenceFaultClass::Timeout), + FailureKind::InvalidRequest => InferenceFault::new("the provider rejected the request as invalid") + .classed(InferenceFaultClass::InvalidRequest), + FailureKind::Authentication => InferenceFault::new("the provider rejected the connector's credential") + .classed(InferenceFaultClass::Authentication), + FailureKind::ResultSize | FailureKind::Provider => { + InferenceFault::new("the provider reported a failed outcome") + .classed(InferenceFaultClass::ProviderFailed) + } } } #[async_trait] -impl InferencePort for CodexConnectorInferencePort { +impl InferencePort for ConnectorInferencePort { fn prepare(&self, request: InferenceRequest) -> Result { PreparedInference::prepare( &self.caller_runtime_id, @@ -665,7 +778,7 @@ impl InferencePort for CodexConnectorInferencePort { let port = self.clone(); tokio::task::spawn_blocking(move || port.execute(request)) .await - .map_err(|_| InferenceFault::new("the CodexConnector worker task failed"))? + .map_err(|_| InferenceFault::new("the connector worker task failed"))? } } @@ -1712,14 +1825,12 @@ fn prose_request_shape_is_valid(request: &PreparedInference) -> bool { provider.input.len() == 1 && matches!( provider.input.first(), - Some(CodexInputItem::UserText { .. }) + Some(InputItem::UserText { .. }) ) && provider.tools.is_empty() - && provider.tool_choice == CodexToolChoice::Auto + && provider.tool_choice == ToolChoice::Auto && !provider.parallel_tool_calls - && provider.output_format_name.is_none() && provider.output_schema_json.is_none() - && provider.previous_response_id.is_none() } fn persona_request_shape_is_valid(request: &PreparedInference) -> bool { @@ -2552,7 +2663,7 @@ impl ControllerModels { pub enum ControllerOpenError { #[error("controller model IDs must be exact nonempty identifiers without whitespace")] InvalidModels, - #[error("CodexConnector controller transport could not open: {0}")] + #[error("the connector transport could not open: {0}")] Connector(#[from] InferenceFault), #[error("controller work journal could not open: {0}")] WorkStore(String), @@ -2566,13 +2677,15 @@ pub enum ControllerOpenError { HostedEndpointNotHttps, #[error("the hosted inference key file is unreadable, empty, or is not one run of visible ASCII")] HostedKeyUnreadable, + #[error("the SDK sidecar prefix claims the connector model `{model}`")] + SidecarClaimsConnectorModel { model: String }, #[error("two inference transports both claim model prefix `{prefix}`")] SharedModelPrefix { prefix: String }, #[error("the {transport} inference transport's model prefix must not be empty")] EmptyModelPrefix { transport: &'static str }, } -/// Everything the CodexConnector transport needs to open, gathered so +/// Everything the connector transport needs to open, gathered so /// `ControllerRunner::open` takes a port rather than building one. pub struct ConnectorBinding { pub endpoint: SocketAddr, @@ -2580,6 +2693,13 @@ pub struct ConnectorBinding { pub caller_runtime_id: String, } +/// Whether a model name is one claude-connector serves: its allow list is the +/// `claude--5-5` family. The connector owns the list; this reads only the +/// naming shape so an overlapping sidecar prefix is refused at open. +fn names_connector_model(model: &str) -> bool { + model.starts_with("claude-") && model.ends_with("-5-5") +} + /// Builds the one port every lane shares. A lane whose model no configured /// backend claims fails here, at open, rather than at its first tick. `models` /// is every model that must route, not just `ControllerModels`'s own fields, @@ -2593,7 +2713,7 @@ pub fn open_inference( models: &[&str], ) -> Result, ControllerOpenError> { let connector: Option> = match connector { - Some(binding) => Some(Arc::new(CodexConnectorInferencePort::from_secret_file( + Some(binding) => Some(Arc::new(ConnectorInferencePort::from_secret_file( binding.endpoint, binding.key_path, binding.caller_runtime_id, @@ -2657,6 +2777,16 @@ pub fn open_inference( prefix: pair[0].to_owned(), }); } + if connector.is_some() && sdk.is_some() { + if let Some(model) = models + .iter() + .find(|model| names_connector_model(model) && model.starts_with(&sdk_model_prefix)) + { + return Err(ControllerOpenError::SidecarClaimsConnectorModel { + model: (*model).to_owned(), + }); + } + } let routed = RoutedInferencePort::new(connector, sdk, sdk_model_prefix, claims); for &model in models { if routed.route(model).is_none() { @@ -5627,7 +5757,7 @@ pub(super) fn tool_decode_need(name: &str, arguments: &str, detail: &str) -> Con } enum InterpreterLoopEvaluation { - Continue { conversation: Vec }, + Continue { conversation: Vec }, Complete { capture: NarrativeCapture }, } @@ -5811,7 +5941,7 @@ fn evaluate_interpreter_loop( prompt: &str, completed: &[InferenceOutput], ) -> Result { - let mut conversation = vec![CodexInputItem::UserText { + let mut conversation = vec![InputItem::UserText { text: prompt.to_owned(), }]; let mut fold = InterpreterFold::new(source.clone()); @@ -5831,7 +5961,7 @@ fn evaluate_interpreter_loop( match event { InferenceEvent::Text(text) => { if !text.is_empty() { - conversation.push(CodexInputItem::AssistantText { text: text.clone() }); + conversation.push(InputItem::AssistantText { text: text.clone() }); } } InferenceEvent::ToolCall { @@ -5840,13 +5970,13 @@ fn evaluate_interpreter_loop( arguments, } => { called_tool = true; - conversation.push(CodexInputItem::ToolCall { + conversation.push(InputItem::ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone(), }); let result = interpreter_tool_result(&mut fold, name, arguments); - conversation.push(CodexInputItem::ToolResult { + conversation.push(InputItem::ToolResult { call_id: call_id.clone(), output: result, }); @@ -5920,7 +6050,7 @@ fn handle_prefix(handle: usize) -> String { /// decided by which tool was called rather than by an argument the model writes. /// A shared tool with a `subject` argument is the forgeable shape: it would let /// one constituent's turn propose for another. -fn cell_catalog_tools(constituents: &[ConstituentWork]) -> Vec { +fn cell_catalog_tools(constituents: &[ConstituentWork]) -> Vec { constituents .iter() .enumerate() @@ -5962,7 +6092,7 @@ struct GroupedCapture { } enum GroupedLoopEvaluation { - Continue { conversation: Vec }, + Continue { conversation: Vec }, Complete { capture: GroupedCapture }, } @@ -6136,7 +6266,7 @@ fn evaluate_grouped_loop( constituents: &[ConstituentWork], completed: &[InferenceOutput], ) -> Result { - let mut conversation = vec![CodexInputItem::UserText { + let mut conversation = vec![InputItem::UserText { text: prompt.to_owned(), }]; let mut fold = GroupedFold::new(); @@ -6154,7 +6284,7 @@ fn evaluate_grouped_loop( match event { InferenceEvent::Text(text) => { if !text.is_empty() { - conversation.push(CodexInputItem::AssistantText { text: text.clone() }); + conversation.push(InputItem::AssistantText { text: text.clone() }); } } InferenceEvent::ToolCall { @@ -6163,13 +6293,13 @@ fn evaluate_grouped_loop( arguments, } => { called_tool = true; - conversation.push(CodexInputItem::ToolCall { + conversation.push(InputItem::ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone(), }); let result = grouped_tool_result(constituents, &mut fold, name, arguments)?; - conversation.push(CodexInputItem::ToolResult { + conversation.push(InputItem::ToolResult { call_id: call_id.clone(), output: result, }); @@ -6245,7 +6375,7 @@ fn grouped_request( round: usize, model: &str, constituents: &[ConstituentWork], - input: Vec, + input: Vec, ) -> Result { tool_request( command_id, @@ -6281,7 +6411,7 @@ fn grouped_pending(checkpoint: GroupedCheckpoint, reason: ControllerPendingReaso } } enum OperationalLoopEvaluation { - Continue { conversation: Vec }, + Continue { conversation: Vec }, Complete { capture: OperationalCapture }, } @@ -6429,7 +6559,7 @@ fn evaluate_operational_loop( granted: &[AffordanceSnapshot], completed: &[InferenceOutput], ) -> Result { - let mut conversation = vec![CodexInputItem::UserText { + let mut conversation = vec![InputItem::UserText { text: prompt.to_owned(), }]; let mut fold = OperationalFold::new(); @@ -6450,7 +6580,7 @@ fn evaluate_operational_loop( match event { InferenceEvent::Text(text) => { if !text.is_empty() { - conversation.push(CodexInputItem::AssistantText { text: text.clone() }); + conversation.push(InputItem::AssistantText { text: text.clone() }); } } InferenceEvent::ToolCall { @@ -6459,13 +6589,13 @@ fn evaluate_operational_loop( arguments, } => { called_tool = true; - conversation.push(CodexInputItem::ToolCall { + conversation.push(InputItem::ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone(), }); let result = operational_tool_result(granted, &mut fold, name, arguments)?; - conversation.push(CodexInputItem::ToolResult { + conversation.push(InputItem::ToolResult { call_id: call_id.clone(), output: result, }); @@ -6643,8 +6773,8 @@ fn persona_request( // constructor. Its only model-visible input is the dedicated natural-prose // prompt plus the smallest nonempty instruction required by the provider // transport contract. - let input = vec![CodexInputItem::UserText { text: prompt }]; - let mut provider = CodexProviderRequest::new( + let input = vec![InputItem::UserText { text: prompt }]; + let mut provider = ProviderRequest::new( provider_request_id( command_id, InferencePurpose::Persona, @@ -6655,16 +6785,15 @@ fn persona_request( conversation_id(command_id, InferencePurpose::Persona, 0)?, model, PERSONA_PROVIDER_INSTRUCTIONS, + 1_200, ); provider.input = input; - provider.reasoning_effort = Some("low".into()); + provider.reasoning_effort = Some(ReasoningEffort::Low); provider.tools = Vec::new(); - provider.tool_choice = CodexToolChoice::Auto; + provider.tool_choice = ToolChoice::Auto; provider.parallel_tool_calls = false; - provider.output_format_name = None; provider.output_schema_json = None; - provider.max_output_tokens = Some(1_200); - Ok(InferenceRequest { + Ok(InferenceRequest { purpose: InferencePurpose::Persona, provider, }) @@ -6678,26 +6807,24 @@ fn text_request( prompt: String, max_output_tokens: u32, ) -> Result { - let input = vec![CodexInputItem::UserText { text: prompt }]; + let input = vec![InputItem::UserText { text: prompt }]; let request = provider_request_id(command_id, purpose, 0, instructions, &input)?; let conversation = conversation_id(command_id, purpose, 0)?; - let mut provider = CodexProviderRequest::new(request, conversation, model, instructions); + let mut provider = ProviderRequest::new(request, conversation, model, instructions, max_output_tokens); provider.input = input; - provider.reasoning_effort = Some("low".into()); + provider.reasoning_effort = Some(ReasoningEffort::Low); provider.tools = Vec::new(); - provider.tool_choice = CodexToolChoice::Auto; + provider.tool_choice = ToolChoice::Auto; provider.parallel_tool_calls = false; - provider.output_format_name = None; provider.output_schema_json = None; - provider.max_output_tokens = Some(max_output_tokens); - Ok(InferenceRequest { purpose, provider }) + Ok(InferenceRequest { purpose, provider }) } fn interpreter_request( command_id: CommandId, round: usize, model: &str, - input: Vec, + input: Vec, ) -> Result { tool_request( command_id, @@ -6716,7 +6843,7 @@ fn operational_request( round: usize, model: &str, granted: &[AffordanceSnapshot], - input: Vec, + input: Vec, ) -> Result { tool_request( command_id, @@ -6752,28 +6879,27 @@ pub(super) fn tool_request( purpose: InferencePurpose, model: &str, instructions: &str, - input: Vec, - tools: Vec, + input: Vec, + tools: Vec, shape: RequestShape, ) -> Result { - let mut provider = CodexProviderRequest::new( + let mut provider = ProviderRequest::new( provider_request_id(command_id, purpose, round, instructions, &input)?, conversation_id(command_id, purpose, round)?, model, instructions, + shape.max_output_tokens, ); provider.input = input; - provider.reasoning_effort = Some("medium".into()); + provider.reasoning_effort = Some(ReasoningEffort::Medium); provider.tools = tools; - provider.tool_choice = CodexToolChoice::Auto; + provider.tool_choice = ToolChoice::Auto; provider.parallel_tool_calls = shape.parallel_tool_calls; - provider.output_format_name = None; provider.output_schema_json = None; - provider.max_output_tokens = Some(shape.max_output_tokens); - Ok(InferenceRequest { purpose, provider }) + Ok(InferenceRequest { purpose, provider }) } -fn interpreter_tools() -> Vec { +fn interpreter_tools() -> Vec { vec![ tool_schema::tool( INTERPRETER_SPEAK_TOOL, @@ -6846,7 +6972,7 @@ fn interpreter_tools() -> Vec { pub(super) fn catalog_tools( prefix: &str, granted: &[AffordanceSnapshot], -) -> Vec { +) -> Vec { let mut tools = affordance_tools(prefix, granted); tools.push(tool_schema::tool( &format!("{prefix}{RECORD_NEED_TOOL}"), @@ -6874,7 +7000,7 @@ pub(super) fn catalog_tools( pub(super) fn affordance_tools( prefix: &str, granted: &[AffordanceSnapshot], -) -> Vec { +) -> Vec { granted .iter() .map(|entry| { @@ -7079,7 +7205,7 @@ pub(super) fn provider_request_id( purpose: InferencePurpose, round: usize, instructions: &str, - input: &[CodexInputItem], + input: &[InputItem], ) -> Result { let content = request_content_digest(instructions, input)?; Ok(format!( @@ -7091,7 +7217,7 @@ pub(super) fn provider_request_id( fn request_content_digest( instructions: &str, - input: &[CodexInputItem], + input: &[InputItem], ) -> Result { let bytes = serde_json::to_vec(&(instructions, input)) .map_err(|error| ControllerError::Serialization(error.to_string()))?; @@ -7141,13 +7267,13 @@ mod tests { let not_utf8 = directory.path().join(CANARY); std::fs::write(¬_utf8, [0xff_u8, 0xfe]).unwrap(); let faults = [ - CodexConnectorInferencePort::from_secret_file(endpoint, directory.path().join("absent").join(CANARY), "runtime") + ConnectorInferencePort::from_secret_file(endpoint, directory.path().join("absent").join(CANARY), "runtime") .err() .expect("a missing key file opened"), - CodexConnectorInferencePort::from_secret_file(endpoint, ¬_utf8, "runtime") + ConnectorInferencePort::from_secret_file(endpoint, ¬_utf8, "runtime") .err() .expect("a key file that is not UTF-8 opened"), - CodexConnectorInferencePort::new(endpoint, "key".into(), format!(" {CANARY} ")) + ConnectorInferencePort::new(endpoint, "key".into(), format!(" {CANARY} ")) .err() .expect("a runtime identity with whitespace opened"), ]; @@ -7167,6 +7293,360 @@ mod tests { super::super::tool_schema::assert_strict(&schema, &tool.name); } } + + // The connector port on model-connector v4. The wire itself is the + // upstream client's; these pin what Ghostlight decides about what comes + // back: which refusal is retryable, which failure is terminal, and what + // usage and log text survive. + + use model_connector::{ + CacheRetention, StopReason, TransportEvent, TransportReceipt, Usage, + }; + + fn receipt(outcome: TransportOutcome) -> TransportReceipt { + TransportReceipt { + schema_id: "gamecult.model.transport_receipt.v4".into(), + request_id: "request-1".into(), + caller_runtime_id: "runtime".into(), + native_request_sha256: [1; 32], + provider_request_sha256: [2; 32], + model: "claude-haiku-5-5".into(), + provider: "anthropic-messages".into(), + foreign_reasoning_dropped: 0, + outcome, + } + } + + fn result_of(disposition: TransportDisposition) -> TransportResult { + TransportResult { + schema_id: "gamecult.model.transport_result.v4".into(), + request_id: "request-1".into(), + caller_runtime_id: "runtime".into(), + disposition, + } + } + + fn refused_with(reason: Refusal) -> InferenceFault { + lift_result(result_of(TransportDisposition::Refused(reason))) + .err() + .expect("a refusal produced an output") + } + + fn failed_with(kind: FailureKind) -> InferenceFault { + lift_result(result_of(TransportDisposition::Transported { + events: Vec::new(), + receipt: Box::new(receipt(TransportOutcome::Failed { + kind, + message: "provider words".into(), + usage: None, + })), + })) + .err() + .expect("a failed outcome produced an output") + } + + /// One test per v4 refusal: what the flow may do, and the class the play + /// card names. + macro_rules! refusal_maps_to { + ($test:ident, $variant:ident, $disposition:ident, $class:expr) => { + #[test] + fn $test() { + let fault = refused_with(Refusal::$variant); + assert_eq!( + fault.disposition(), + InferenceFaultDisposition::$disposition, + "{fault:?}" + ); + assert_eq!(fault.class(), $class, "{fault:?}"); + } + }; + } + refusal_maps_to!(refusal_in_flight_is_retryable, InFlight, Retryable, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_capacity_is_retryable, Capacity, Retryable, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_expired_needs_recovery, Expired, RecoveryRequired, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_indeterminate_needs_recovery, Indeterminate, RecoveryRequired, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_identity_substitution_is_integrity, IdentitySubstitution, IntegrityViolation, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_digest_substitution_is_integrity, ProviderDigestSubstitution, IntegrityViolation, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_replay_conflict_is_integrity, ReplayConflict, IntegrityViolation, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_malformed_is_integrity, Malformed, IntegrityViolation, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_model_not_allowed_is_terminal_and_named, ModelNotAllowed, RecoveryRequired, InferenceFaultClass::ModelNotAllowed); + refusal_maps_to!(refusal_output_bound_is_terminal_and_named, OutputBound, RecoveryRequired, InferenceFaultClass::OutputBound); + refusal_maps_to!(refusal_payload_bound_is_terminal_and_named, PayloadBound, RecoveryRequired, InferenceFaultClass::PayloadBound); + refusal_maps_to!(refusal_foreign_reasoning_state_is_integrity_and_named, ForeignReasoningState, IntegrityViolation, InferenceFaultClass::ForeignReasoningState); + refusal_maps_to!(refusal_provider_rejected_is_terminal_and_named, ProviderRejected, RecoveryRequired, InferenceFaultClass::ProviderRejected); + + macro_rules! failure_maps_to { + ($test:ident, $kind:ident, $disposition:ident, $class:expr) => { + #[test] + fn $test() { + let fault = failed_with(FailureKind::$kind); + assert_eq!( + fault.disposition(), + InferenceFaultDisposition::$disposition, + "{fault:?}" + ); + assert_eq!(fault.class(), $class, "{fault:?}"); + } + }; + } + failure_maps_to!(failure_rate_limited_is_retryable, RateLimited, Retryable, InferenceFaultClass::RateLimited); + failure_maps_to!(failure_unavailable_is_retryable, Unavailable, Retryable, InferenceFaultClass::Unavailable); + failure_maps_to!(failure_timeout_is_retryable, Timeout, Retryable, InferenceFaultClass::Timeout); + failure_maps_to!(failure_invalid_request_is_terminal, InvalidRequest, RecoveryRequired, InferenceFaultClass::InvalidRequest); + failure_maps_to!(failure_authentication_is_terminal, Authentication, RecoveryRequired, InferenceFaultClass::Authentication); + failure_maps_to!(failure_provider_is_terminal, Provider, RecoveryRequired, InferenceFaultClass::ProviderFailed); + failure_maps_to!(failure_result_size_is_terminal, ResultSize, RecoveryRequired, InferenceFaultClass::ProviderFailed); + + /// Collects the events a closure logs, with their fields rendered. + struct LogCapture(Arc>>); + + impl tracing::Subscriber for LogCapture { + fn enabled(&self, _: &tracing::Metadata<'_>) -> bool { + true + } + fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} + fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} + fn event(&self, event: &tracing::Event<'_>) { + struct Fields(String); + impl tracing::field::Visit for Fields { + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { + self.0.push_str(&format!("{}={value:?} ", field.name())); + } + } + let mut fields = Fields(String::new()); + event.record(&mut fields); + self.0.lock().unwrap().push(fields.0); + } + fn enter(&self, _: &tracing::span::Id) {} + fn exit(&self, _: &tracing::span::Id) {} + } + + /// An invalid request is terminal and the provider's own message reaches + /// the operator log, never the fault. + #[test] + fn a_failed_outcome_keeps_the_providers_message_in_the_log_and_out_of_the_fault() { + let lines = Arc::new(Mutex::new(Vec::new())); + let fault = tracing::subscriber::with_default(LogCapture(Arc::clone(&lines)), || { + failed_with(FailureKind::InvalidRequest) + }); + let rendered = format!("{fault} | {fault:?}"); + assert!(!rendered.contains("provider words"), "{rendered}"); + let lines = lines.lock().unwrap(); + assert!( + lines + .iter() + .any(|line| line.contains("provider words") && line.contains("InvalidRequest")), + "the operator log lacks the provider's message: {lines:?}" + ); + } + + /// A completed outcome reports the provider's own counts, never None; the + /// prompt is the whole prompt, cache traffic included. + #[test] + fn a_completed_outcome_reports_the_scripted_usage() { + let output = lift_result(result_of(TransportDisposition::Transported { + events: vec![ + TransportEvent { + sequence: 0, + payload: TransportEventPayload::TextDelta { text: "ok".into() }, + }, + TransportEvent { + sequence: 1, + payload: TransportEventPayload::ReasoningState { state: vec![9] }, + }, + TransportEvent { + sequence: 2, + payload: TransportEventPayload::ToolCall { + call_id: "call-1".into(), + name: "note".into(), + arguments: "{}".into(), + }, + }, + ], + receipt: Box::new(receipt(TransportOutcome::Completed { + provider_response_id: None, + stop_reason: StopReason::ToolUse, + usage: Usage { + input_tokens: 11, + cache_read_tokens: 5, + cache_write_tokens: 3, + output_tokens: 7, + reasoning_tokens: Some(2), + }, + })), + })) + .expect("a completed outcome lifts"); + assert_eq!( + output.usage, + Some(TokenUsage { + prompt: 19, + completion: 7, + cached_prompt: Some(5), + }) + ); + assert_eq!( + output.events, + vec![ + InferenceEvent::Text("ok".into()), + InferenceEvent::ToolCall { + call_id: "call-1".into(), + name: "note".into(), + arguments: "{}".into(), + }, + ], + "reasoning state is opaque and never becomes an event" + ); + assert!(output.receipt_digest.starts_with("sha256:")); + } + + /// A connection that closes before a reply is retryable and named, and a + /// transport that is wrong in itself is an integrity violation. + #[test] + fn a_closed_connection_is_retryable_and_a_broken_exchange_is_not() { + use std::io::{Error, ErrorKind}; + for (kind, class) in [ + (ErrorKind::UnexpectedEof, InferenceFaultClass::NoResponse), + (ErrorKind::ConnectionReset, InferenceFaultClass::NoResponse), + (ErrorKind::TimedOut, InferenceFaultClass::Timeout), + (ErrorKind::ConnectionRefused, InferenceFaultClass::Connect), + ] { + let fault = client_fault(ConnectorClientError::Connection(Error::from(kind))); + assert_eq!(fault.disposition(), InferenceFaultDisposition::Retryable, "{kind:?}"); + assert_eq!(fault.class(), class, "{kind:?}"); + } + for error in [ + ConnectorClientError::InvalidConfig, + ConnectorClientError::FrameSize, + ConnectorClientError::RequestIdTooLong, + ] { + assert!(client_fault(error).integrity_was_violated()); + } + } + + /// The whole port against a peer that accepts and hangs up: the closed + /// connection is the retryable, named fault, not an integrity breach. + #[tokio::test] + async fn the_port_names_a_peer_that_hangs_up() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let endpoint = listener.local_addr().unwrap(); + let peer = std::thread::spawn(move || drop(listener.accept().unwrap())); + let port = ConnectorInferencePort::new(endpoint, "test-key".into(), "runtime").unwrap(); + let request = persona_request(CommandId::new(), "claude-haiku-5-5", "Speak.".into()).unwrap(); + let prepared = port.prepare(request).unwrap(); + let fault = port.infer(prepared).await.expect_err("a hung-up peer answered"); + peer.join().unwrap(); + assert_eq!(fault.disposition(), InferenceFaultDisposition::Retryable, "{fault:?}"); + assert!( + matches!(fault.class(), InferenceFaultClass::NoResponse | InferenceFaultClass::Connect), + "{fault:?}" + ); + } + + /// v4 requests carry a required output allowance and a typed effort, and + /// name no cache retention Ghostlight never chose. + #[test] + fn every_lane_builds_a_bounded_typed_v4_request() { + let persona = persona_request(CommandId::new(), "claude-haiku-5-5", "Speak.".into()).unwrap(); + assert_eq!(persona.provider.max_output_tokens, 1_200); + assert_eq!(persona.provider.reasoning_effort, Some(ReasoningEffort::Low)); + assert_eq!(persona.provider.cache_retention, None::); + let interpreter = + interpreter_request(CommandId::new(), 0, "claude-haiku-5-5", vec![InputItem::UserText { text: "x".into() }]) + .unwrap(); + assert_eq!(interpreter.provider.max_output_tokens, DECISION_REQUEST_SHAPE.max_output_tokens); + assert_eq!(interpreter.provider.reasoning_effort, Some(ReasoningEffort::Medium)); + assert_eq!(interpreter.provider.tool_choice, ToolChoice::Auto); + } + + /// A tool or output schema is held to strict-grammar limits. model-connector + /// documents none, so: at most 24 optional parameters in a schema (the + /// Messages API strict-tool limit), and at most 16 KiB of schema text, a + /// Ghostlight-chosen ceiling at twice the largest schema sent today (8,055 + /// bytes, measured; no upstream byte figure exists). + const MAX_OPTIONAL_PARAMS: usize = 24; + const MAX_SCHEMA_BYTES: usize = 16_384; + + /// Counts the properties a schema does not list as required, anywhere in it. + fn optional_params(schema: &serde_json::Value) -> usize { + match schema { + serde_json::Value::Object(fields) => { + let own = match fields.get("properties") { + Some(serde_json::Value::Object(properties)) => { + let required: BTreeSet<&str> = fields + .get("required") + .and_then(|value| value.as_array()) + .map(|names| names.iter().filter_map(|name| name.as_str()).collect()) + .unwrap_or_default(); + properties + .keys() + .filter(|name| !required.contains(name.as_str())) + .count() + } + _ => 0, + }; + own + fields.values().map(optional_params).sum::() + } + serde_json::Value::Array(items) => items.iter().map(optional_params).sum(), + _ => 0, + } + } + + fn schema_within_limits(schema_json: &str) -> Result<(), String> { + let schema: serde_json::Value = serde_json::from_str(schema_json).map_err(|e| e.to_string())?; + let optional = optional_params(&schema); + if optional > MAX_OPTIONAL_PARAMS { + return Err(format!("{optional} optional parameters, more than {MAX_OPTIONAL_PARAMS}")); + } + if schema_json.len() > MAX_SCHEMA_BYTES { + return Err(format!("{} bytes, more than {MAX_SCHEMA_BYTES}", schema_json.len())); + } + Ok(()) + } + + #[test] + fn every_schema_ghostlight_sends_fits_the_grammar_limits() { + let opportunity = fixture_opportunity(ControllerMode::OperationalAgent); + let granted = vec![speak_snapshot(opportunity.affordance_ids[0])]; + // The interpreter's capture tools, the operational and grouped action + // catalog (which `actor_tools` projects as well), and the patch + // catalog every authoring lane draws from: elaborator, seed and play. + // No lane sets `output_schema_json` today. + let mut tools = interpreter_tools(); + tools.extend(catalog_tools("", &granted)); + tools.extend(catalog_tools("c0__", &granted)); + tools.extend(crate::patch::patch_tools()); + assert!(tools.len() > 10, "the walk saw only {} tools", tools.len()); + let mut worst = (0, 0); + for tool in &tools { + if let Err(reason) = schema_within_limits(&tool.parameters_json) { + panic!("{}: {reason}", tool.name); + } + let schema: serde_json::Value = serde_json::from_str(&tool.parameters_json).unwrap(); + worst = ( + worst.0.max(optional_params(&schema)), + worst.1.max(tool.parameters_json.len()), + ); + } + eprintln!("schema walk: {} tools, worst (optional, bytes) = {worst:?}", tools.len()); + } + + #[test] + fn a_planted_twenty_fifth_optional_parameter_fails_the_limit() { + let properties = |count: usize| -> String { + let fields: Vec = (0..count).map(|n| format!("\"p{n}\":{{\"type\":\"string\"}}")).collect(); + format!("{{\"type\":\"object\",\"required\":[],\"properties\":{{{}}}}}", fields.join(",")) + }; + assert!(schema_within_limits(&properties(MAX_OPTIONAL_PARAMS)).is_ok()); + assert!(schema_within_limits(&properties(MAX_OPTIONAL_PARAMS + 1)).is_err()); + let oversized = format!( + "{{\"type\":\"object\",\"required\":[],\"properties\":{{\"p\":{{\"type\":\"string\",\"description\":\"{}\"}}}}}}", + "x".repeat(MAX_SCHEMA_BYTES) + ); + assert!(schema_within_limits(&oversized).is_err()); + } use super::*; use crate::elaboration::{ElaboratorSession, EvidenceError, EvidenceQuery, EvidenceReceipt}; use crate::tests::{operations, opportunity_for}; @@ -7447,11 +7927,9 @@ mod tests { assert!(request.provider.validate().is_ok()); assert_eq!(request.provider.instructions, PERSONA_PROVIDER_INSTRUCTIONS); assert!(request.provider.tools.is_empty()); - assert_eq!(request.provider.tool_choice, CodexToolChoice::Auto); + assert_eq!(request.provider.tool_choice, ToolChoice::Auto); assert!(!request.provider.parallel_tool_calls); - assert!(request.provider.output_format_name.is_none()); assert!(request.provider.output_schema_json.is_none()); - assert!(request.provider.previous_response_id.is_none()); assert_eq!(request.provider.input.len(), 1); let encoded = serde_json::to_string(&request.provider) .unwrap() @@ -7874,7 +8352,7 @@ mod tests { } } - /// Every `CodexInputItem::UserText` in a captured request's input, + /// Every `InputItem::UserText` in a captured request's input, /// concatenated: what actually reached the provider, independent of how /// many input items carried it. fn request_text(request: &InferenceRequest) -> String { @@ -7883,7 +8361,7 @@ mod tests { .input .iter() .map(|item| match item { - CodexInputItem::UserText { text } => text.clone(), + InputItem::UserText { text } => text.clone(), _ => String::new(), }) .collect::>() @@ -9846,7 +10324,7 @@ mod tests { command_id, 0, "interpreter-model", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "prompt".into(), }], ) @@ -9855,7 +10333,7 @@ mod tests { command_id, 1, "interpreter-model", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "prompt".into(), }], ) @@ -10234,11 +10712,11 @@ mod tests { } } - fn tool_results(conversation: &[CodexInputItem]) -> Vec { + fn tool_results(conversation: &[InputItem]) -> Vec { conversation .iter() .filter_map(|item| match item { - CodexInputItem::ToolResult { output, .. } => Some(output.clone()), + InputItem::ToolResult { output, .. } => Some(output.clone()), _ => None, }) .collect() @@ -10518,7 +10996,7 @@ mod tests { 0, "claude-opus-5", &granted, - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Hold the bridge.".into(), }], ) @@ -10548,7 +11026,7 @@ mod tests { }]; let command_id = CommandId::new(); let prompt = || { - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Hold the bridge.".into(), }] }; @@ -11610,12 +12088,22 @@ mod tests { } #[tokio::test] - #[ignore = "requires a local model server on GHOSTLIGHT_LOCAL_ENDPOINT"] + #[ignore = "requires a local model server on GHOSTLIGHT_LOCAL_ENDPOINT, or a connector at GHOSTLIGHT_ACCEPTANCE_CONNECTOR with its key as the systemd credential `connector-key`"] async fn real_local_model_cognition_modes_commit_speech() { - let local_endpoint: SocketAddr = std::env::var("GHOSTLIGHT_LOCAL_ENDPOINT") - .expect("GHOSTLIGHT_LOCAL_ENDPOINT is required") - .parse() - .expect("GHOSTLIGHT_LOCAL_ENDPOINT must be a socket address"); + // The connector, when named, replaces the local server: the key reaches + // the process only as the credential file systemd mounts, never as a value. + let connector_endpoint: Option = std::env::var("GHOSTLIGHT_ACCEPTANCE_CONNECTOR") + .ok() + .map(|endpoint| endpoint.parse().expect("GHOSTLIGHT_ACCEPTANCE_CONNECTOR must be a socket address")); + let local_endpoint: Option = match connector_endpoint { + Some(_) => None, + None => Some( + std::env::var("GHOSTLIGHT_LOCAL_ENDPOINT") + .expect("GHOSTLIGHT_LOCAL_ENDPOINT is required") + .parse() + .expect("GHOSTLIGHT_LOCAL_ENDPOINT must be a socket address"), + ), + }; let local_model_prefix = std::env::var("GHOSTLIGHT_LOCAL_MODEL_PREFIX") .unwrap_or_else(|_| DEFAULT_LOCAL_MODEL_PREFIX.to_owned()); let runtime_id = std::env::var("GHOSTLIGHT_ACCEPTANCE_RUNTIME_ID") @@ -11789,18 +12277,21 @@ mod tests { .unwrap(); assert!(matches!(seed_receipt, SubmitReceipt::Applied(_))); - let inference = open_inference( - None, - None, - Some(LocalBinding { - endpoint: local_endpoint, - model_prefix: local_model_prefix, - caller_runtime_id: runtime_id, - }), - None, - &models.each(), - ) - .unwrap(); + let connector = connector_endpoint.map(|endpoint| ConnectorBinding { + endpoint, + key_path: PathBuf::from( + std::env::var_os("CREDENTIALS_DIRECTORY") + .expect("a connector run needs the systemd credential directory"), + ) + .join("connector-key"), + caller_runtime_id: runtime_id.clone(), + }); + let local = local_endpoint.map(|endpoint| LocalBinding { + endpoint, + model_prefix: local_model_prefix, + caller_runtime_id: runtime_id, + }); + let inference = open_inference(connector, None, local, None, &models.each()).unwrap(); let work = open_controller_work(directory.path().join("controller-work.cc")).unwrap(); let runner = ControllerRunner::open(mailbox.clone(), inference, work, models).unwrap(); @@ -12956,7 +13447,7 @@ mod tests { 0, &invocation.invocation.request.model, &session.instructions, - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: agent_prompt.clone(), }], ) @@ -13171,17 +13662,17 @@ mod tests { /// refused at open and not migrated; the same payload under the current /// version opens, so the refusal is the version's. #[tokio::test] - async fn a_controller_work_row_from_v17_is_refused_at_open() { + async fn a_controller_work_row_from_v18_is_refused_at_open() { let checkpoint = refused_checkpoint().await; let directory = tempfile::tempdir().unwrap(); let Err(error) = open_with_raw_row( &directory, - "v17.cc", + "v18.cc", &checkpoint, - "controller_work.v17", - "ghostlight.controller_work.v17", + "controller_work.v18", + "ghostlight.controller_work.v18", ) else { - panic!("a v17 row was accepted by the {CONTROLLER_WORK_ROW} store"); + panic!("a v18 row was accepted by the {CONTROLLER_WORK_ROW} store"); }; assert!(matches!(error, ControllerWorkStoreError::Fault { .. })); open_with_raw_row( @@ -13267,7 +13758,7 @@ mod tests { #[tokio::test] async fn the_catalog_takes_no_lens() { let _: fn() -> String = crate::patch::patch_tool_signatures; - let _: fn() -> Vec = crate::patch::patch_tools; + let _: fn() -> Vec = crate::patch::patch_tools; let (_directory, mailbox, task, commons, _roads) = dead_end_mailbox(only(Lens::Numen), &["The Unwalked Road"]).await; let store = fresh_store(); @@ -13282,7 +13773,7 @@ mod tests { let first = &seen[0].invocation.request; assert_eq!(first.instructions, Lens::Numen.instructions()); assert_eq!(first.tools, crate::patch::patch_tools()); - let Some(CodexInputItem::UserText { text }) = first.input.first() else { + let Some(InputItem::UserText { text }) = first.input.first() else { panic!("the first turn is not the prompt"); }; let tools = text @@ -13441,7 +13932,7 @@ mod tests { /// The first user turn of a prepared request: the session's prompt. fn prompt_of(request: &PreparedInference) -> String { match request.invocation.request.input.first() { - Some(CodexInputItem::UserText { text }) => text.clone(), + Some(InputItem::UserText { text }) => text.clone(), other => panic!("the first turn is not the prompt: {other:?}"), } } diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index 0c2c119..c12b733 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -33,7 +33,7 @@ use super::{ SubjectId, SubjectKind, WorldId, WorldPatch, WorldPhase, WorldSnapshot, }; use async_trait::async_trait; -use codex_connector::CodexInputItem; +use model_connector::InputItem; use serde::{Deserialize, Serialize}; use serde_json::Value; use sha2::{Digest, Sha256}; @@ -349,7 +349,7 @@ pub(super) struct ElaborationCapture { } pub(super) enum ElaborationLoopEvaluation { - Continue { conversation: Vec }, + Continue { conversation: Vec }, Complete { capture: ElaborationCapture }, } @@ -1135,7 +1135,7 @@ pub(super) fn evaluate_elaboration_loop( budget: usize, ) -> Result { check_refusals(refusals, completed.len())?; - let mut conversation = vec![CodexInputItem::UserText { + let mut conversation = vec![InputItem::UserText { text: prompt.to_owned(), }]; let mut fold = DraftFold::default(); @@ -1155,7 +1155,7 @@ pub(super) fn evaluate_elaboration_loop( match event { InferenceEvent::Text(text) => { if !text.is_empty() { - conversation.push(CodexInputItem::AssistantText { text: text.clone() }); + conversation.push(InputItem::AssistantText { text: text.clone() }); } } InferenceEvent::ToolCall { @@ -1164,13 +1164,13 @@ pub(super) fn evaluate_elaboration_loop( arguments, } => { called_tool = true; - conversation.push(CodexInputItem::ToolCall { + conversation.push(InputItem::ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone(), }); let result = fold.apply(name, arguments); - conversation.push(CodexInputItem::ToolResult { + conversation.push(InputItem::ToolResult { call_id: call_id.clone(), output: result, }); @@ -1187,7 +1187,7 @@ pub(super) fn evaluate_elaboration_loop( "a refusal follows a round that submitted nothing".into(), )); } - conversation.push(CodexInputItem::UserText { + conversation.push(InputItem::UserText { text: render_refusal(&refusal.mismatches), }); fold = DraftFold::default(); @@ -1439,7 +1439,7 @@ pub(super) fn elaboration_request( round: usize, model: &str, instructions: &str, - input: Vec, + input: Vec, ) -> Result { tool_request( command_id, @@ -2035,7 +2035,7 @@ fn seed_request( command_id: CommandId, round: usize, model: &str, - input: Vec, + input: Vec, ) -> Result { tool_request( command_id, @@ -2213,7 +2213,7 @@ mod tests { let recomputed: Vec = conversation .iter() .filter_map(|item| match item { - CodexInputItem::ToolResult { output, .. } => Some(output.clone()), + InputItem::ToolResult { output, .. } => Some(output.clone()), _ => None, }) .collect(); @@ -2389,13 +2389,13 @@ mod tests { .unwrap() else { panic!("a refused round finalized instead of reopening"); }; - let CodexInputItem::UserText { text } = conversation.last().unwrap() else { + let InputItem::UserText { text } = conversation.last().unwrap() else { panic!("the refusal is not the next user turn"); }; assert!(text.contains("The world refused the patch you submitted")); assert!(text.contains(&render_mismatch(&Mismatch::NoCanonicalChange))); assert!( - matches!(&conversation[1], CodexInputItem::ToolCall { name, .. } if name == "declare_place"), + matches!(&conversation[1], InputItem::ToolCall { name, .. } if name == "declare_place"), "the refused round's calls left the conversation" ); assert_eq!( diff --git a/crates/ghostlight/src/local_inference.rs b/crates/ghostlight/src/local_inference.rs index fd7cdff..a145da7 100644 --- a/crates/ghostlight/src/local_inference.rs +++ b/crates/ghostlight/src/local_inference.rs @@ -17,7 +17,7 @@ use super::controllers::{ call_id_is_valid, tool_name_is_valid, unix_ms, }; use async_trait::async_trait; -use codex_connector::CodexInputItem; +use model_connector::InputItem; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; @@ -334,9 +334,9 @@ fn lower_request(prepared: &PreparedInference, prefix: &str) -> Result json!({"role": "user", "content": text}), - CodexInputItem::AssistantText { text } => json!({"role": "assistant", "content": text}), - CodexInputItem::ToolCall { + InputItem::UserText { text } => json!({"role": "user", "content": text}), + InputItem::AssistantText { text } => json!({"role": "assistant", "content": text}), + InputItem::ToolCall { call_id, name, arguments, @@ -349,11 +349,18 @@ fn lower_request(prepared: &PreparedInference, prefix: &str) -> Result json!({ + InputItem::ToolResult { call_id, output } => json!({ "role": "tool", "tool_call_id": call_id, "content": output, }), + // Ghostlight replays no provider state, and an OpenAI-compatible + // server has no place for one. + InputItem::ReasoningState { .. } => { + return Err(InferenceFault::integrity_violation( + "a local request carried provider reasoning state", + )); + } }); } let mut tools = Vec::with_capacity(request.tools.len()); @@ -379,9 +386,7 @@ fn lower_request(prepared: &PreparedInference, prefix: &str) -> Result::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1119,10 +1124,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1194,10 +1199,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1232,10 +1237,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1400,7 +1405,7 @@ mod tests { InferencePurpose::Elaboration, TEST_MODEL, "Author the shortfall.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Author the shortfall.".into(), }], patch_tools(), @@ -1428,10 +1433,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1460,7 +1465,7 @@ mod tests { InferencePurpose::Elaboration, TEST_MODEL, "Author the shortfall.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Author the shortfall.".into(), }], patch_tools(), @@ -1493,10 +1498,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1526,10 +1531,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1558,10 +1563,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1588,10 +1593,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1624,10 +1629,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -2054,8 +2059,8 @@ mod tests { InferencePurpose::Persona, "hosted/deepseek-chat", "Respond only in natural prose.", - vec![CodexInputItem::UserText { text: "Say something true.".into() }], - Vec::::new(), + vec![InputItem::UserText { text: "Say something true.".into() }], + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false }, ) .expect("the request builds"); diff --git a/crates/ghostlight/src/patch.rs b/crates/ghostlight/src/patch.rs index aa50ae6..a838ac0 100644 --- a/crates/ghostlight/src/patch.rs +++ b/crates/ghostlight/src/patch.rs @@ -18,7 +18,7 @@ use super::{ AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, LensWeights, NewController, SubjectId, SubjectKind, SubjectState, WorldId, }; -use codex_connector::CodexToolDefinition; +use model_connector::ToolDefinition; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; @@ -6726,7 +6726,7 @@ pub(crate) const PATCH_TOOLS: &[PatchTool] = &[ /// The catalog. Fixed per build: it reads `PATCH_TOOLS` and nothing else — not /// world state, not a snapshot, not a config. -pub(crate) fn patch_tools() -> Vec { +pub(crate) fn patch_tools() -> Vec { PATCH_TOOLS .iter() .map(|entry| { diff --git a/crates/ghostlight/src/sdk_inference.rs b/crates/ghostlight/src/sdk_inference.rs index d112be3..06f69df 100644 --- a/crates/ghostlight/src/sdk_inference.rs +++ b/crates/ghostlight/src/sdk_inference.rs @@ -12,7 +12,7 @@ use super::controllers::{ tool_name_is_valid, unix_ms, }; use async_trait::async_trait; -use codex_connector::CodexInputItem; +use model_connector::{InputItem, ReasoningEffort}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::BTreeMap; @@ -29,10 +29,6 @@ use tokio::sync::Mutex as AsyncMutex; /// largest request either transport carries is the same grouped cell. pub(super) const MAX_SIDECAR_FRAME_BYTES: usize = 1_052_672; -/// The reasoning-effort values the SDK's own `EffortLevel` admits. A request -/// carrying anything else is refused rather than silently mis-mapped. -const SDK_EFFORT_LEVELS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"]; - #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub(super) enum SidecarFrame { @@ -379,9 +375,9 @@ struct SdkInferenceReceipt { const SDK_RECEIPT_SCHEMA: &str = "ghostlight.sdk_inference_receipt.v1"; /// The model-name prefix that names the SDK transport when nothing configures -/// one. It holds even with no SDK port built, so a `claude-`prefixed lane on a -/// connector-only deployment is refused at open instead of quietly reaching the -/// wrong backend. +/// one. It claims a model only when the sidecar is configured; the connector +/// serves `claude-` models on its own, and `open_inference` refuses a sidecar +/// whose prefix would take a connector model. pub const DEFAULT_SDK_MODEL_PREFIX: &str = "claude"; /// Everything the SDK sidecar needs to open, gathered so `open_inference` takes @@ -551,15 +547,8 @@ pub(super) fn lower_query( turn_cap: u32, ) -> Result { let request = &prepared.invocation.request; - if let Some(effort) = request.reasoning_effort.as_deref() - && !SDK_EFFORT_LEVELS.contains(&effort) - { - return Err(InferenceFault::integrity_violation( - "the requested reasoning effort has no SDK counterpart", - )); - } let mut items = request.input.iter(); - let Some(CodexInputItem::UserText { text: prompt }) = items.next() else { + let Some(InputItem::UserText { text: prompt }) = items.next() else { return Err(InferenceFault::integrity_violation( "an SDK request must open with exactly one user text item", )); @@ -567,17 +556,22 @@ pub(super) fn lower_query( let mut transcript = Vec::new(); for item in items { match item { - CodexInputItem::AssistantText { text } => transcript.push(format!("assistant: {text}")), - CodexInputItem::ToolCall { + InputItem::AssistantText { text } => transcript.push(format!("assistant: {text}")), + InputItem::ToolCall { name, arguments, .. } => transcript.push(format!("tool call {name}: {arguments}")), - CodexInputItem::ToolResult { output, .. } => { + InputItem::ToolResult { output, .. } => { transcript.push(format!("tool result: {output}")) } // A later user turn is a kernel refusal reopening the session; the // transcript is already a textual replay of the conversation, so // it rides there like every other turn. - CodexInputItem::UserText { text } => transcript.push(format!("user: {text}")), + InputItem::UserText { text } => transcript.push(format!("user: {text}")), + InputItem::ReasoningState { .. } => { + return Err(InferenceFault::integrity_violation( + "an SDK request carried provider reasoning state", + )); + } } } Ok(SidecarFrame::Query { @@ -595,8 +589,16 @@ pub(super) fn lower_query( parameters_json: tool.parameters_json.clone(), }) .collect(), - effort: request.reasoning_effort.clone(), - max_output_tokens: request.max_output_tokens, + effort: request.reasoning_effort.map(|effort| { + match effort { + ReasoningEffort::Low => "low", + ReasoningEffort::Medium => "medium", + ReasoningEffort::High => "high", + ReasoningEffort::Max => "max", + } + .to_owned() + }), + max_output_tokens: Some(request.max_output_tokens), turn_cap, }) } @@ -769,8 +771,10 @@ impl RoutedInferencePort { .filter(|(prefix, _)| model.starts_with(prefix.as_str())) .max_by_key(|(prefix, _)| prefix.len()) .map(|(prefix, port)| (prefix.len(), port)); - let sdk_claim = model - .starts_with(&self.sdk_model_prefix) + // The SDK prefix claims only when the sidecar is configured: the + // connector serves `claude-` models too, so an unconfigured sidecar + // must leave them to it. + let sdk_claim = (self.sdk.is_some() && model.starts_with(&self.sdk_model_prefix)) .then_some(self.sdk_model_prefix.len()); match (local_claim, sdk_claim) { (Some((local_len, local_port)), Some(sdk_len)) => { @@ -831,7 +835,7 @@ mod tests { RECORD_GAP_PATCH_TOOL, SUBMIT_PATCH_TOOL, kernel_speak_entry, patch_tools, }; use crate::{AffordanceId, AffordanceSnapshot}; - use codex_connector::CodexToolDefinition; + use model_connector::ToolDefinition; use std::collections::VecDeque; const TEST_RUNTIME: &str = "ghostlight-sdk-test"; @@ -912,7 +916,7 @@ mod tests { InferencePurpose::Elaboration, TEST_MODEL, "Author the shortfall.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: prompt.into(), }], patch_tools(), @@ -932,10 +936,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: prompt.into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1346,7 +1350,7 @@ mod tests { InferencePurpose::OperationalAgent, TEST_MODEL, "Use only the supplied tools.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Hold the bridge.".into(), }], catalog_tools("", &granted), @@ -1442,10 +1446,21 @@ mod tests { open_inference(None, Some(sdk()), None, None, &models("gpt-5.6-terra").each()), Err(ControllerOpenError::UnroutableModel { .. }) )); + // The connector alone serves `claude-` models. + assert!( + open_inference(Some(connector()), None, None, None, &models("claude-haiku-5-5").each()).is_ok() + ); + // A sidecar whose prefix would take a model the connector serves is + // refused at open, not left to steal the route. assert!(matches!( - open_inference(Some(connector()), None, None, None, &models("claude-opus-5").each()), - Err(ControllerOpenError::UnroutableModel { .. }) + open_inference(Some(connector()), Some(sdk()), None, None, &models("claude-haiku-5-5").each()), + Err(ControllerOpenError::SidecarClaimsConnectorModel { .. }) )); + // The same sidecar beside the connector is fine for a model the + // connector does not serve. + assert!( + open_inference(Some(connector()), Some(sdk()), None, None, &models("claude-opus-5").each()).is_ok() + ); assert!(matches!( open_inference( None, @@ -1795,13 +1810,6 @@ mod tests { assert_names_no(&fault, CANARY); } - // An effort the SDK has no counterpart for. - let port = SdkInferencePort::new(ScriptedLink::new(Vec::new()), TEST_RUNTIME); - let mut prepared = prose_prepared(&port, "Say something true."); - prepared.invocation.request.reasoning_effort = Some(CANARY.into()); - let fault = lower_query(1, &prepared, 1).expect_err("an unmapped effort lowered"); - assert_names_no(&fault, CANARY); - // A model no backend claims, prepared and inferred through the router. let directory = tempfile::tempdir().unwrap(); let entry = directory.path().join("main.js"); @@ -1824,8 +1832,8 @@ mod tests { InferencePurpose::Persona, CANARY, "Respond only in natural prose.", - vec![CodexInputItem::UserText { text: "Say something true.".into() }], - Vec::::new(), + vec![InputItem::UserText { text: "Say something true.".into() }], + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false }, ) .expect("the request builds"); @@ -1840,25 +1848,27 @@ mod tests { // `lower_query` reads the provider request off the prepared value, so // the shapes it must refuse are written there directly. Nothing here // asserts a digest; the identity tests own that. - let build = |input: Vec, effort: Option<&str>| { + let build = |input: Vec, effort: Option| { let mut prepared = prose_prepared(&port, "Say something true."); prepared.invocation.request.input = input; - prepared.invocation.request.reasoning_effort = effort.map(str::to_owned); + prepared.invocation.request.reasoning_effort = effort; prepared }; - let user = |text: &str| CodexInputItem::UserText { text: text.into() }; + let user = |text: &str| InputItem::UserText { text: text.into() }; - // Every effort the SDK admits passes; anything else is refused. - for effort in SDK_EFFORT_LEVELS { + // Every typed effort lowers. + for effort in [ + ReasoningEffort::Low, + ReasoningEffort::Medium, + ReasoningEffort::High, + ReasoningEffort::Max, + ] { assert!(lower_query(1, &build(vec![user("go")], Some(effort)), 1).is_ok()); } - let fault = lower_query(1, &build(vec![user("go")], Some("blistering")), 1) - .expect_err("an unmapped effort lowered"); - assert!(fault.integrity_was_violated(), "{fault:?}"); // The first item must be user text. for input in [ - vec![CodexInputItem::AssistantText { text: "no".into() }], + vec![InputItem::AssistantText { text: "no".into() }], Vec::new(), ] { let fault = lower_query(1, &build(input, None), 1) @@ -1881,20 +1891,20 @@ mod tests { &build( vec![ user("go"), - CodexInputItem::AssistantText { + InputItem::AssistantText { text: "thinking".into(), }, - CodexInputItem::ToolCall { + InputItem::ToolCall { call_id: "call-0".into(), name: "record_gap".into(), arguments: "{}".into(), }, - CodexInputItem::ToolResult { + InputItem::ToolResult { call_id: "call-0".into(), output: "gap recorded".into(), }, ], - Some("medium"), + Some(ReasoningEffort::Medium), ), 4, ) @@ -1930,15 +1940,27 @@ mod tests { #[tokio::test] async fn soul_routing_refuses_rather_than_falling_back() { assert_eq!(DEFAULT_SDK_MODEL_PREFIX, "claude"); - let connector_only = RoutedInferencePort::new( - Some(Arc::new(SdkInferencePort::new( + let stand_in = || { + Arc::new(SdkInferencePort::new( ScriptedLink::new(Vec::new()), TEST_RUNTIME, - )) as Arc), + )) as Arc + }; + // A connector with no sidecar serves `claude-` models itself. + let connector = stand_in(); + let connector_only = RoutedInferencePort::new( + Some(Arc::clone(&connector)), None, DEFAULT_SDK_MODEL_PREFIX, Vec::new(), ); + assert!(Arc::ptr_eq( + connector_only.route(TEST_MODEL).unwrap(), + &connector + )); + // A sidecar on a prefix that does not match, and no connector: the + // model has no owner and routes nowhere. + let connector_only = RoutedInferencePort::new(None, Some(stand_in()), "sdk/", Vec::new()); assert!(connector_only.route(TEST_MODEL).is_none()); let prepared = PreparedInference::prepare(TEST_RUNTIME, 4_102_444_800_000, prose_request("Say it.")).unwrap(); diff --git a/crates/ghostlight/src/table.rs b/crates/ghostlight/src/table.rs index b4049f0..1eccbb5 100644 --- a/crates/ghostlight/src/table.rs +++ b/crates/ghostlight/src/table.rs @@ -26,7 +26,7 @@ use super::{ DecisionOpportunity, EntityId, KernelError, Mismatch, RefKind, Statement, SubjectId, SubjectKind, Target, WorldPatch, WorldSnapshot, }; -use codex_connector::{CodexInputItem, CodexToolDefinition}; +use model_connector::{InputItem, ToolDefinition}; use serde_json::Value; use thiserror::Error; @@ -44,7 +44,7 @@ pub enum TableError { /// `PATCH_TOOLS`; which names a particular agent gets is policy, and policy /// belongs to the caller — `PLAY_TOOLS` is Dungeon's, pinned in Cut 8, not /// this module's. -pub fn authoring_tools(names: &[&str]) -> Result, TableError> { +pub fn authoring_tools(names: &[&str]) -> Result, TableError> { let catalog = patch::patch_tools(); names .iter() @@ -220,7 +220,7 @@ fn subject_opportunity<'a>( /// turn; that is the controller lane's own vocabulary, and /// `decode_actor_call` has no arm for either, so offering them here would /// hand the play agent a tool `decode_actor_call` always refuses (PA.f55). -pub fn actor_tools(prefix: &str, snapshot: &WorldSnapshot, subject: SubjectId) -> Vec { +pub fn actor_tools(prefix: &str, snapshot: &WorldSnapshot, subject: SubjectId) -> Vec { match subject_opportunity(snapshot, subject) { Some((_, granted)) => controllers::affordance_tools(prefix, &granted), None => Vec::new(), @@ -1038,8 +1038,8 @@ impl InferenceRequest { round: usize, model: &str, instructions: &str, - input: Vec, - tools: Vec, + input: Vec, + tools: Vec, max_output_tokens: u32, ) -> Result { tool_request( diff --git a/crates/ghostlight/src/tool_schema.rs b/crates/ghostlight/src/tool_schema.rs index ce15274..8ce081b 100644 --- a/crates/ghostlight/src/tool_schema.rs +++ b/crates/ghostlight/src/tool_schema.rs @@ -6,11 +6,11 @@ //! own vocabulary. Both spell a property the same way because both spell it //! here. Nothing in this module reads world state, a snapshot, or a config. -use codex_connector::CodexToolDefinition; +use model_connector::ToolDefinition; use serde_json::{Value, json}; -pub(super) fn tool(name: &str, description: &str, schema: Value) -> CodexToolDefinition { - CodexToolDefinition { +pub(super) fn tool(name: &str, description: &str, schema: Value) -> ToolDefinition { + ToolDefinition { name: name.into(), description: description.into(), parameters_json: serde_json::to_string(&schema) diff --git a/crates/ghostlight/src/verse/calls.rs b/crates/ghostlight/src/verse/calls.rs index 079fa44..22bfe31 100644 --- a/crates/ghostlight/src/verse/calls.rs +++ b/crates/ghostlight/src/verse/calls.rs @@ -26,7 +26,7 @@ use crate::controllers::{ }; use async_trait::async_trait; use chrono::Utc; -use codex_connector::CodexProviderRequest; +use model_connector::ProviderRequest; use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -197,10 +197,10 @@ fn hex(digest: &[u8]) -> String { /// id from the world it ran in, so keying on them would tie a recorded run to /// one world's random identity. Everything else the provider is sent /// (model, instructions, input, tools, shape) is in the digest. -fn content_digest(request: &CodexProviderRequest) -> Result { +fn content_digest(request: &ProviderRequest) -> Result { // Exhaustive on purpose: a field added upstream must be placed in the key // or left out here by name before this compiles. - let CodexProviderRequest { + let ProviderRequest { schema_id, request_id: _request_id, // names the call, not what it asks conversation_id: _conversation_id, // names the call, not what it asks @@ -208,16 +208,12 @@ fn content_digest(request: &CodexProviderRequest) -> Result Result Result { - let allowance = request - .invocation - .request - .max_output_tokens - .ok_or_else(InferenceFault::budget_exhausted)?; + let allowance = request.invocation.request.max_output_tokens; let payload = serde_json::to_vec(&request.invocation.request) .map_err(|_| InferenceFault::new("a provider request could not be measured"))?; Ok((payload.len() as u64).saturating_add(u64::from(allowance))) diff --git a/crates/ghostlight/src/verse/calls/tests.rs b/crates/ghostlight/src/verse/calls/tests.rs index 02131ae..201b6f7 100644 --- a/crates/ghostlight/src/verse/calls/tests.rs +++ b/crates/ghostlight/src/verse/calls/tests.rs @@ -3,7 +3,7 @@ use crate::CommandId; use crate::controllers::{ InferenceFaultClass, InferenceFaultDisposition, RequestShape, tool_request, }; -use codex_connector::{CodexInputItem, CodexToolDefinition}; +use model_connector::{InputItem, ToolDefinition}; use std::sync::atomic::{AtomicUsize, Ordering}; const MODEL: &str = "hosted/test-model"; @@ -73,10 +73,10 @@ fn request_for(command: CommandId, prompt: &str, max_output_tokens: u32) -> Infe InferencePurpose::Persona, MODEL, "Respond only in prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: prompt.into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens, parallel_tool_calls: false, @@ -100,13 +100,7 @@ fn bound_of(prepared: &PreparedInference) -> u64 { .expect("a provider request serializes") .len() as u64; payload - + u64::from( - prepared - .invocation - .request - .max_output_tokens - .expect("an allowance"), - ) + + u64::from(prepared.invocation.request.max_output_tokens) } fn reply(text: &str, receipt: &str) -> InferenceOutput { @@ -276,17 +270,6 @@ async fn cap_refuses_before_the_provider_is_called() { .await .expect("a call that fits the cap is made"); assert_eq!(inner.calls(), 1); - - // A request with no output allowance has no bound and is refused. - let mut open_ended = prepared_for("open ended", 1_200); - open_ended.invocation.request.max_output_tokens = None; - let unbounded = recording(&inner, &store, "run-open", u64::MAX); - let fault = unbounded - .infer(open_ended) - .await - .expect_err("no allowance, no bound"); - assert_eq!(fault.class(), InferenceFaultClass::BudgetExhausted); - assert_eq!(inner.calls(), 1); } #[tokio::test] @@ -969,20 +952,20 @@ async fn usage_one_token_over_the_bound_faults_and_stores_no_record() { #[test] fn the_replay_key_covers_what_the_request_asks_and_not_what_names_it() { let base = prepared_for("key", 1_200).invocation.request.clone(); - let digest = |edit: &dyn Fn(&mut CodexProviderRequest)| { + let digest = |edit: &dyn Fn(&mut ProviderRequest)| { let mut request = base.clone(); edit(&mut request); content_digest(&request).unwrap() }; let same = digest(&|_| {}); assert_eq!(same, content_digest(&base).unwrap()); - let changes: Vec<(&str, Box)> = vec![ + let changes: Vec<(&str, Box)> = vec![ ("model", Box::new(|r| r.model.push('x'))), ("instructions", Box::new(|r| r.instructions.push('x'))), ( "tools", Box::new(|r| { - r.tools.push(CodexToolDefinition { + r.tools.push(ToolDefinition { name: "t".into(), description: "d".into(), parameters_json: "{}".into(), @@ -991,57 +974,41 @@ fn the_replay_key_covers_what_the_request_asks_and_not_what_names_it() { ), ( "input", - Box::new(|r| r.input.push(CodexInputItem::UserText { text: "x".into() })), + Box::new(|r| r.input.push(InputItem::UserText { text: "x".into() })), ), ( "max_output_tokens", - Box::new(|r| r.max_output_tokens = Some(1)), + Box::new(|r| r.max_output_tokens = 1), ), ( "reasoning_effort", - Box::new(|r| r.reasoning_effort = Some("low".into())), - ), - ( - "service_tier", - Box::new(|r| r.service_tier = Some("flex".into())), + Box::new(|r| r.reasoning_effort = Some(model_connector::ReasoningEffort::High)), ), ( "output_schema_json", Box::new(|r| r.output_schema_json = Some("{}".into())), ), - ( - "previous_response_id", - Box::new(|r| r.previous_response_id = Some("p".into())), - ), ( "parallel_tool_calls", Box::new(|r| r.parallel_tool_calls = !r.parallel_tool_calls), ), ("schema_id", Box::new(|r| r.schema_id.push_str(".v2"))), - ( - "reasoning_summary", - Box::new(|r| r.reasoning_summary = Some("auto".into())), - ), - ( - "output_format_name", - Box::new(|r| r.output_format_name = Some("persona_reply".into())), - ), ( "tool_choice", Box::new(|r| { r.tool_choice = match r.tool_choice { - codex_connector::CodexToolChoice::Auto => { - codex_connector::CodexToolChoice::Required + model_connector::ToolChoice::Auto => { + model_connector::ToolChoice::Required } - codex_connector::CodexToolChoice::Required => { - codex_connector::CodexToolChoice::Auto + model_connector::ToolChoice::Required => { + model_connector::ToolChoice::Auto } } }), ), ( - "prompt_cache_key", - Box::new(|r| r.prompt_cache_key = Some("ghostlight-persona-1".into())), + "cache_retention", + Box::new(|r| r.cache_retention = Some(model_connector::CacheRetention::Short)), ), ]; for (field, change) in changes { diff --git a/crates/ghostlight/src/verse/run/tests.rs b/crates/ghostlight/src/verse/run/tests.rs index a5f00f8..ff4236a 100644 --- a/crates/ghostlight/src/verse/run/tests.rs +++ b/crates/ghostlight/src/verse/run/tests.rs @@ -141,7 +141,7 @@ impl InferencePort for ScriptedPort { let sequence = self.calls.fetch_add(1, Ordering::SeqCst); let wire = &request.invocation.request; let bound = serde_json::to_vec(wire).unwrap().len() as u64 - + u64::from(wire.max_output_tokens.unwrap()); + + u64::from(wire.max_output_tokens); self.bounds.lock().unwrap().push(bound); if let Some(fault) = self.faults.lock().unwrap().pop_front() { return Err(fault);