diff --git a/Cargo.lock b/Cargo.lock index 3709c14..37286de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -73,6 +73,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -94,6 +100,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + [[package]] name = "cc" version = "1.4.4" @@ -144,12 +156,14 @@ dependencies = [ "hmac", "libc", "model-connector", + "rand_core 0.6.4", "rmp-serde", "rmpv", "serde", "serde_json", "sha2", "thiserror", + "ureq", "zeroize", ] @@ -231,7 +245,7 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f111 dependencies = [ "aes-gcm", "anyhow", - "base64", + "base64 0.22.1", "chrono", "cultcache-rs", "ed25519-dalek", @@ -436,6 +450,22 @@ dependencies = [ "digest", ] +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -510,7 +540,7 @@ version = "0.1.0" dependencies = [ "aes-gcm", "anyhow", - "base64", + "base64 0.22.1", "cultcache-rs", "cultnet-rs", "rand_core 0.6.4", @@ -555,6 +585,12 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -699,6 +735,20 @@ dependencies = [ "syn 3.0.4", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rmp" version = "0.8.15" @@ -738,6 +788,41 @@ dependencies = [ "semver", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -985,6 +1070,46 @@ dependencies = [ "subtle", ] +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0" +dependencies = [ + "base64 0.22.1", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "uuid" version = "1.25.0" @@ -1062,6 +1187,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "winapi" version = "0.3.9" diff --git a/README.md b/README.md index 7ffd262..eb3a1e3 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,8 @@ publishes the plan's usage windows (`usage_readout`, `claude_usage_readout` on t minds to read and decide their own burn. The one usage-derived refusal is the provider's own (`ProviderRejected`), repeated until its reset. -Status: the `model-connector` crate and the `claude-connector` backend crate are live. No -connector binary exists yet (the Claude connector binary is first, then an OpenAI-compatible one). +Status: the `model-connector` crate and the `claude-connector` backend crate and binary are live +(`claude-connector serve|config|ask`); an OpenAI-compatible connector is not written. ## Entry points @@ -40,7 +40,7 @@ Crate `crates/model-connector`: `ProviderBackend` trait. A connector binary implements `ProviderBackend` for its provider and calls `serve`; the kit names no provider. -Crate `crates/claude-connector` (library only; the binary that wires it to `serve` is not written): +Crate `crates/claude-connector` (library and the `claude-connector` binary that wires it to `serve`): - `ClaudeCodeBackend` implements `ProviderBackend` for provider `claude-code` by driving the unmodified `claude` binary, one child per call, in print stream-json mode with no tools, no MCP @@ -50,12 +50,31 @@ Crate `crates/claude-connector` (library only; the binary that wires it to `serv - Reasoning state is a session handle (`ClaudeCodeHandle`) authenticated with a connector secret and bound to the caller it was minted for; a handle that cannot be proven to match the request and its caller re-seeds from the caller's transcript, and every resume forks. +- `MessagesBackend` implements `ProviderBackend` for provider `anthropic-messages` when the config document says `auth` is an API key (`config init --auth api-key`; one choice for the whole connector, held in the credential `--token-credential` names). One non-streaming `POST /v1/messages` per call: tools, tool calls and results, thinking blocks (replayed unchanged as reasoning state), `cache_control` (5 minutes, or 1 hour for long retention) and cache read and write usage map natively. The key is read from the systemd credential at every call and travels only as the `x-api-key` header. A request's output schema is `output_config.format`; `Required` tool choice is `tool_choice: any` where the model accepts it and a refusal before sending where it does not (the current Sonnet and Opus reject it). A key has no plan: no meter runs, the plan windows stay empty, and a key document refuses leases. - `ProcessPort` is the one OS seam (`StdProcessPort`, unix, kills the child's whole process group); `SessionStore` and `StderrSink` are the other ports. `ClaudeCodeConfig` is what the - binary hands in; the credential is read from a systemd credential and reaches the child on a - pipe (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`), never in an environment. `QuotaCell` keeps the + binary hands in; the subscription token is read from a systemd credential and reaches the child on a + pipe, never in an environment (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`). `QuotaCell` keeps the plan windows the CLI's `rate_limit_event`s report, for the usage readout and the lease grant. +## Asking for one no-tools completion + +`claude-connector ask` is a caller of a running connector for a Mind's Self run: the prompt is all +of stdin, the answer text is stdout. + +``` +claude-connector ask --caller-id ID --connection-key-file FILE --model MODEL (--system TEXT | --system-file FILE) [--endpoint HOST:PORT] [--effort low|medium|high|max] [--max-output-tokens N] [--timeout-secs N] < prompt > answer +``` + +Defaults: endpoint `127.0.0.1:4110`, 8192 output tokens, 300 s. The key is read from the file (the +same text the connector reads for the caller; never argv or environment). There is no tools flag, +no working-directory flag and no other endpoint: the request is built by `ProviderRequest::new` +(no tools) and the model child's cwd and environment stay the connector's. Any failure (refused, +over a cap, model not allowed, wrong key or caller, timeout, provider failure, empty answer, empty +stdin) exits nonzero with one `claude-connector: ` line on stderr and nothing on stdout; +the line never carries the key, the prompt or the provider's message. Each run uses a fresh request +id. Code: `crates/claude-connector/src/ask.rs`; tests: `crates/claude-connector/tests/ask.rs`. + Frame arithmetic is public in `src/envelope.rs`, measured on the carriage frame: `frame_bytes_for_payload(n)` is the frame a caller payload bound of `n` needs, `payload_bytes_for_frame(frame)` is the largest payload bound a frame allows, and `MAX_IDENTITY_BYTES` (256) bounds caller ids, request ids and model names. diff --git a/crates/claude-connector/Cargo.toml b/crates/claude-connector/Cargo.toml index 6cb9e45..73f60cd 100644 --- a/crates/claude-connector/Cargo.toml +++ b/crates/claude-connector/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "claude-connector" -description = "Claude backend for the connector kit: drives the unmodified claude binary in print stream-json mode" +description = "Claude backends for the connector kit: the claude CLI on a subscription token, the Messages API on an API key" version.workspace = true edition.workspace = true license.workspace = true @@ -17,11 +17,13 @@ chrono = { version = "0.4", default-features = false } hmac = "0.12" cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "a4eae9056152335662f1115f97bf35fb00ab6d23", package = "cultcache-rs" } model-connector = { path = "../model-connector", features = ["daemon"] } +rand_core = { version = "0.6", features = ["getrandom"] } rmp-serde = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" thiserror = "2" +ureq = { version = "~3.3", default-features = false, features = ["rustls"] } zeroize = "1" [target.'cfg(unix)'.dependencies] diff --git a/crates/claude-connector/src/ask.rs b/crates/claude-connector/src/ask.rs new file mode 100644 index 0000000..8e707ce --- /dev/null +++ b/crates/claude-connector/src/ask.rs @@ -0,0 +1,338 @@ +//! `claude-connector ask`: one no-tools completion through a running connector. +//! +//! A thin caller over [`ConnectorClient`]. It builds a [`ProviderRequest`] with +//! `ProviderRequest::new`, which carries no tools, and has no field, flag or +//! path by which a caller could add one; the working directory and environment +//! of the model child belong to the connector. Every failure is an +//! [`AskError`] whose text names a cause and never echoes the key, the prompt +//! or the instructions. + +use std::net::SocketAddr; +use std::path::Path; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use model_connector::{ + ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest, + ReasoningEffort, StopReason, TransportDisposition, TransportEventPayload, TransportInvocation, + TransportOutcome, TransportResult, frame_bytes_for_payload, provider_request_sha256, +}; +use rand_core::{OsRng, RngCore}; +use zeroize::Zeroizing; + +/// The loopback endpoint a claude connector listens on. +pub const DEFAULT_ENDPOINT: &str = "127.0.0.1:4110"; +/// The payload bound the connector's own `config init` defaults to. +pub const PAYLOAD_BYTES: usize = 1 << 20; +const MAX_KEY_BYTES: usize = 1024; +pub const MAX_SYSTEM_BYTES: usize = 64 * 1024; + +pub struct AskArgs { + pub endpoint: SocketAddr, + pub caller_id: String, + pub key_file: std::path::PathBuf, + pub model: String, + pub instructions: String, + pub effort: Option, + pub max_output_tokens: u32, + pub timeout: Duration, + pub prompt: String, +} + +#[derive(Debug, thiserror::Error)] +pub enum AskError { + #[error("the prompt on stdin is empty")] + EmptyPrompt, + #[error("the prompt on stdin is larger than the {PAYLOAD_BYTES} byte payload bound")] + PromptTooLarge, + #[error("the instructions are empty")] + EmptyInstructions, + #[error("the connection key file cannot be read")] + KeyUnreadable, + #[error("the connection key file is not text")] + KeyEncoding, + #[error("the connection key file is not a regular file")] + KeyNotRegular, + #[error("the connection key file is readable by group or world (chmod 600)")] + KeyExposed, + #[error("the instructions file cannot be read as text from a regular file")] + SystemUnreadable, + #[error("the instructions file is larger than {MAX_SYSTEM_BYTES} bytes")] + SystemTooLarge, + #[error("standard input cannot be read")] + StdinRead, + #[error("standard input is not UTF-8 text")] + StdinNotText, + #[error("the answer cannot be written to standard output")] + StdoutWrite, + #[error("nothing is listening at the connector endpoint")] + NotListening, + #[error( + "the connector closed the connection without answering (key, caller or frame not accepted)" + )] + ClosedWithoutAnswer, + #[error("the connection key file is empty or longer than {MAX_KEY_BYTES} bytes")] + KeyLength, + #[error("the connection key is not usable as a key (surrounding whitespace?)")] + KeyUnusable, + #[error("the request is invalid for the connector contract")] + Request, + #[error("timed out waiting for the connector")] + Timeout, + #[error("the connector connection failed: {0}")] + Connection(std::io::ErrorKind), + #[error("the connector answer was not accepted (wrong key, caller or tampered frame): {0}")] + Transport(model_connector::ServiceError), + #[error("the request exceeded a frame bound")] + FrameSize, + #[error("the connector refused the request: {0:?}")] + Refused(model_connector::Refusal), + #[error("the provider failed: {0:?}")] + Failed(FailureKind), + #[error("the answer stopped as {0:?}, not a completed text")] + NotCompleted(StopReason), + #[error("the answer carried a tool call, which this command never requests")] + ToolCall, + #[error("the answer is empty")] + EmptyAnswer, +} + +enum ReadFailure { + Unreadable, + NotRegular, + TooLarge, + Exposed, +} + +/// Opens `path` without blocking (a FIFO must not hang the open), requires the +/// opened file to be a regular file (a symlink is followed and its target +/// judged), optionally refuses one readable by group or world, and reads at +/// most `cap` bytes, failing if there are more. +fn read_regular(path: &Path, cap: usize, private: bool) -> Result>, ReadFailure> { + use std::io::Read; + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NONBLOCK); + } + let file = options.open(path).map_err(|_| ReadFailure::Unreadable)?; + let metadata = file.metadata().map_err(|_| ReadFailure::Unreadable)?; + if !metadata.is_file() { + return Err(ReadFailure::NotRegular); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if private && metadata.permissions().mode() & 0o077 != 0 { + return Err(ReadFailure::Exposed); + } + } + let mut bytes = Zeroizing::new(Vec::new()); + file.take(cap as u64 + 1) + .read_to_end(&mut bytes) + .map_err(|_| ReadFailure::Unreadable)?; + if bytes.len() > cap { + return Err(ReadFailure::TooLarge); + } + Ok(bytes) +} + +/// Reads the key as the connector reads its own key file (the text without the +/// trailing line ending). The bytes are zeroized on drop and never shown. +pub fn read_key(path: &Path) -> Result, AskError> { + let raw = read_regular(path, MAX_KEY_BYTES, true).map_err(|failure| match failure { + ReadFailure::Unreadable => AskError::KeyUnreadable, + ReadFailure::NotRegular => AskError::KeyNotRegular, + ReadFailure::TooLarge => AskError::KeyLength, + ReadFailure::Exposed => AskError::KeyExposed, + })?; + let text = std::str::from_utf8(raw.as_slice()).map_err(|_| AskError::KeyEncoding)?; + let key = Zeroizing::new(text.trim_end_matches(['\r', '\n']).to_string()); + if key.is_empty() || key.len() > MAX_KEY_BYTES { + return Err(AskError::KeyLength); + } + if key.trim() != key.as_str() { + return Err(AskError::KeyUnusable); + } + Ok(key) +} + +/// The instructions file: a regular file of at most [`MAX_SYSTEM_BYTES`] of text. +pub fn read_system_file(path: &Path) -> Result { + let raw = read_regular(path, MAX_SYSTEM_BYTES, false).map_err(|failure| match failure { + ReadFailure::TooLarge => AskError::SystemTooLarge, + _ => AskError::SystemUnreadable, + })?; + String::from_utf8(raw.to_vec()).map_err(|_| AskError::SystemUnreadable) +} + +fn fresh_id(prefix: &str) -> String { + let mut nonce = [0_u8; 16]; + OsRng.fill_bytes(&mut nonce); + let hex: String = nonce.iter().map(|b| format!("{b:02x}")).collect(); + format!("{prefix}-{hex}") +} + +/// The one invocation `ask` ever sends: instructions, one user text, no tools. +pub fn build_invocation(args: &AskArgs) -> Result { + if args.prompt.trim().is_empty() { + return Err(AskError::EmptyPrompt); + } + if args.prompt.len() > PAYLOAD_BYTES { + return Err(AskError::PromptTooLarge); + } + if args.instructions.trim().is_empty() { + return Err(AskError::EmptyInstructions); + } + let mut request = ProviderRequest::new( + fresh_id("ask"), + fresh_id("ask-conversation"), + args.model.clone(), + args.instructions.clone(), + args.max_output_tokens, + ); + request.input = vec![InputItem::UserText { + text: args.prompt.clone(), + }]; + request.reasoning_effort = args.effort; + let digest = provider_request_sha256(&request).map_err(|_| AskError::Request)?; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64); + let invocation = + TransportInvocation::new(args.caller_id.clone(), now + 120_000, digest, request) + .map_err(|_| AskError::Request)?; + invocation + .validate(now, 300_000) + .map_err(|_| AskError::Request)?; + Ok(invocation) +} + +/// The answer text of a result, or the one cause it is not an answer. +pub fn answer_text(result: &TransportResult) -> Result { + let (events, receipt) = match &result.disposition { + TransportDisposition::Refused(reason) => return Err(AskError::Refused(reason.clone())), + TransportDisposition::Transported { events, receipt } => (events, receipt), + }; + match &receipt.outcome { + TransportOutcome::Failed { kind, .. } => return Err(AskError::Failed(*kind)), + TransportOutcome::Completed { stop_reason, .. } => { + if !matches!(stop_reason, StopReason::EndTurn | StopReason::StopSequence) { + return Err(AskError::NotCompleted(*stop_reason)); + } + } + } + let mut text = String::new(); + for event in events { + match &event.payload { + TransportEventPayload::TextDelta { text: delta } => text.push_str(delta), + TransportEventPayload::ToolCall { .. } => return Err(AskError::ToolCall), + TransportEventPayload::ReasoningState { .. } => {} + } + } + if text.trim().is_empty() { + return Err(AskError::EmptyAnswer); + } + Ok(text) +} + +pub fn ask(args: &AskArgs) -> Result { + let invocation = build_invocation(args)?; + let key = read_key(&args.key_file)?; + let client = ConnectorClient::new( + args.endpoint, + key.as_str(), + frame_bytes_for_payload(PAYLOAD_BYTES), + Some(args.timeout), + ) + .map_err(|error| match error { + ConnectorClientError::Transport(_) => AskError::KeyUnusable, + _ => AskError::Request, + })?; + let result = client.execute(&invocation).map_err(|error| match error { + ConnectorClientError::Connection(io) + if matches!( + io.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut + ) => + { + AskError::Timeout + } + ConnectorClientError::Connection(io) => match io.kind() { + std::io::ErrorKind::ConnectionRefused => AskError::NotListening, + std::io::ErrorKind::UnexpectedEof + | std::io::ErrorKind::ConnectionReset + | std::io::ErrorKind::BrokenPipe => AskError::ClosedWithoutAnswer, + kind => AskError::Connection(kind), + }, + ConnectorClientError::Transport(error) => AskError::Transport(error), + ConnectorClientError::FrameSize => AskError::FrameSize, + ConnectorClientError::InvalidConfig | ConnectorClientError::RequestIdTooLong => { + AskError::Request + } + })?; + answer_text(&result) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::{ClaudeCodeConfig, ClaudeCodeLimits}; + use crate::handle::{SessionStore, plan}; + use model_connector::ToolDefinition; + + struct NoSessions; + impl SessionStore for NoSessions { + fn exists(&self, _: &str) -> bool { + false + } + } + + fn args() -> AskArgs { + AskArgs { + endpoint: DEFAULT_ENDPOINT.parse().unwrap(), + caller_id: "c".into(), + key_file: "/nonexistent".into(), + model: "m".into(), + instructions: "i".into(), + effort: None, + max_output_tokens: 16, + timeout: Duration::from_secs(1), + prompt: "p".into(), + } + } + + /// The claude backend's own planner accepts what `ask` builds and refuses + /// the same request once a tool is forced into it. + #[test] + fn the_backend_planner_refuses_a_forced_tool_and_accepts_the_asked_request() { + let config = ClaudeCodeConfig { + provider_id: "claude-code".into(), + claude_binary: "/claude".into(), + claude_binary_sha256: [0; 32], + work_dir: "/w".into(), + config_dir: "/c".into(), + prompt_dir: "/p".into(), + token_credential: "t".into(), + handle_secret_credential: "h".into(), + instance: "i".into(), + meter_model: None, + limits: ClaudeCodeLimits { + deadline: Duration::from_secs(1), + max_line_bytes: 1024, + max_total_bytes: 4096, + stderr_tail_bytes: 64, + }, + }; + let mut request = build_invocation(&args()).unwrap().request; + let secret = [7_u8; 32]; + assert!(plan(&request, &config, &secret, "c", &NoSessions).is_ok()); + request.tools.push(ToolDefinition { + name: "t".into(), + description: "d".into(), + parameters_json: "{}".into(), + }); + assert!(plan(&request, &config, &secret, "c", &NoSessions).is_err()); + } +} diff --git a/crates/claude-connector/src/backend.rs b/crates/claude-connector/src/backend.rs index 0bc2d77..48dcb1c 100644 --- a/crates/claude-connector/src/backend.rs +++ b/crates/claude-connector/src/backend.rs @@ -1,17 +1,17 @@ use std::fs::File; use std::io; -use std::path::PathBuf; use std::sync::Arc; use std::time::Instant; use model_connector::{ - FailureKind, InputItem, PlanQuotaSnapshot, ProviderBackend, ProviderCall, ProviderRequest, - TransportEvent, TransportEventPayload, TransportOutcome, TransportResult, Usage, + FailureKind, InputItem, PlanQuotaSnapshot, ProviderRequest, ToolChoice, TransportEvent, + TransportEventPayload, TransportOutcome, Usage, }; use sha2::{Digest, Sha256}; use zeroize::Zeroizing; -use crate::config::{ClaudeCodeConfig, PROVIDER}; +use crate::config::{ClaudeCodeConfig, ModelRow, OutputSchemaSupport}; +use crate::credential::{CredentialTokenSource, TokenSource, credential_ready}; use crate::handle::{ Binding, ClaudeCodeHandle, MIN_SECRET_BYTES, SessionStore, plan, prefix_digest, stdin_bytes, }; @@ -20,81 +20,9 @@ use crate::process::{ProcessPort, RunningChild, StdoutRead}; use crate::quota::QuotaCell; use crate::stream::{Failure, Finished, Step, StreamState}; -/// The meter's call: the cheapest model, a trivial prompt, and an answer cap -/// that only bounds a runaway. -const METER_MODEL: &str = "claude-haiku-5-5"; const METER_CALLER: &str = "meter"; const METER_MAX_OUTPUT_TOKENS: u32 = 16; -/// Where the child's credential comes from, read afresh at every use. The -/// connector's own environment is never a source (ruling -/// claude-connector-token-credential). -pub trait TokenSource: Send + Sync { - /// The token, or `None` when there is none or it is empty. - fn read(&self) -> Option>; - /// What `config check` names when `read` has no token. - fn missing(&self) -> &'static str { - "token_credential" - } -} - -/// A token in a file named by a systemd credential: the file -/// `$CREDENTIALS_DIRECTORY/`, read on every call so a rotated credential -/// is picked up by the next spawn. -pub struct CredentialTokenSource { - directory: Option, - name: String, - /// The configuration field `missing` names when the credential is absent. - field: &'static str, -} - -impl CredentialTokenSource { - /// The credential `name` under the directory systemd names in - /// `CREDENTIALS_DIRECTORY`; with no such variable the source has no token. - /// The variable names a directory, never a token. - pub fn from_environment(name: impl Into) -> Self { - Self { - directory: std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from), - name: name.into(), - field: "token_credential", - } - } - - /// The same source, naming `field` when its credential is absent. - pub fn for_field(mut self, field: &'static str) -> Self { - self.field = field; - self - } - - pub fn in_directory(directory: impl Into, name: impl Into) -> Self { - Self { - directory: Some(directory.into()), - name: name.into(), - field: "token_credential", - } - } -} - -impl TokenSource for CredentialTokenSource { - fn read(&self) -> Option> { - let directory = self.directory.as_ref()?; - let mut token = Zeroizing::new(std::fs::read_to_string(directory.join(&self.name)).ok()?); - let trimmed = token.trim_end_matches(['\r', '\n']).len(); - token.truncate(trimmed); - (!token.is_empty()).then_some(token) - } - - /// No directory at all is the unit's environment lacking its credentials, - /// which is not the same fault as a credential the directory lacks. - fn missing(&self) -> &'static str { - if self.directory.is_none() { - "credentials_directory" - } else { - self.field - } - } -} - /// Where the tail of a child's stderr goes. The backend never puts it in a /// result; the connector binary wires this to its log. pub trait StderrSink: Send + Sync { @@ -157,27 +85,50 @@ impl ClaudeCodeBackend { } } + /// Provider tag written on receipts and matched on reasoning state items. + pub fn provider_id(&self) -> &str { + &self.config.provider_id + } + + /// Whether the backend can take work, naming the first config field that + /// cannot be used. + pub fn ready(&self) -> Result<(), &'static str> { + readiness( + &self.config, + self.tokens.as_ref(), + self.handle_secret.as_ref(), + ) + } + /// The plan windows every stream this backend reads feeds. pub fn quota(&self) -> Arc { self.quota.clone() } + /// Latest plan quota snapshot paired with this backend's provider id. + pub fn plan_quota(&self) -> (&str, PlanQuotaSnapshot) { + (&self.config.provider_id, self.quota.snapshot()) + } + /// The meter's call: the smallest real one, through the same child, /// stream and cell as any other. The stream's `rate_limit_event` is what /// the caller wants; this returns what the call billed, or the failure's /// kind (never its message). pub(crate) fn read_meter(&self) -> Result { + let Some(model) = self.config.meter_model.as_deref() else { + return Err("MissingMeterModel".to_string()); + }; let mut request = ProviderRequest::new( METER_CALLER, METER_CALLER, - METER_MODEL, + model, "Reply with the single word ok.", METER_MAX_OUTPUT_TOKENS, ); request.input = vec![InputItem::UserText { text: "ok?".to_string(), }]; - match self.run(&request, METER_CALLER, true).1 { + match self.run_inner(&request, METER_CALLER, None, true).1 { TransportOutcome::Completed { usage, .. } => Ok(usage), TransportOutcome::Failed { kind, .. } => Err(format!("{kind:?}")), } @@ -189,12 +140,54 @@ impl ClaudeCodeBackend { binary_matches_pin(&self.config) } - /// `ephemeral` leaves no transcript behind: the meter keeps no handle and - /// resumes nothing, every other call is resumed by its session. - fn run( + pub(crate) fn run_model( &self, request: &ProviderRequest, caller: &str, + row: &ModelRow, + ) -> (Vec, TransportOutcome) { + let effort = match row.resolve_effort(request.reasoning_effort) { + Ok(effort) => effort, + Err(message) => { + return failed( + FailureKind::InvalidRequest, + format!("{}: {message}", self.config.provider_id), + Some(zero_usage()), + ); + } + }; + if request.output_schema_json.is_some() && row.output_schema == OutputSchemaSupport::None { + return failed( + FailureKind::InvalidRequest, + format!( + "{}: model {} does not accept an output schema", + self.config.provider_id, row.id + ), + Some(zero_usage()), + ); + } + if request.tool_choice == ToolChoice::Required + && !row.allows_forced_tool_choice(ModelRow::thinking_active(effort)) + { + return failed( + FailureKind::InvalidRequest, + format!( + "{}: model {} does not accept a required tool choice", + self.config.provider_id, row.id + ), + Some(zero_usage()), + ); + } + self.run_inner(request, caller, effort, false) + } + + /// `ephemeral` leaves no transcript behind: the meter keeps no handle and + /// resumes nothing, every other call is resumed by its session. + fn run_inner( + &self, + request: &ProviderRequest, + caller: &str, + effort: Option<&str>, ephemeral: bool, ) -> (Vec, TransportOutcome) { let Some(secret) = usable_secret(self.handle_secret.as_ref()) else { @@ -239,7 +232,14 @@ impl ClaudeCodeBackend { "claude-code: the system prompt could not be staged", )); }; - let argv = argv(&self.config, request, &plan, prompt.path(), ephemeral); + let argv = argv( + &self.config, + request, + &plan, + prompt.path(), + effort, + ephemeral, + ); let env = child_env(&self.config, request); let deadline = Instant::now() + self.config.limits.deadline; @@ -261,7 +261,7 @@ impl ClaudeCodeBackend { deadline, &request.model, request.output_schema_json.as_deref(), - &self.quota, + Some(&*self.quota), ); child.kill(); child.wait(); @@ -339,35 +339,12 @@ impl ClaudeCodeBackend { } } -impl ProviderBackend for ClaudeCodeBackend { - fn ready(&self) -> Result<(), &'static str> { - readiness( - &self.config, - self.tokens.as_ref(), - self.handle_secret.as_ref(), - ) - } - - fn provider(&self) -> &str { - PROVIDER - } - - fn execute(&self, call: &ProviderCall) -> TransportResult { - let (events, outcome) = self.run(call.request(), call.caller_runtime_id(), false); - call.transported(events, outcome) - } - - fn plan_quota(&self) -> PlanQuotaSnapshot { - self.quota.snapshot() - } -} - fn read_stream( child: &mut dyn RunningChild, deadline: Instant, model: &str, schema: Option<&str>, - quota: &QuotaCell, + quota: Option<&QuotaCell>, ) -> Result { let mut state = StreamState::new(model, schema, quota); let finished = loop { @@ -435,9 +412,7 @@ pub(crate) fn readiness( if usable_secret(handle_secret).is_none() { return Err(handle_secret.missing()); } - if tokens.read().is_none() { - return Err(tokens.missing()); - } + credential_ready(tokens)?; Ok(()) } diff --git a/crates/claude-connector/src/backend/tests.rs b/crates/claude-connector/src/backend/tests.rs index ecd98fa..863cadb 100644 --- a/crates/claude-connector/src/backend/tests.rs +++ b/crates/claude-connector/src/backend/tests.rs @@ -5,16 +5,18 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use model_connector::{ - CallerAdmission, PlanQuotaSnapshot, ReasoningEffort, StopReason, ToolDefinition, + CallerAdmission, ProviderBackend, ProviderRoutes, ReasoningEffort, StopReason, ToolDefinition, TransportAdmission, TransportDisposition, TransportInvocation, TransportKey, TransportReceipt, - TransportService, decrypt_result, encrypt_invocation, + TransportResult, TransportService, decrypt_result, encrypt_invocation, }; use super::*; -use crate::config::ClaudeCodeLimits; +use crate::config::{ClaudeCodeLimits, EffortMap, ForcedToolChoice, ModelRow, OutputSchemaSupport}; use crate::handle::{FsSessionStore, SessionStore}; use crate::launch::ChildEnv; +use crate::router::RouterBackend; +const PROVIDER: &str = "claude-code"; const CANARY_TOKEN: &str = "canary-oauth-token-value"; /// The variable the connector's own environment must never hand on. const TOKEN_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN"; @@ -325,8 +327,27 @@ fn sandbox() -> TempDir { dir } +fn default_row(id: &str) -> ModelRow { + ModelRow { + id: id.to_string(), + provider: PROVIDER.to_string(), + upstream: id.to_string(), + efforts: EffortMap { + low: Some("low".to_string()), + medium: Some("medium".to_string()), + high: Some("high".to_string()), + max: Some("max".to_string()), + }, + unset_effort: None, + forced_tool_choice: ForcedToolChoice::Never, + output_schema: OutputSchemaSupport::Native, + strict_tools: false, + } +} + fn config(dir: &Path, instance: &str, limits: ClaudeCodeLimits) -> ClaudeCodeConfig { ClaudeCodeConfig { + provider_id: PROVIDER.to_string(), claude_binary: dir.join("claude"), claude_binary_sha256: pin_of(PINNED), work_dir: PathBuf::from("/work"), @@ -335,6 +356,7 @@ fn config(dir: &Path, instance: &str, limits: ClaudeCodeLimits) -> ClaudeCodeCon token_credential: "claude-token".to_string(), handle_secret_credential: "claude-handle-secret".to_string(), instance: instance.to_string(), + meter_model: Some(MODEL.to_string()), limits, } } @@ -383,7 +405,8 @@ fn limits() -> ClaudeCodeLimits { struct Rig { dir: TempDir, - backend: ClaudeCodeBackend, + backend: Arc, + router: RouterBackend, spawns: Arc, seen: Arc>, sink: Sink, @@ -410,17 +433,25 @@ fn rig_with_secret( stderr: stderr.to_vec(), }; let dir = sandbox(); - let backend = ClaudeCodeBackend::with_ports( + let backend = Arc::new(ClaudeCodeBackend::with_ports( config(dir.path(), instance, limits()), Box::new(port), Box::new(Sessions(sessions.iter().map(|s| s.to_string()).collect())), Box::new(sink.clone()), canary_token(), Box::new(FixedSecret(secret)), - ); + )); + let router = RouterBackend::from_backends( + [], + [], + Some(backend.clone()), + vec![default_row(MODEL), default_row(OTHER_MODEL)], + ) + .unwrap(); Rig { dir, backend, + router, spawns, seen, sink, @@ -438,7 +469,7 @@ impl Rig { fn run_as(&self, caller: &str, request: ProviderRequest) -> TransportResult { let mut door = Door::new(); let (claim, _) = door.begin_as(caller, request); - self.backend.execute(claim.call()) + self.router.execute(claim.call()) } fn seen(&self) -> Seen { self.seen.lock().unwrap().clone() @@ -480,8 +511,13 @@ impl Door { ) .unwrap() }); + let routes = ProviderRoutes::new([ + (MODEL.to_string(), PROVIDER.to_string()), + (OTHER_MODEL.to_string(), PROVIDER.to_string()), + ]) + .unwrap(); let service = - TransportService::open(&dir.join("replay.cc"), PROVIDER, callers, 5_000).unwrap(); + TransportService::open(&dir.join("replay.cc"), routes, callers, 5_000).unwrap(); Self { dir, service } } @@ -500,11 +536,7 @@ impl Door { let key = TransportKey::from_connection_secret(&format!("{caller}-key")).unwrap(); let invocation = TransportInvocation::new(caller, 2_000, [7; 32], request).unwrap(); let envelope = encrypt_invocation(&invocation, &key).unwrap(); - match self - .service - .begin(&envelope, 1_000, &PlanQuotaSnapshot::default(), FRAME) - .unwrap() - { + match self.service.begin(&envelope, 1_000, None, FRAME).unwrap() { TransportAdmission::Execute(claim) => (*claim, invocation), TransportAdmission::Reply(_) => panic!("the door answered instead of admitting"), } @@ -620,6 +652,169 @@ fn reasoning_effort_is_passed_as_its_level() { } } +#[test] +fn cli_parameterized_id_efforts_output_schema_and_meter_model() { + let spawns = Arc::new(AtomicUsize::new(0)); + let seen = Arc::new(Mutex::new(Seen::default())); + let dir = sandbox(); + let mut cfg = config(dir.path(), INSTANCE, limits()); + cfg.provider_id = "custom-cli-id".to_string(); + cfg.meter_model = Some("custom-meter-wire".to_string()); + + let mut row = ModelRow { + id: MODEL.to_string(), + provider: "custom-cli-id".to_string(), + upstream: "wire-cli-model".to_string(), + efforts: EffortMap { + low: Some("lo-wire".to_string()), + medium: None, + high: Some("hi-wire".to_string()), + max: None, + }, + unset_effort: Some("unset-wire".to_string()), + forced_tool_choice: ForcedToolChoice::Never, + output_schema: OutputSchemaSupport::None, + strict_tools: false, + }; + + let backend = ClaudeCodeBackend::with_ports( + cfg.clone(), + Box::new(ScriptedPort { + scripts: Mutex::new( + vec![ + Script::lines(vec![ + init_line("wire-cli-model", SESSION), + text_line("m1", "hi"), + result_line("end_turn", USAGE), + ]), + Script::lines(vec![ + init_line("wire-cli-model", FORK), + text_line("m2", "hi2"), + result_line("end_turn", USAGE), + ]), + Script::lines(vec![ + init_line("wire-cli-model", FORK), + text_line("m2b", "hi2b"), + result_line("end_turn", USAGE), + ]), + Script::lines(vec![ + init_line("custom-meter-wire", SESSION), + text_line("m3", "ok"), + result_line("end_turn", USAGE), + ]), + ] + .into(), + ), + spawns: spawns.clone(), + seen: seen.clone(), + stderr: Vec::new(), + }), + Box::new(Sessions(vec![SESSION.to_string()])), + Box::new(Sink::default()), + canary_token(), + Box::new(FixedSecret(Some(SECRET))), + ); + + assert_eq!(backend.plan_quota().0, "custom-cli-id"); + + // 1. Unmapped ReasoningEffort refuses before spawn. + let mut unmapped = request(vec![user("hello")]); + unmapped.reasoning_effort = Some(ReasoningEffort::Medium); + let (_, outcome_unmapped) = backend.run_model(&unmapped, CALLER_1, &row); + assert!(matches!( + outcome_unmapped, + TransportOutcome::Failed { + kind: FailureKind::InvalidRequest, + .. + } + )); + assert_eq!(spawns.load(Ordering::SeqCst), 0); + + // 2. OutputSchemaSupport::None refuses output_schema_json before spawn. + let mut with_schema = request(vec![user("hello")]); + with_schema.output_schema_json = Some(SCHEMA.to_string()); + let (_, outcome_schema) = backend.run_model(&with_schema, CALLER_1, &row); + assert!(matches!( + outcome_schema, + TransportOutcome::Failed { + kind: FailureKind::InvalidRequest, + .. + } + )); + assert_eq!(spawns.load(Ordering::SeqCst), 0); + + // 3. Mapped effort passes custom wire string; unset_effort applies when request effort is None. + let mut wire_req = request(vec![user("hello")]); + wire_req.model = row.upstream.clone(); + wire_req.reasoning_effort = Some(ReasoningEffort::Low); + let (_, outcome_low) = backend.run_model(&wire_req, CALLER_1, &row); + assert!(matches!(outcome_low, TransportOutcome::Completed { .. })); + assert_eq!( + arg_after(&seen.lock().unwrap().argv, "--effort"), + Some("lo-wire") + ); + + let mut unset_req = request(vec![user("hello")]); + unset_req.model = row.upstream.clone(); + unset_req.reasoning_effort = None; + let (_, outcome_unset) = backend.run_model(&unset_req, CALLER_1, &row); + assert!(matches!(outcome_unset, TransportOutcome::Completed { .. })); + assert_eq!( + arg_after(&seen.lock().unwrap().argv, "--effort"), + Some("unset-wire") + ); + + // 4. ForcedToolChoice::Never refuses ToolChoice::Required before spawn; Always allows it. + let mut forced_req = request(vec![user("hello")]); + forced_req.model = row.upstream.clone(); + forced_req.tool_choice = model_connector::ToolChoice::Required; + let (_, outcome_forced_never) = backend.run_model(&forced_req, CALLER_1, &row); + assert!(matches!( + outcome_forced_never, + TransportOutcome::Failed { + kind: FailureKind::InvalidRequest, + ref message, + .. + } if message.contains("required tool choice") + )); + assert_eq!(spawns.load(Ordering::SeqCst), 2); + + row.forced_tool_choice = ForcedToolChoice::Always; + let (_, outcome_forced_always) = backend.run_model(&forced_req, CALLER_1, &row); + assert!(matches!( + outcome_forced_always, + TransportOutcome::Completed { .. } + )); + assert_eq!(spawns.load(Ordering::SeqCst), 3); + + // 5. read_meter uses config.meter_model. + let meter_ok = backend.read_meter(); + assert!(meter_ok.is_ok(), "{meter_ok:?}"); + assert_eq!( + arg_after(&seen.lock().unwrap().argv, "--model"), + Some("custom-meter-wire") + ); + assert_eq!(spawns.load(Ordering::SeqCst), 4); + + // 6. read_meter returns Err("MissingMeterModel") when meter_model is None, without spawning. + cfg.meter_model = None; + let no_meter = ClaudeCodeBackend::with_ports( + cfg, + Box::new(ScriptedPort { + scripts: Mutex::new(VecDeque::new()), + spawns: spawns.clone(), + seen: seen.clone(), + stderr: Vec::new(), + }), + Box::new(Sessions(vec![])), + Box::new(Sink::default()), + canary_token(), + Box::new(FixedSecret(Some(SECRET))), + ); + assert_eq!(no_meter.read_meter().unwrap_err(), "MissingMeterModel"); + assert_eq!(spawns.load(Ordering::SeqCst), 4); +} + #[test] fn resume_always_forks() { let rig = rig(vec![ok_script(SESSION, "hi"), ok_script(FORK, "again")]); @@ -674,6 +869,15 @@ fn child_env_is_cleared_and_names_the_token_descriptor_never_the_token() { assert!(!format!("{result:?}").contains(CANARY_TOKEN)); } +#[test] +fn the_cell_is_fed_and_the_oauth_descriptor_named() { + let rig = rig(vec![structured_script()]); + rig.run(schema_request()); + assert!(!quota_of(&rig).windows.is_empty()); + let seen = rig.seen(); + assert!(seen.env.iter().any(|(name, _)| name == TOKEN_FD_ENV)); +} + #[test] fn the_token_never_reaches_a_message_an_event_or_a_debug_form() { // A failing run, so a message is built, and the env's own Debug. @@ -1005,7 +1209,7 @@ fn token_comes_from_the_credential_file_not_the_environment() { let mut config = config(dir.path(), INSTANCE, limits()); config.work_dir = dir.path().join("work"); config.config_dir = dir.path().join("cfg"); - let backend = ClaudeCodeBackend::with_ports( + let backend = Arc::new(ClaudeCodeBackend::with_ports( config, Box::new(ScriptedPort { scripts: Mutex::new(vec![ok_script(SESSION, "x")].into()), @@ -1020,13 +1224,16 @@ fn token_comes_from_the_credential_file_not_the_environment() { "claude-token", )), canary_secret(), - ); + )); + let router = + RouterBackend::from_backends([], [], Some(backend.clone()), vec![default_row(MODEL)]) + .unwrap(); let mut door = Door::new(); // The variable is set and the file is absent: nothing to give the child. assert_eq!(backend.ready(), Err("token_credential")); let (claim, _) = door.begin(request(vec![user("hi")])); - let (kind, message, usage) = failure_of(&backend.execute(claim.call())); + let (kind, message, usage) = failure_of(&router.execute(claim.call())); assert_eq!(kind, FailureKind::Authentication); assert_eq!(usage, Some(usage_zero())); assert!(!message.contains("canary-environment-token")); @@ -1042,7 +1249,7 @@ fn token_comes_from_the_credential_file_not_the_environment() { assert_eq!(backend.ready(), Ok(())); let mut door = Door::new(); let (claim, _) = door.begin(request(vec![user("hi")])); - let result = backend.execute(claim.call()); + let result = router.execute(claim.call()); assert!(matches!( outcome(&result), TransportOutcome::Completed { .. } @@ -1640,12 +1847,31 @@ fn one_spawn_per_execute() { #[test] fn a_missing_token_fails_before_spawn() { - let mut rig = rig(vec![ok_script(SESSION, "x")]); - rig.backend.tokens = Box::new(FixedToken(None)); - let (kind, _, usage) = failure_of(&rig.run(request(vec![user("hi")]))); - assert_eq!(kind, FailureKind::Authentication); - assert_eq!(usage, Some(usage_zero())); - assert_eq!(rig.spawns(), 0); + let spawns = Arc::new(AtomicUsize::new(0)); + let dir = sandbox(); + let backend = ClaudeCodeBackend::with_ports( + config(dir.path(), INSTANCE, limits()), + Box::new(ScriptedPort { + scripts: Mutex::new(vec![ok_script(SESSION, "x")].into()), + spawns: spawns.clone(), + seen: Arc::new(Mutex::new(Seen::default())), + stderr: Vec::new(), + }), + Box::new(Sessions(vec![SESSION.to_string()])), + Box::new(Sink::default()), + Box::new(FixedToken(None)), + canary_secret(), + ); + let (_, outcome) = backend.run_model(&request(vec![user("hi")]), CALLER_1, &default_row(MODEL)); + assert!(matches!( + &outcome, + TransportOutcome::Failed { + kind: FailureKind::Authentication, + usage: Some(u), + .. + } if *u == usage_zero() + )); + assert_eq!(spawns.load(Ordering::SeqCst), 0); } #[test] @@ -1664,17 +1890,19 @@ fn a_port_that_cannot_spawn_is_a_provider_failure() { } } let dir = sandbox(); - let backend = ClaudeCodeBackend::with_ports( + let backend = Arc::new(ClaudeCodeBackend::with_ports( config(dir.path(), INSTANCE, limits()), Box::new(Refusing), Box::new(Sessions(vec![])), Box::new(Sink::default()), canary_token(), canary_secret(), - ); + )); + let router = + RouterBackend::from_backends([], [], Some(backend), vec![default_row(MODEL)]).unwrap(); let mut door = Door::new(); let (claim, _) = door.begin(request(vec![user("hi")])); - let result = backend.execute(claim.call()); + let result = router.execute(claim.call()); let (kind, message, usage) = failure_of(&result); assert_eq!(kind, FailureKind::Provider); assert_eq!( @@ -1693,7 +1921,7 @@ fn backend_end_to_end_through_the_service() { let rig = rig(vec![ok_script(SESSION, "hello back")]); let mut door = Door::new(); let (claim, invocation) = door.begin(request(vec![user("hello")])); - let result = rig.backend.execute(claim.call()); + let result = rig.router.execute(claim.call()); let sealed = door.service.complete(claim, result, FRAME).unwrap(); let opened = decrypt_result( &sealed, @@ -1952,11 +2180,6 @@ fn pin_is_checked_before_every_spawn() { assert_eq!(rig.spawns(), 2); } -#[test] -fn the_provider_tag_is_claude_code() { - assert_eq!(rig(vec![]).backend.provider(), "claude-code"); -} - // ---- the session store ---- #[test] @@ -2108,12 +2331,23 @@ fn only_the_structured_output_tool_is_allowed_and_only_when_a_schema_was_sent() } fn quota_of(rig: &Rig) -> model_connector::PlanQuotaSnapshot { - rig.backend.plan_quota() + let (provider, snapshot) = rig.backend.plan_quota(); + assert_eq!(provider, PROVIDER); + snapshot } /// The windows with their observation stamps zeroed, for comparing readings. fn readings(rig: &Rig) -> Vec { - let mut windows = quota_of(rig).windows; + readings_at(rig, None) +} + +/// The held windows as of `now` (unix ms), or as of the wall clock when none. +fn readings_at(rig: &Rig, now: Option) -> Vec { + let cell = rig.backend.quota(); + let mut windows = match now { + Some(now) => cell.snapshot_at(now).windows, + None => cell.snapshot().windows, + }; for window in &mut windows { window.observed_at_unix_ms = 0; } @@ -2214,7 +2448,7 @@ mod real { struct Fake { _guard: std::sync::MutexGuard<'static, ()>, dir: TempDir, - backend: ClaudeCodeBackend, + router: RouterBackend, sink: Sink, } @@ -2235,18 +2469,20 @@ mod real { config.work_dir = work; config.config_dir = cfg; let sink = Sink::default(); - let backend = ClaudeCodeBackend::with_ports( + let backend = Arc::new(ClaudeCodeBackend::with_ports( config.clone(), Box::new(crate::process::StdProcessPort::new(config.limits)), Box::new(FsSessionStore::new(config.config_dir.clone())), Box::new(sink.clone()), canary_token(), canary_secret(), - ); + )); + let router = + RouterBackend::from_backends([], [], Some(backend), vec![default_row(MODEL)]).unwrap(); Fake { _guard: guard, dir, - backend, + router, sink, } } @@ -2255,7 +2491,7 @@ mod real { fn run(&self, request: ProviderRequest) -> TransportResult { let mut door = Door::new(); let (claim, _) = door.begin(request); - self.backend.execute(claim.call()) + self.router.execute(claim.call()) } } @@ -2764,14 +3000,15 @@ fn the_meter_call_reads_the_week_from_a_real_captured_event() { .read_meter() .expect("the captured call completes"); assert_eq!((usage.input_tokens, usage.output_tokens), (384, 4)); - // 0.06 of the week used; it resets at 1794261600 (unix s). + // 0.06 of the week used; it resets at 1794261600 (unix s). Read as of an instant before + // that reset, so the captured event stays a live reading whatever the wall clock says. assert_eq!( - readings(&rig), + readings_at(&rig, Some(1_794_261_600_000 - 1)), vec![window("seven_day", 60, 1_794_261_600_000)] ); let argv = rig.seen().argv; let after = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone(); - assert_eq!(after("--model"), METER_MODEL); + assert_eq!(after("--model"), MODEL); assert_eq!(after("--tools"), "", "the call can use no tool"); assert!( argv.iter().any(|a| a == "--no-session-persistence"), diff --git a/crates/claude-connector/src/config.rs b/crates/claude-connector/src/config.rs index 9c0f239..139d393 100644 --- a/crates/claude-connector/src/config.rs +++ b/crates/claude-connector/src/config.rs @@ -1,14 +1,135 @@ use std::path::PathBuf; use std::time::Duration; -/// The provider tag the kit puts on every receipt and on the reasoning state -/// of this backend. It is distinct from any Messages-API backend's tag, so the -/// kit treats each backend's state as foreign to the other. -pub(crate) const PROVIDER: &str = "claude-code"; +use model_connector::ReasoningEffort; +use serde::{Deserialize, Serialize}; + +/// One configured provider entry in the connector's v3 config document. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProviderEntry { + /// Provider tag written on receipts and reasoning state items. + pub id: String, + /// Systemd credential name under `$CREDENTIALS_DIRECTORY`; `None` only for + /// a loopback HTTP `base_url`. + pub credential: Option, + pub wire: ProviderWire, +} + +/// Wire protocol and per-provider backend parameters for a [`ProviderEntry`]. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ProviderWire { + AnthropicMessages { + base_url: String, + deadline_ms: u64, + max_response_bytes: usize, + }, + OpenAiChat { + base_url: String, + strict_unsupported: Vec, + deadline_ms: u64, + max_response_bytes: usize, + }, + ClaudeCodeCli { + binary: PathBuf, + binary_sha256: [u8; 32], + work_dir: PathBuf, + config_dir: PathBuf, + prompt_dir: PathBuf, + handle_secret_credential: String, + instance: String, + deadline_ms: u64, + max_line_bytes: usize, + max_total_bytes: usize, + stderr_tail_bytes: usize, + meter_model: Option, + }, +} + +/// One caller-facing model routed to a [`ProviderEntry`]. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ModelRow { + /// Caller-facing model id named in `ProviderRequest.model` and `allowed_models`. + pub id: String, + /// Id of the [`ProviderEntry`] that serves this model. + pub provider: String, + /// Provider-side model name sent on the wire. + pub upstream: String, + pub efforts: EffortMap, + pub unset_effort: Option, + pub forced_tool_choice: ForcedToolChoice, + pub output_schema: OutputSchemaSupport, + pub strict_tools: bool, +} + +impl ModelRow { + pub(crate) fn resolve_effort( + &self, + requested: Option, + ) -> Result, String> { + match requested { + Some(effort) => self.efforts.get(effort).map(Some).ok_or_else(|| { + format!( + "model {} does not support reasoning effort {effort:?}", + self.id + ) + }), + None => Ok(self.unset_effort.as_deref()), + } + } + + pub(crate) fn thinking_active(effort: Option<&str>) -> bool { + effort.is_some_and(|level| level != "none") + } + + pub(crate) fn allows_forced_tool_choice(&self, thinking_active: bool) -> bool { + match self.forced_tool_choice { + ForcedToolChoice::Always => true, + ForcedToolChoice::WithoutThinking => !thinking_active, + ForcedToolChoice::Never => false, + } + } +} + +/// Maps each contract [`ReasoningEffort`] to the provider's wire value. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct EffortMap { + pub low: Option, + pub medium: Option, + pub high: Option, + pub max: Option, +} + +impl EffortMap { + pub fn get(&self, effort: ReasoningEffort) -> Option<&str> { + match effort { + ReasoningEffort::Low => self.low.as_deref(), + ReasoningEffort::Medium => self.medium.as_deref(), + ReasoningEffort::High => self.high.as_deref(), + ReasoningEffort::Max => self.max.as_deref(), + } + } +} + +/// Whether the model accepts `ToolChoice::Required` (`tool_choice: any` / `required`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ForcedToolChoice { + Always, + WithoutThinking, + Never, +} + +/// Whether the model natively enforces a request's output JSON schema. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum OutputSchemaSupport { + Native, + None, +} /// What the connector's binary hands the backend. Every path is absolute. #[derive(Debug, Clone)] pub struct ClaudeCodeConfig { + /// Provider tag written on receipts and reasoning state items. + pub provider_id: String, /// The `claude` executable. pub claude_binary: PathBuf, /// The SHA-256 the executable must have for [`ready`](model_connector::ProviderBackend::ready). @@ -22,7 +143,7 @@ pub struct ClaudeCodeConfig { /// A directory the connector owns (mode 0700), where each call's system /// prompt is staged for the child. pub prompt_dir: PathBuf, - /// The name of the systemd credential that holds the child's token, under + /// The name of the systemd credential that holds the child's subscription token, under /// `$CREDENTIALS_DIRECTORY`. pub token_credential: String, /// The name of the systemd credential that holds the handle secret: the @@ -30,6 +151,8 @@ pub struct ClaudeCodeConfig { pub handle_secret_credential: String, /// The connector instance id written into every handle. pub instance: String, + /// Upstream model name used for the subscription plan meter's minimal call. + pub meter_model: Option, pub limits: ClaudeCodeLimits, } diff --git a/crates/claude-connector/src/credential.rs b/crates/claude-connector/src/credential.rs new file mode 100644 index 0000000..e277f02 --- /dev/null +++ b/crates/claude-connector/src/credential.rs @@ -0,0 +1,88 @@ +use std::path::{Path, PathBuf}; + +use zeroize::Zeroizing; + +/// Where a backend's or lease lender's credential comes from, read afresh at +/// every use. The connector's own environment is never a source (ruling +/// claude-connector-token-credential). +pub trait TokenSource: Send + Sync { + /// The token, or `None` when there is none or it is empty. + fn read(&self) -> Option>; + /// What `config check` names when `read` has no token. + fn missing(&self) -> &'static str { + "token_credential" + } +} + +/// A token in a file named by a systemd credential: the file +/// `$CREDENTIALS_DIRECTORY/`, read on every call so a rotated credential +/// is picked up by the next use. +pub struct CredentialTokenSource { + directory: Option, + name: String, + /// The configuration field `missing` names when the credential is absent. + field: &'static str, +} + +impl CredentialTokenSource { + /// The credential `name` under the directory systemd names in + /// `CREDENTIALS_DIRECTORY`; with no such variable the source has no token. + /// The variable names a directory, never a token. + pub fn from_environment(name: impl Into) -> Self { + Self { + directory: std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from), + name: name.into(), + field: "token_credential", + } + } + + /// The same source, naming `field` when its credential is absent. + pub fn for_field(mut self, field: &'static str) -> Self { + self.field = field; + self + } + + pub fn in_directory(directory: impl Into, name: impl Into) -> Self { + Self { + directory: Some(directory.into()), + name: name.into(), + field: "token_credential", + } + } + + pub(crate) fn in_optional_directory(directory: Option<&Path>, name: impl Into) -> Self { + Self { + directory: directory.map(Path::to_path_buf), + name: name.into(), + field: "token_credential", + } + } +} + +impl TokenSource for CredentialTokenSource { + fn read(&self) -> Option> { + let directory = self.directory.as_ref()?; + let mut token = Zeroizing::new(std::fs::read_to_string(directory.join(&self.name)).ok()?); + let trimmed = token.trim_end_matches(['\r', '\n']).len(); + token.truncate(trimmed); + (!token.is_empty()).then_some(token) + } + + /// No directory at all is the unit's environment lacking its credentials, + /// which is not the same fault as a credential the directory lacks. + fn missing(&self) -> &'static str { + if self.directory.is_none() { + "credentials_directory" + } else { + self.field + } + } +} + +/// Checks whether `source` yields a non-empty credential without leaking it. +pub(crate) fn credential_ready(source: &dyn TokenSource) -> Result<(), &'static str> { + match source.read() { + Some(_) => Ok(()), + None => Err(source.missing()), + } +} diff --git a/crates/claude-connector/src/daemon.rs b/crates/claude-connector/src/daemon.rs index e64e473..86f4f41 100644 --- a/crates/claude-connector/src/daemon.rs +++ b/crates/claude-connector/src/daemon.rs @@ -4,49 +4,54 @@ //! them. Validation errors name a field and never echo a value. use std::collections::BTreeSet; -use std::net::{SocketAddr, TcpListener}; +use std::net::{IpAddr, SocketAddr, TcpListener}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::Duration; use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore}; use model_connector::{ - CallerAdmission, CallerConfig, LeaseTurn, MIN_PAYLOAD_BYTES, ProviderBackend, ServeError, - ServeLimits, ServiceError, TransportService, load_admissions, serve_service, + CallerAdmission, CallerConfig, LeaseScope, MAX_IDENTITY_BYTES, MIN_PAYLOAD_BYTES, + ProviderRoutes, ServeError, ServeLimits, ServiceError, TransportService, load_admissions, + serve_service, }; use serde::{Deserialize, Serialize}; use thiserror::Error; use crate::backend::readiness; +use crate::credential::{CredentialTokenSource, TokenSource, credential_ready}; #[cfg(target_os = "linux")] -use crate::lease::{LeaseCaller, LeaseLimits, serve_leases, user_uid}; -#[cfg(target_os = "linux")] -use crate::unit::SystemdUnits; +use crate::lease::{LeaseHolder, LeaseLimits, serve_leases, user_uid}; #[cfg(unix)] use crate::meter; +#[cfg(unix)] +use crate::router::RouterBackend; +#[cfg(target_os = "linux")] +use crate::unit::SystemdUnits; use crate::{ - ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource, StderrSink, + ClaudeCodeConfig, ClaudeCodeLimits, ModelRow, ProviderEntry, ProviderWire, StderrSink, }; +#[cfg(unix)] +use crate::{MessagesConfig, OpenAiChatConfig}; const CONFIG_KEY: &str = "runtime"; -const MODEL_PREFIX: &str = "claude-"; -/// A unix account that may lease the subscription token for a Self run or a -/// Persona turn, the unit its process must run in (`mind-self@` -/// or `mind-persona@`, by `turn`), and the configured caller -/// whose name its leases carry. +/// A unix account that may lease the subscription token, the provider and full +/// systemd unit its process must run in, its exclusivity scope, and the +/// configured caller whose name its leases carry. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct LeaseCallerConfig { +pub struct LeaseHolderConfig { pub unix_user: String, pub caller_id: String, - /// The kind of turn this account leases for: it fixes the unit, `mind-self@` - /// or `mind-persona@`, its process must run in. - pub turn: LeaseTurn, - pub unit_instance: String, + pub provider: String, + pub unit: String, + /// Exclusivity scope of this holder's leases: one per caller or one per + /// unit invocation. + pub scope: LeaseScope, } #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "gamecult.model_connector.claude_connector_config.v2")] +#[cultcache(type = "gamecult.model_connector.connector_config.v3")] pub struct ClaudeConnectorConfig { /// A loopback socket address. #[cultcache(key = 0)] @@ -54,58 +59,35 @@ pub struct ClaudeConnectorConfig { #[cultcache(key = 1)] pub replay_store: PathBuf, #[cultcache(key = 2)] - pub claude_binary: PathBuf, - #[cultcache(key = 3)] - pub claude_binary_sha256: [u8; 32], - #[cultcache(key = 4)] - pub work_dir: PathBuf, - #[cultcache(key = 5)] - pub config_dir: PathBuf, - /// Where each call's system prompt is staged: a directory the connector - /// owns, mode 0700. - #[cultcache(key = 6)] - pub prompt_dir: PathBuf, - #[cultcache(key = 7)] - pub instance: String, - /// The name of the systemd credential that holds the child's token. - #[cultcache(key = 8)] - pub token_credential: String, - #[cultcache(key = 9)] - pub deadline_ms: u64, - #[cultcache(key = 10)] - pub max_line_bytes: usize, - #[cultcache(key = 11)] - pub max_total_bytes: usize, - #[cultcache(key = 12)] - pub stderr_tail_bytes: usize, - #[cultcache(key = 13)] pub max_frame_bytes: usize, - #[cultcache(key = 14)] + #[cultcache(key = 3)] pub max_connections: usize, - #[cultcache(key = 15)] + #[cultcache(key = 4)] pub socket_timeout_ms: u64, - #[cultcache(key = 16)] + #[cultcache(key = 5)] pub max_expiry_skew_ms: u64, + /// Configured upstream providers; each carries its own credential and wire parameters. + #[cultcache(key = 6)] + pub providers: Vec, + /// Caller-facing models, each routed to a configured provider. + #[cultcache(key = 7)] + pub models: Vec, /// Every caller of this connector: its own connection key and epoch, models, /// concurrency, payload and output bounds. /// Ids are unique. Handles are bound to the caller that was given them. - #[cultcache(key = 17)] + #[cultcache(key = 8)] pub callers: Vec, - /// Where the Self-run lease socket is bound (a systemd RuntimeDirectory), + /// Where the credential lease socket is bound (a systemd RuntimeDirectory), /// or none when this connector lends no token. - #[cultcache(key = 19)] + #[cultcache(key = 9)] pub lease_socket: Option, /// The accounts allowed to lease, each bound to a configured caller. /// Empty exactly when `lease_socket` is none. - #[cultcache(key = 20)] - pub lease_callers: Vec, + #[cultcache(key = 10)] + pub lease_holders: Vec, /// The furthest a lease's expiry may lie from now. - #[cultcache(key = 21)] + #[cultcache(key = 11)] pub lease_max_ms: u64, - /// The name of the systemd credential that holds the handle secret (at - /// least 32 bytes), the key every handle is authenticated with. - #[cultcache(key = 22)] - pub handle_secret_credential: String, } /// A refusal. It names the field or stage that failed and nothing the @@ -123,6 +105,9 @@ pub enum ConfigError { /// Something the document names exists but cannot be used now. #[error("the configured {0} cannot be used")] Unusable(&'static str), + /// A configured provider entry exists but cannot be used now. + #[error("configured provider {id} field {field} cannot be used")] + UnusableEntry { id: String, field: &'static str }, /// The serve loop failed after it started. #[error("the serve loop failed at {0}")] Serving(&'static str), @@ -155,8 +140,8 @@ impl From for ConfigError { } impl ClaudeConnectorConfig { - /// The one validation: `config init`, `config check` and `serve` all pass - /// through it. Returns the listen address. + /// The one validation: `config init`, `config add-provider`, `config add-model`, + /// `config check`, and `serve` all pass through it. Returns the listen address. pub fn validate(&self) -> Result { let listen = self .listen @@ -164,38 +149,8 @@ impl ClaudeConnectorConfig { .ok() .filter(|address| address.ip().is_loopback()) .ok_or(ConfigError::Invalid("listen"))?; - let paths = [ - ("replay_store", &self.replay_store), - ("claude_binary", &self.claude_binary), - ("work_dir", &self.work_dir), - ("config_dir", &self.config_dir), - ("prompt_dir", &self.prompt_dir), - ]; - for (field, path) in paths { - if !path.is_absolute() { - return Err(ConfigError::Invalid(field)); - } - } - if self.claude_binary_sha256 == [0; 32] { - return Err(ConfigError::Invalid("claude_binary_sha256")); - } - if !is_trimmed_nonempty(&self.instance) { - return Err(ConfigError::Invalid("instance")); - } - if !is_credential_name(&self.token_credential) { - return Err(ConfigError::Invalid("token_credential")); - } - if !is_credential_name(&self.handle_secret_credential) - || self.handle_secret_credential == self.token_credential - { - return Err(ConfigError::Invalid("handle_secret_credential")); - } - if self.deadline_ms == 0 - || self.max_line_bytes == 0 - || self.max_total_bytes < self.max_line_bytes - || self.stderr_tail_bytes == 0 - { - return Err(ConfigError::Invalid("child limits")); + if !self.replay_store.is_absolute() { + return Err(ConfigError::Invalid("replay_store")); } if self.max_frame_bytes == 0 || self.max_connections == 0 @@ -204,6 +159,153 @@ impl ClaudeConnectorConfig { { return Err(ConfigError::Invalid("serve limits")); } + + if self.providers.is_empty() { + return Err(ConfigError::Invalid("providers")); + } + let mut provider_ids = BTreeSet::new(); + let mut credential_names = BTreeSet::new(); + let mut cli_provider: Option<&str> = None; + for entry in &self.providers { + if !is_valid_identity(&entry.id) || entry.id == "model-connector" { + return Err(ConfigError::Invalid("provider_id")); + } + if !provider_ids.insert(entry.id.as_str()) { + return Err(ConfigError::Invalid("providers")); + } + if let Some(credential) = &entry.credential { + if !is_credential_name(credential) { + return Err(ConfigError::Invalid("credential")); + } + if !credential_names.insert(credential.as_str()) { + return Err(ConfigError::Invalid("credential")); + } + } + match &entry.wire { + ProviderWire::AnthropicMessages { + base_url, + deadline_ms, + max_response_bytes, + } => { + let is_loopback = validate_base_url(base_url)?; + if !is_loopback && entry.credential.is_none() { + return Err(ConfigError::Invalid("credential")); + } + if *deadline_ms == 0 || *max_response_bytes == 0 { + return Err(ConfigError::Invalid("http limits")); + } + } + ProviderWire::OpenAiChat { + base_url, + strict_unsupported, + deadline_ms, + max_response_bytes, + } => { + let is_loopback = validate_base_url(base_url)?; + if !is_loopback && entry.credential.is_none() { + return Err(ConfigError::Invalid("credential")); + } + if *deadline_ms == 0 || *max_response_bytes == 0 { + return Err(ConfigError::Invalid("http limits")); + } + if strict_unsupported.iter().any(|kw| !is_trimmed_nonempty(kw)) { + return Err(ConfigError::Invalid("strict_unsupported")); + } + } + ProviderWire::ClaudeCodeCli { + binary, + binary_sha256, + work_dir, + config_dir, + prompt_dir, + handle_secret_credential, + instance, + deadline_ms, + max_line_bytes, + max_total_bytes, + stderr_tail_bytes, + meter_model, + } => { + if cli_provider.is_some() { + return Err(ConfigError::Invalid("providers")); + } + cli_provider = Some(entry.id.as_str()); + if entry.credential.is_none() { + return Err(ConfigError::Invalid("credential")); + } + for (field, path) in [ + ("claude_binary", binary), + ("work_dir", work_dir), + ("config_dir", config_dir), + ("prompt_dir", prompt_dir), + ] { + if !path.is_absolute() { + return Err(ConfigError::Invalid(field)); + } + } + if *binary_sha256 == [0; 32] { + return Err(ConfigError::Invalid("claude_binary_sha256")); + } + if !is_trimmed_nonempty(instance) { + return Err(ConfigError::Invalid("instance")); + } + if !is_credential_name(handle_secret_credential) + || !credential_names.insert(handle_secret_credential.as_str()) + { + return Err(ConfigError::Invalid("handle_secret_credential")); + } + if *deadline_ms == 0 + || *max_line_bytes == 0 + || *max_total_bytes < *max_line_bytes + || *stderr_tail_bytes == 0 + { + return Err(ConfigError::Invalid("child limits")); + } + if let Some(model) = meter_model + && !is_valid_identity(model) + { + return Err(ConfigError::Invalid("meter_model")); + } + } + } + } + + if self.models.is_empty() { + return Err(ConfigError::Invalid("models")); + } + let mut model_ids = BTreeSet::new(); + for model in &self.models { + if !is_valid_identity(&model.id) { + return Err(ConfigError::Invalid("model_id")); + } + if !model_ids.insert(model.id.as_str()) { + return Err(ConfigError::Invalid("models")); + } + if !provider_ids.contains(model.provider.as_str()) { + return Err(ConfigError::Invalid("model_provider")); + } + if !is_trimmed_nonempty(&model.upstream) { + return Err(ConfigError::Invalid("upstream")); + } + for effort in [ + &model.efforts.low, + &model.efforts.medium, + &model.efforts.high, + &model.efforts.max, + ] { + if let Some(value) = effort + && !is_trimmed_nonempty(value) + { + return Err(ConfigError::Invalid("efforts")); + } + } + if let Some(value) = &model.unset_effort + && !is_trimmed_nonempty(value) + { + return Err(ConfigError::Invalid("unset_effort")); + } + } + if self.callers.is_empty() { return Err(ConfigError::Invalid("callers")); } @@ -232,21 +334,27 @@ impl ClaudeConnectorConfig { } let mut seen = BTreeSet::new(); for model in &caller.allowed_models { - if !has_model_id_form(model) || !seen.insert(model.as_str()) { + if !model_ids.contains(model.as_str()) || !seen.insert(model.as_str()) { return Err(ConfigError::Invalid("allowed_models")); } } } - self.validate_leases()?; + self.validate_leases(cli_provider)?; Ok(listen) } - fn validate_leases(&self) -> Result<(), ConfigError> { + fn cli_entry(&self) -> Option<&ProviderEntry> { + self.providers + .iter() + .find(|entry| matches!(entry.wire, ProviderWire::ClaudeCodeCli { .. })) + } + + fn validate_leases(&self, cli_provider: Option<&str>) -> Result<(), ConfigError> { let Some(socket) = &self.lease_socket else { - return if self.lease_callers.is_empty() { + return if self.lease_holders.is_empty() { Ok(()) } else { - Err(ConfigError::Invalid("lease_callers")) + Err(ConfigError::Invalid("lease_holders")) }; }; if !socket.is_absolute() { @@ -255,42 +363,36 @@ impl ClaudeConnectorConfig { if self.lease_max_ms == 0 { return Err(ConfigError::Invalid("lease_max_ms")); } + let Some(cli_id) = cli_provider else { + return Err(ConfigError::Invalid("lease_socket")); + }; + let has_cli_meter_target = self.cli_entry().is_some_and(|entry| match &entry.wire { + ProviderWire::ClaudeCodeCli { meter_model, .. } => { + meter_model.is_some() || self.models.iter().any(|model| model.provider == cli_id) + } + _ => false, + }); + if !has_cli_meter_target { + return Err(ConfigError::Invalid("meter_model")); + } let mut users = BTreeSet::new(); - if self.lease_callers.is_empty() - || !self.lease_callers.iter().all(|lease| { + if self.lease_holders.is_empty() + || !self.lease_holders.iter().all(|lease| { is_trimmed_nonempty(&lease.unix_user) && self .callers .iter() .any(|caller| caller.caller_runtime_id == lease.caller_id) - && is_unit_instance(&lease.unit_instance) + && lease.provider == cli_id + && is_systemd_unit_name(&lease.unit) && users.insert(lease.unix_user.as_str()) }) { - return Err(ConfigError::Invalid("lease_callers")); + return Err(ConfigError::Invalid("lease_holders")); } Ok(()) } - fn backend_config(&self) -> ClaudeCodeConfig { - ClaudeCodeConfig { - claude_binary: self.claude_binary.clone(), - claude_binary_sha256: self.claude_binary_sha256, - work_dir: self.work_dir.clone(), - config_dir: self.config_dir.clone(), - prompt_dir: self.prompt_dir.clone(), - token_credential: self.token_credential.clone(), - handle_secret_credential: self.handle_secret_credential.clone(), - instance: self.instance.clone(), - limits: ClaudeCodeLimits { - deadline: Duration::from_millis(self.deadline_ms), - max_line_bytes: self.max_line_bytes, - max_total_bytes: self.max_total_bytes, - stderr_tail_bytes: self.stderr_tail_bytes, - }, - } - } - fn serve_limits(&self) -> ServeLimits { ServeLimits { max_frame_bytes: self.max_frame_bytes, @@ -301,47 +403,201 @@ impl ClaudeConnectorConfig { } } -/// The `` of a unit name, as plain as a systemd instance can be. -fn is_unit_instance(text: &str) -> bool { - !text.is_empty() - && text - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) +pub(crate) fn backend_config_for( + entry: &ProviderEntry, + models: &[ModelRow], +) -> Option { + let ProviderWire::ClaudeCodeCli { + binary, + binary_sha256, + work_dir, + config_dir, + prompt_dir, + handle_secret_credential, + instance, + deadline_ms, + max_line_bytes, + max_total_bytes, + stderr_tail_bytes, + meter_model, + } = &entry.wire + else { + return None; + }; + let token_credential = entry.credential.as_ref()?.clone(); + let meter_model = meter_model.clone().or_else(|| { + models + .iter() + .find(|model| model.provider == entry.id) + .map(|model| model.upstream.clone()) + }); + Some(ClaudeCodeConfig { + provider_id: entry.id.clone(), + claude_binary: binary.clone(), + claude_binary_sha256: *binary_sha256, + work_dir: work_dir.clone(), + config_dir: config_dir.clone(), + prompt_dir: prompt_dir.clone(), + token_credential, + handle_secret_credential: handle_secret_credential.clone(), + instance: instance.clone(), + meter_model, + limits: ClaudeCodeLimits { + deadline: Duration::from_millis(*deadline_ms), + max_line_bytes: *max_line_bytes, + max_total_bytes: *max_total_bytes, + stderr_tail_bytes: *stderr_tail_bytes, + }, + }) +} + +#[cfg(unix)] +pub(crate) fn messages_config_for(entry: &ProviderEntry) -> Option { + let ProviderWire::AnthropicMessages { + base_url, + deadline_ms, + max_response_bytes, + } = &entry.wire + else { + return None; + }; + Some(MessagesConfig { + provider_id: entry.id.clone(), + base_url: base_url.clone(), + key_credential: entry.credential.clone(), + deadline: Duration::from_millis(*deadline_ms), + max_response_bytes: *max_response_bytes, + }) +} + +#[cfg(unix)] +pub(crate) fn openai_chat_config_for(entry: &ProviderEntry) -> Option { + let ProviderWire::OpenAiChat { + base_url, + strict_unsupported, + deadline_ms, + max_response_bytes, + } = &entry.wire + else { + return None; + }; + Some(OpenAiChatConfig { + provider_id: entry.id.clone(), + base_url: base_url.clone(), + key_credential: entry.credential.clone(), + strict_unsupported: strict_unsupported.clone(), + deadline: Duration::from_millis(*deadline_ms), + max_response_bytes: *max_response_bytes, + }) +} + +/// A systemd service unit name: `name.service` or `name@instance.service`. +fn is_systemd_unit_name(text: &str) -> bool { + if text.len() > 256 { + return false; + } + let Some(stem) = text.strip_suffix(".service") else { + return false; + }; + let valid_part = |part: &str| { + !part.is_empty() + && !part.starts_with('.') + && !part.ends_with('.') + && !part.contains("..") + && part + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) + }; + match stem.split_once('@') { + Some((name, instance)) => { + !instance.contains('@') && valid_part(name) && valid_part(instance) + } + None => valid_part(stem), + } } fn is_trimmed_nonempty(text: &str) -> bool { !text.is_empty() && text.trim() == text } -/// The loose shape of a model id, only to catch typos: -/// `claude--`, then an optional `-` and an optional -/// `-YYYYMMDD`, the family lowercase letters. No shape can tell an alias from -/// a canonical id, so the known list is `allowed_models` itself; an alias that slips in fails its first -/// call, when the stream's `init.model` differs from the request. -fn has_model_id_form(model: &str) -> bool { - let Some(rest) = model.strip_prefix(MODEL_PREFIX) else { - return false; +fn is_valid_identity(text: &str) -> bool { + is_trimmed_nonempty(text) && text.len() <= MAX_IDENTITY_BYTES +} + +/// Accepts `https://` URLs and loopback-IP `http://` URLs; rejects userinfo, +/// query strings, fragments, whitespace, control characters, and trailing `/`. +/// Returns `Ok(true)` when the host is a loopback `IpAddr`, `Ok(false)` otherwise. +fn validate_base_url(url: &str) -> Result { + if url.is_empty() + || url.ends_with('/') + || url.chars().any(|c| c.is_whitespace() || c.is_control()) + || url.contains(['?', '#', '\\']) + { + return Err(ConfigError::Invalid("base_url")); + } + let (is_http, rest) = if let Some(rest) = url.strip_prefix("https://") { + (false, rest) + } else if let Some(rest) = url.strip_prefix("http://") { + (true, rest) + } else { + return Err(ConfigError::Invalid("base_url")); }; - let digits = |part: &str, most: usize| { - (1..=most).contains(&part.len()) && part.bytes().all(|byte| byte.is_ascii_digit()) + let (authority, path) = match rest.split_once('/') { + Some((authority, path)) => (authority, Some(path)), + None => (rest, None), }; - let date = |part: &str| part.len() == 8 && digits(part, 8); - let mut parts = rest.split('-'); - let family = parts.next().unwrap_or(""); - let tail: Vec<&str> = parts.collect(); - let Some((major, after)) = tail.split_first() else { - return false; + if authority.is_empty() || authority.contains('@') { + return Err(ConfigError::Invalid("base_url")); + } + if let Some(path) = path + && (path.is_empty() || path.split('/').any(str::is_empty)) + { + return Err(ConfigError::Invalid("base_url")); + } + let (host, port) = parse_authority(authority).ok_or(ConfigError::Invalid("base_url"))?; + if let Some(port) = port + && (port.is_empty() + || !port.bytes().all(|b| b.is_ascii_digit()) + || !port.parse::().is_ok_and(|p| p > 0)) + { + return Err(ConfigError::Invalid("base_url")); + } + let is_loopback = host.parse::().is_ok_and(|ip| ip.is_loopback()); + if is_http && !is_loopback { + return Err(ConfigError::Invalid("base_url")); + } + Ok(is_loopback) +} + +fn parse_authority(authority: &str) -> Option<(&str, Option<&str>)> { + if let Some(after_open) = authority.strip_prefix('[') { + let (host, rest) = after_open.split_once(']')?; + host.parse::().ok()?; + let port = if rest.is_empty() { + None + } else { + Some(rest.strip_prefix(':')?) + }; + return Some((host, port)); + } + if authority.contains(['[', ']']) { + return None; + } + let (host, port) = match authority.rsplit_once(':') { + Some((host, port)) => (host, Some(port)), + None => (authority, None), }; - let after_ok = match after { - [] => true, - [one] => digits(one, 2) || date(one), - [minor, last] => digits(minor, 2) && date(last), - _ => false, - }; - !family.is_empty() - && family.bytes().all(|byte| byte.is_ascii_lowercase()) - && digits(major, 2) - && after_ok + if host.is_empty() + || host.starts_with('.') + || host.ends_with('.') + || host.contains("..") + || !host + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-')) + { + return None; + } + Some((host, port)) } /// One file name under `$CREDENTIALS_DIRECTORY`, never a path. @@ -430,26 +686,74 @@ impl StderrSink for LogSink { } } +fn token_source_in( + creds_dir: Option<&Path>, + name: &str, + field: &'static str, +) -> Box { + Box::new(CredentialTokenSource::in_optional_directory(creds_dir, name).for_field(field)) +} + +fn entry_readiness(entry: &ProviderEntry, creds_dir: Option<&Path>) -> Result<(), ConfigError> { + match &entry.wire { + ProviderWire::ClaudeCodeCli { .. } => { + let backend = + backend_config_for(entry, &[]).ok_or_else(|| ConfigError::UnusableEntry { + id: entry.id.clone(), + field: "credential", + })?; + #[cfg(unix)] + check_prompt_dir(&backend.prompt_dir).map_err(|_| ConfigError::UnusableEntry { + id: entry.id.clone(), + field: "prompt_dir", + })?; + let tokens = token_source_in(creds_dir, &backend.token_credential, "credential"); + let handle_secret = token_source_in( + creds_dir, + &backend.handle_secret_credential, + "handle_secret_credential", + ); + readiness(&backend, tokens.as_ref(), handle_secret.as_ref()).map_err(|field| { + ConfigError::UnusableEntry { + id: entry.id.clone(), + field, + } + }) + } + ProviderWire::AnthropicMessages { .. } | ProviderWire::OpenAiChat { .. } => { + if let Some(credential) = &entry.credential { + let source = token_source_in(creds_dir, credential, "credential"); + credential_ready(source.as_ref()).map_err(|field| ConfigError::UnusableEntry { + id: entry.id.clone(), + field, + })?; + } + Ok(()) + } + } +} + /// Everything `serve` needs true before it binds, in one place so that /// `config check` passes exactly what `serve` will start: the prompt -/// directory, the other directories, the credential, the pin, the connection -/// key and the frame and connection bounds. Returns the admitted callers. +/// directory, the other directories, every entry's credential, the pin, the +/// connection key and the frame and connection bounds. Returns the admitted callers. fn readiness_of(config: &ClaudeConnectorConfig) -> Result, ConfigError> { + let creds_dir = std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from); + readiness_of_in(config, creds_dir.as_deref()) +} + +fn readiness_of_in( + config: &ClaudeConnectorConfig, + creds_dir: Option<&Path>, +) -> Result, ConfigError> { config.validate()?; - #[cfg(unix)] - check_prompt_dir(&config.prompt_dir)?; let admissions = load_admissions(&config.callers)?; config.serve_limits().validate(&admissions)?; - let backend = config.backend_config(); - readiness( - &backend, - &CredentialTokenSource::from_environment(backend.token_credential.clone()), - &CredentialTokenSource::from_environment(backend.handle_secret_credential.clone()) - .for_field("handle_secret_credential"), - ) - .map_err(ConfigError::Unusable)?; + for entry in &config.providers { + entry_readiness(entry, creds_dir)?; + } if config.lease_socket.is_some() { - lease_callers_of(config)?; + lease_holders_of(config)?; } Ok(admissions) } @@ -457,26 +761,27 @@ fn readiness_of(config: &ClaudeConnectorConfig) -> Result, /// The accounts allowed to lease, resolved to the uids the kernel will report /// for their connections. An account the system does not have is not ready. #[cfg(target_os = "linux")] -fn lease_callers_of(config: &ClaudeConnectorConfig) -> Result, ConfigError> { +fn lease_holders_of(config: &ClaudeConnectorConfig) -> Result, ConfigError> { config - .lease_callers + .lease_holders .iter() .map(|lease| { user_uid(&lease.unix_user) - .map(|uid| LeaseCaller { + .map(|uid| LeaseHolder { uid, caller_id: lease.caller_id.clone(), - turn: lease.turn, - unit_instance: lease.unit_instance.clone(), + provider: lease.provider.clone(), + unit: lease.unit.clone(), + scope: lease.scope, }) - .ok_or(ConfigError::Unusable("lease_callers")) + .ok_or(ConfigError::Unusable("lease_holders")) }) .collect() } -/// Peer credentials identify a lease caller only on Linux. +/// Peer credentials identify a lease holder only on Linux. #[cfg(not(target_os = "linux"))] -fn lease_callers_of(_: &ClaudeConnectorConfig) -> Result<(), ConfigError> { +fn lease_holders_of(_: &ClaudeConnectorConfig) -> Result<(), ConfigError> { Err(ConfigError::Unusable("lease_socket")) } @@ -494,7 +799,7 @@ fn start_leases( use std::os::unix::fs::{FileTypeExt, PermissionsExt}; use std::os::unix::net::UnixListener; - let callers = lease_callers_of(config)?; + let holders = lease_holders_of(config)?; // A socket a previous run left is replaced; anything else at the path is not ours. if std::fs::symlink_metadata(socket).is_ok_and(|found| found.file_type().is_socket()) { let _ = std::fs::remove_file(socket); @@ -507,15 +812,17 @@ fn start_leases( max_lease_ms: config.lease_max_ms, max_connections: config.max_connections, }; - let tokens = Arc::new(CredentialTokenSource::from_environment( - config.token_credential.clone(), - )); + let cli_cred = config + .cli_entry() + .and_then(|entry| entry.credential.as_ref()) + .ok_or(ConfigError::Unusable("providers"))?; + let tokens = Arc::new(CredentialTokenSource::from_environment(cli_cred.clone())); std::thread::Builder::new() .name("claude-lease-listener".to_string()) .spawn(move || { let _ = serve_leases( &listener, - callers, + holders, limits, service, quota, @@ -540,41 +847,69 @@ pub fn serve_config(path: &Path) -> Result<(), ConfigError> { serve_config_with(path, |_| ()) } +/// Maps every configured model to its configured provider entry id. +#[cfg(any(unix, test))] +fn routes_for(config: &ClaudeConnectorConfig) -> Result { + ProviderRoutes::new( + config + .models + .iter() + .map(|model| (model.id.clone(), model.provider.clone())), + ) + .map_err(|error| ConfigError::from(ServeError::Service(error))) +} + /// [`serve_config`] handing the quota cell to `started` once the meter runs: -/// a test stands in for the swarm's lease requests only through here. +/// a test stands in for lease requests only through here. #[cfg(unix)] fn serve_config_with( path: &Path, started: impl FnOnce(&Arc), +) -> Result<(), ConfigError> { + serve_bound_with(path, |_| (), started) +} + +#[cfg(unix)] +fn serve_bound_with( + path: &Path, + bound: impl FnOnce(SocketAddr), + started: impl FnOnce(&Arc), ) -> Result<(), ConfigError> { let config = load_config(path)?; let admissions = readiness_of(&config)?; let listen = config.validate()?; - let backend = Arc::new(ClaudeCodeBackend::new( - config.backend_config(), + let routes = routes_for(&config)?; + let router = Arc::new(RouterBackend::from_config( + &config, Box::new(LogSink(std::sync::Mutex::new(std::io::stderr()))), - )); + )?); let listener = TcpListener::bind(listen).map_err(|_| ConfigError::Listen)?; + bound(listener.local_addr().map_err(|_| ConfigError::Listen)?); let service = Arc::new(Mutex::new( TransportService::open( &config.replay_store, - backend.provider(), + routes, admissions, config.max_expiry_skew_ms, ) .map_err(|error| ConfigError::from(ServeError::Service(error)))?, )); // The meter is running before the first lease can ask, so that lease can - // wait for its first read. - let quota = backend.quota(); - meter::start(quota.clone(), Box::new(backend.clone())) - .map_err(|_| ConfigError::Serving("meter"))?; + // wait for its first read. When no ClaudeCodeCli entry is configured, no + // meter runs and the cell stays empty. + let quota = router + .cli_backend() + .map_or_else(|| Arc::new(crate::QuotaCell::new()), |c| c.quota()); + if let Some(claude) = router.cli_backend() { + meter::start(quota.clone(), Box::new(claude.clone())) + .map_err(|_| ConfigError::Serving("meter"))?; + } started("a); #[cfg(target_os = "linux")] if let Some(socket) = &config.lease_socket { start_leases(&config, socket, service.clone(), quota.clone())?; } - serve_service(listener, config.serve_limits(), service, backend)?; + serve_service(listener, config.serve_limits(), service, router)?; Ok(()) } @@ -585,6 +920,25 @@ mod tests { use sha2::Digest; use super::*; + use crate::{EffortMap, ForcedToolChoice, OutputSchemaSupport}; + + fn test_model(id: &str, provider: &str) -> ModelRow { + ModelRow { + id: id.to_string(), + provider: provider.to_string(), + upstream: id.to_string(), + efforts: EffortMap { + low: Some("low".to_string()), + medium: Some("medium".to_string()), + high: Some("high".to_string()), + max: Some("max".to_string()), + }, + unset_effort: None, + forced_tool_choice: ForcedToolChoice::Never, + output_schema: OutputSchemaSupport::Native, + strict_tools: false, + } + } /// A log that a test can read back. #[derive(Clone, Default)] @@ -600,6 +954,9 @@ mod tests { } } + #[cfg(unix)] + static CREDENTIALS_ENV_LOCK: Mutex<()> = Mutex::new(()); + /// `serve` starts the meter beside the listener, wired to the backend's own /// cell: it makes no call while nobody asks, and once a lease is asked for /// it runs the claude binary and serve stays up. The binary is a script @@ -609,6 +966,10 @@ mod tests { fn serve_config_starts_the_meter_and_stays_up() { use std::os::unix::fs::PermissionsExt; + let _env_guard = CREDENTIALS_ENV_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + const CALL: &str = include_str!("../tests/fixtures/claude-2.1.312-meter-call.jsonl"); let dir = std::env::temp_dir().join(format!("claude-connector-serve-{}", std::process::id())); @@ -632,33 +993,40 @@ mod tests { let config = ClaudeConnectorConfig { listen: "127.0.0.1:0".to_string(), replay_store: at("replay.cc"), - claude_binary: at("claude"), - claude_binary_sha256: sha2::Sha256::digest(script.as_bytes()).into(), - work_dir: at("work"), - config_dir: at("home"), - prompt_dir: at("prompts"), - instance: "persona-a".to_string(), - token_credential: "claude-token".to_string(), - handle_secret_credential: "claude-handle-secret".to_string(), - deadline_ms: 600_000, - max_line_bytes: 4 << 20, - max_total_bytes: 64 << 20, - stderr_tail_bytes: 8192, max_frame_bytes: 2 << 20, max_connections: 8, socket_timeout_ms: 10_000, max_expiry_skew_ms: 300_000, + providers: vec![ProviderEntry { + id: "cli-main".to_string(), + credential: Some("claude-token".to_string()), + wire: ProviderWire::ClaudeCodeCli { + binary: at("claude"), + binary_sha256: sha2::Sha256::digest(script.as_bytes()).into(), + work_dir: at("work"), + config_dir: at("home"), + prompt_dir: at("prompts"), + handle_secret_credential: "claude-handle-secret".to_string(), + instance: "persona-a".to_string(), + deadline_ms: 600_000, + max_line_bytes: 4 << 20, + max_total_bytes: 64 << 20, + stderr_tail_bytes: 8192, + meter_model: None, + }, + }], + models: vec![test_model("cli-test-model", "cli-main")], callers: vec![CallerConfig { caller_runtime_id: "persona-a-caller".to_string(), connection_key_file: at("caller.key"), connection_key_epoch: 1, - allowed_models: vec!["claude-haiku-5-5".to_string()], + allowed_models: vec!["cli-test-model".to_string()], max_concurrent_requests: 4, max_payload_bytes: 1 << 20, max_output_tokens: 32_768, }], lease_socket: None, - lease_callers: Vec::new(), + lease_holders: Vec::new(), lease_max_ms: 3_600_000, }; write_config(&at("connector.cc"), &config).unwrap(); @@ -668,10 +1036,10 @@ mod tests { let path = at("connector.cc"); let lease = std::sync::Arc::new(std::sync::Mutex::new(None)); - let swarm = lease.clone(); + let held_quota = lease.clone(); let served = std::thread::spawn(move || { serve_config_with(&path, |cell| { - *swarm.lock().unwrap() = Some(cell.clone()); + *held_quota.lock().unwrap() = Some(cell.clone()); }) }); @@ -684,7 +1052,7 @@ mod tests { std::thread::sleep(Duration::from_millis(20)); }; std::thread::sleep(Duration::from_millis(500)); - assert!(!at("spawned").exists(), "a quiet swarm spends nothing"); + assert!(!at("spawned").exists(), "an idle deployment spends nothing"); let _lease = cell.asking(); while !at("spawned").exists() { @@ -694,7 +1062,781 @@ mod tests { ); std::thread::sleep(Duration::from_millis(50)); } - assert!(!served.is_finished(), "serve returned after starting the meter"); + assert!( + !served.is_finished(), + "serve returned after starting the meter" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + struct SeenHttp { + x_api_key: Option, + authorization: Option, + body: serde_json::Value, + } + + #[cfg(unix)] + fn spawn_http_mock(responses: Vec) -> (String, Arc>>) { + use std::io::{Read, Write}; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let seen = Arc::new(Mutex::new(Vec::new())); + let seen_clone = seen.clone(); + std::thread::spawn(move || { + for response_json in responses { + let Ok((mut stream, _)) = listener.accept() else { + break; + }; + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + let mut header_end = None; + let mut content_len = 0usize; + loop { + let n = stream.read(&mut chunk).unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + if header_end.is_none() + && let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") + { + let end = pos + 4; + header_end = Some(end); + let headers = String::from_utf8_lossy(&buf[..pos]); + for line in headers.lines().skip(1) { + if let Some((k, v)) = line.split_once(':') + && k.eq_ignore_ascii_case("content-length") + { + content_len = v.trim().parse().unwrap_or(0); + } + } + } + if let Some(end) = header_end + && buf.len() >= end + content_len + { + break; + } + } + let end = header_end.unwrap_or(buf.len()); + let headers = String::from_utf8_lossy(&buf[..end]); + let header = |name: &str| { + headers.lines().skip(1).find_map(|line| { + let (k, v) = line.split_once(':')?; + k.eq_ignore_ascii_case(name).then(|| v.trim().to_string()) + }) + }; + let x_api_key = header("x-api-key"); + let authorization = header("authorization"); + let body: serde_json::Value = + serde_json::from_slice(&buf[end..end + content_len]).unwrap(); + seen_clone.lock().unwrap().push(SeenHttp { + x_api_key, + authorization, + body, + }); + let payload = response_json.to_string(); + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}", + payload.len(), + payload + ); + } + }); + (format!("http://{addr}"), seen) + } + + #[cfg(unix)] + fn invoke( + client: &model_connector::ConnectorClient, + caller: &str, + request_id: &str, + model: &str, + input: Vec, + ) -> model_connector::TransportResult { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as u64; + let mut req = model_connector::ProviderRequest::new( + request_id, + "conv-daemon-test", + model, + "Be brief.", + 1024, + ); + req.input = input; + let hash = model_connector::provider_request_sha256(&req).unwrap(); + let inv = + model_connector::TransportInvocation::new(caller, now + 60_000, hash, req).unwrap(); + let result = client.execute(&inv).unwrap(); + result.validate_against(&inv).unwrap(); + result + } + + #[cfg(unix)] + #[test] + fn two_anthropic_messages_loopback_fakes_and_keyless_route_independently() { + const SECRET_A: &str = "sk-canary-entry-a-1111"; + const SECRET_B: &str = "sk-canary-entry-b-2222"; + + let _env_guard = CREDENTIALS_ENV_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + + let dir = std::env::temp_dir().join(format!( + "claude-connector-multi-messages-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + let creds = dir.join("creds"); + std::fs::create_dir_all(&creds).unwrap(); + std::fs::write(creds.join("cred-a"), SECRET_A).unwrap(); + std::fs::write(creds.join("cred-b"), SECRET_B).unwrap(); + let key_file = dir.join("caller.key"); + let caller_secret = "k".repeat(48); + std::fs::write(&key_file, &caller_secret).unwrap(); + + let ok_reply = |id: &str, text: &str| { + serde_json::json!({ + "id": id, + "content": [{"type": "text", "text": text}], + "stop_reason": "end_turn", + "usage": {"input_tokens": 3, "output_tokens": 2} + }) + }; + let (url_a, seen_a) = spawn_http_mock(vec![ok_reply("m_a", "from a")]); + let (url_b, seen_b) = spawn_http_mock(vec![ok_reply("m_b", "from b")]); + let (url_local, seen_local) = spawn_http_mock(vec![ok_reply("m_l", "from local")]); + + let model_row = |id: &str, provider: &str, upstream: &str| ModelRow { + id: id.to_string(), + provider: provider.to_string(), + upstream: upstream.to_string(), + ..test_model(id, provider) + }; + + let config = ClaudeConnectorConfig { + listen: "127.0.0.1:0".to_string(), + replay_store: dir.join("replay.cc"), + max_frame_bytes: 2 << 20, + max_connections: 8, + socket_timeout_ms: 10_000, + max_expiry_skew_ms: 300_000, + providers: vec![ + ProviderEntry { + id: "msg-a".to_string(), + credential: Some("cred-a".to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: url_a, + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ProviderEntry { + id: "msg-b".to_string(), + credential: Some("cred-b".to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: url_b, + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ProviderEntry { + id: "msg-local".to_string(), + credential: None, + wire: ProviderWire::AnthropicMessages { + base_url: url_local, + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ], + models: vec![ + model_row("alias-a", "msg-a", "upstream-model-a"), + model_row("alias-b", "msg-b", "upstream-model-b"), + model_row("alias-local", "msg-local", "upstream-model-local"), + ], + callers: vec![CallerConfig { + caller_runtime_id: "caller-multi".to_string(), + connection_key_file: key_file, + connection_key_epoch: 1, + allowed_models: vec![ + "alias-a".to_string(), + "alias-b".to_string(), + "alias-local".to_string(), + ], + max_concurrent_requests: 4, + max_payload_bytes: 1 << 20, + max_output_tokens: 32_768, + }], + lease_socket: None, + lease_holders: Vec::new(), + lease_max_ms: 3_600_000, + }; + let cfg_path = dir.join("connector.cc"); + write_config(&cfg_path, &config).unwrap(); + // SAFETY: guarded by CREDENTIALS_ENV_LOCK across all in-process tests touching CREDENTIALS_DIRECTORY. + unsafe { std::env::set_var("CREDENTIALS_DIRECTORY", &creds) }; + + let (addr_tx, addr_rx) = std::sync::mpsc::channel(); + let cfg_thread = cfg_path.clone(); + std::thread::spawn(move || { + let _ = serve_bound_with( + &cfg_thread, + |addr| { + let _ = addr_tx.send(addr); + }, + |_| (), + ); + }); + let endpoint = addr_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let client = model_connector::ConnectorClient::new( + endpoint, + &caller_secret, + 2 << 20, + Some(Duration::from_secs(5)), + ) + .unwrap(); + + let user_msg = vec![model_connector::InputItem::UserText { + text: "hello".to_string(), + }]; + let res_a = invoke( + &client, + "caller-multi", + "req-a", + "alias-a", + user_msg.clone(), + ); + let res_b = invoke( + &client, + "caller-multi", + "req-b", + "alias-b", + user_msg.clone(), + ); + let res_l = invoke(&client, "caller-multi", "req-l", "alias-local", user_msg); + + for (res, expected_provider, expected_model) in [ + (&res_a, "msg-a", "alias-a"), + (&res_b, "msg-b", "alias-b"), + (&res_l, "msg-local", "alias-local"), + ] { + let model_connector::TransportDisposition::Transported { receipt, .. } = + &res.disposition + else { + panic!("expected transported for {expected_provider}: {res:?}"); + }; + assert_eq!(receipt.provider, expected_provider); + assert_eq!(receipt.model, expected_model); + let dbg = format!("{res:?}"); + assert!(!dbg.contains(SECRET_A)); + assert!(!dbg.contains(SECRET_B)); + } + + let sa = seen_a.lock().unwrap(); + assert_eq!(sa.len(), 1); + assert_eq!(sa[0].x_api_key.as_deref(), Some(SECRET_A)); + assert_eq!(sa[0].body["model"], "upstream-model-a"); + + let sb = seen_b.lock().unwrap(); + assert_eq!(sb.len(), 1); + assert_eq!(sb[0].x_api_key.as_deref(), Some(SECRET_B)); + assert_eq!(sb[0].body["model"], "upstream-model-b"); + + let sl = seen_local.lock().unwrap(); + assert_eq!(sl.len(), 1); + assert_eq!(sl[0].x_api_key, None); + assert_eq!(sl[0].body["model"], "upstream-model-local"); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + #[test] + fn mixed_cli_and_messages_entries_route_isolate_state_and_scope_quota() { + use std::os::unix::fs::PermissionsExt; + + let _env_guard = CREDENTIALS_ENV_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + + let dir = std::env::temp_dir().join(format!( + "claude-connector-mixed-serve-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + let at = |name: &str| dir.join(name); + for sub in ["work", "home/projects/test", "prompts", "credentials"] { + std::fs::create_dir_all(at(sub)).unwrap(); + } + std::fs::set_permissions(at("prompts"), std::fs::Permissions::from_mode(0o700)).unwrap(); + + let session_1 = "11111111-2222-3333-4444-555555555555"; + let session_2 = "66666666-7777-8888-9999-000000000000"; + let session_3 = "22222222-3333-4444-5555-666666666666"; + std::fs::write(at(&format!("home/projects/test/{session_1}.jsonl")), "{}\n").unwrap(); + + let line_init = |session: &str| { + serde_json::json!({ + "type": "system", + "subtype": "init", + "session_id": session, + "model": "cli-wire-model", + "tools": [] + }) + .to_string() + }; + let line_text = |id: &str, text: &str| { + serde_json::json!({ + "type": "assistant", + "message": {"id": id, "content": [{"type": "text", "text": text}]} + }) + .to_string() + }; + let line_result = || { + serde_json::json!({ + "type": "result", + "subtype": "success", + "is_error": false, + "stop_reason": "end_turn", + "model_usage_since_last_result": { + "cli-wire-model": {"inputTokens": 2, "outputTokens": 3, "cacheReadInputTokens": 0, "cacheCreationInputTokens": 0} + } + }) + .to_string() + }; + let rejected_quota = serde_json::json!({ + "type": "rate_limit_event", + "rate_limit_info": { + "status": "rejected", + "unifiedWindows": { + "five_hour": {"utilization": 1.0, "resetsAt": 4102444800u64, "status": "rejected"} + } + } + }) + .to_string(); + + std::fs::write( + at("resp-0.jsonl"), + [ + line_init(session_1), + line_text("m0", "cli one"), + line_result(), + ] + .join("\n") + + "\n", + ) + .unwrap(); + std::fs::write( + at("resp-1.jsonl"), + [ + line_init(session_2), + line_text("m1", "cli two"), + line_result(), + ] + .join("\n") + + "\n", + ) + .unwrap(); + std::fs::write( + at("resp-2.jsonl"), + [ + line_init(session_3), + rejected_quota, + line_text("m2", "cli three"), + line_result(), + ] + .join("\n") + + "\n", + ) + .unwrap(); + + let script = format!( + "#!/bin/sh\ncat > /dev/null\nN=$(cat '{}' 2>/dev/null || echo 0)\necho $((N+1)) > '{}'\nprintf '%s\\n' \"$*\" >> '{}'\ncat \"{}/resp-$N.jsonl\"\n", + at("call.idx").display(), + at("call.idx").display(), + at("argv.log").display(), + dir.display(), + ); + std::fs::write(at("claude"), &script).unwrap(); + std::fs::set_permissions(at("claude"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let caller_secret = "k".repeat(48); + std::fs::write(at("caller.key"), &caller_secret).unwrap(); + std::fs::write(at("credentials/cli-token"), "sk-ant-oat01-fake-token").unwrap(); + std::fs::write(at("credentials/cli-handle-secret"), "s".repeat(48)).unwrap(); + std::fs::write(at("credentials/msg-key"), "sk-msg-canary-key").unwrap(); + + let msg_reply = |id: &str, text: &str| { + serde_json::json!({ + "id": id, + "content": [ + {"type": "thinking", "thinking": "", "signature": "sig=="}, + {"type": "text", "text": text} + ], + "stop_reason": "end_turn", + "usage": {"input_tokens": 4, "output_tokens": 2} + }) + }; + let (msg_url, msg_seen) = spawn_http_mock(vec![ + msg_reply("msg_1", "msg one"), + msg_reply("msg_2", "msg two"), + msg_reply("msg_3", "msg three"), + ]); + + let config = ClaudeConnectorConfig { + listen: "127.0.0.1:0".to_string(), + replay_store: at("replay.cc"), + max_frame_bytes: 2 << 20, + max_connections: 8, + socket_timeout_ms: 10_000, + max_expiry_skew_ms: 300_000, + providers: vec![ + ProviderEntry { + id: "cli-custom".to_string(), + credential: Some("cli-token".to_string()), + wire: ProviderWire::ClaudeCodeCli { + binary: at("claude"), + binary_sha256: sha2::Sha256::digest(script.as_bytes()).into(), + work_dir: at("work"), + config_dir: at("home"), + prompt_dir: at("prompts"), + handle_secret_credential: "cli-handle-secret".to_string(), + instance: "inst-custom".to_string(), + deadline_ms: 600_000, + max_line_bytes: 4 << 20, + max_total_bytes: 64 << 20, + stderr_tail_bytes: 8192, + meter_model: None, + }, + }, + ProviderEntry { + id: "msg-custom".to_string(), + credential: Some("msg-key".to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: msg_url, + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ], + models: vec![ + ModelRow { + id: "cli-alias".to_string(), + provider: "cli-custom".to_string(), + upstream: "cli-wire-model".to_string(), + ..test_model("cli-alias", "cli-custom") + }, + ModelRow { + id: "msg-alias".to_string(), + provider: "msg-custom".to_string(), + upstream: "msg-wire-model".to_string(), + ..test_model("msg-alias", "msg-custom") + }, + ], + callers: vec![CallerConfig { + caller_runtime_id: "caller-mixed".to_string(), + connection_key_file: at("caller.key"), + connection_key_epoch: 1, + allowed_models: vec!["cli-alias".to_string(), "msg-alias".to_string()], + max_concurrent_requests: 4, + max_payload_bytes: 1 << 20, + max_output_tokens: 32_768, + }], + lease_socket: None, + lease_holders: Vec::new(), + lease_max_ms: 3_600_000, + }; + let cfg_path = at("connector.cc"); + write_config(&cfg_path, &config).unwrap(); + // SAFETY: guarded by CREDENTIALS_ENV_LOCK across all in-process tests touching CREDENTIALS_DIRECTORY. + unsafe { std::env::set_var("CREDENTIALS_DIRECTORY", at("credentials")) }; + + let (addr_tx, addr_rx) = std::sync::mpsc::channel(); + let cfg_thread = cfg_path.clone(); + std::thread::spawn(move || { + let _ = serve_bound_with( + &cfg_thread, + |addr| { + let _ = addr_tx.send(addr); + }, + |_| (), + ); + }); + let endpoint = addr_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let client = model_connector::ConnectorClient::new( + endpoint, + &caller_secret, + 2 << 20, + Some(Duration::from_secs(5)), + ) + .unwrap(); + + let user = |text: &str| model_connector::InputItem::UserText { + text: text.to_string(), + }; + + // 1. CLI call routes to `cli-custom` and returns handle tagged `cli-custom`. + let cli_1 = invoke( + &client, + "caller-mixed", + "r-cli-1", + "cli-alias", + vec![user("hi cli")], + ); + let model_connector::TransportDisposition::Transported { + receipt: r_cli_1, .. + } = &cli_1.disposition + else { + panic!("cli_1 failed: {cli_1:?}"); + }; + assert_eq!(r_cli_1.provider, "cli-custom"); + assert_eq!(r_cli_1.model, "cli-alias"); + let cli_1_items = cli_1.transcript_items(); + let cli_state = cli_1_items + .iter() + .find(|i| matches!(i, model_connector::InputItem::ReasoningState { .. })) + .expect("cli handle") + .clone(); + assert!(matches!( + &cli_state, + model_connector::InputItem::ReasoningState { provider, model, .. } + if provider == "cli-custom" && model == "cli-alias" + )); + + // 2. Resuming CLI handle tagged `cli-custom` passes `--resume --fork-session`. + let mut resume_input = vec![user("hi cli")]; + resume_input.extend(cli_1_items); + resume_input.push(user("follow up")); + let cli_2 = invoke( + &client, + "caller-mixed", + "r-cli-2", + "cli-alias", + resume_input, + ); + assert!(matches!( + cli_2.disposition, + model_connector::TransportDisposition::Transported { .. } + )); + + // 3. Messages call routes to `msg-custom`, sends `msg-wire-model`, returns `msg-custom` state. + let msg_1 = invoke( + &client, + "caller-mixed", + "r-msg-1", + "msg-alias", + vec![user("hi msg")], + ); + let model_connector::TransportDisposition::Transported { + receipt: r_msg_1, .. + } = &msg_1.disposition + else { + panic!("msg_1 failed: {msg_1:?}"); + }; + assert_eq!(r_msg_1.provider, "msg-custom"); + assert_eq!(r_msg_1.model, "msg-alias"); + let msg_state = msg_1 + .transcript_items() + .into_iter() + .find(|i| matches!(i, model_connector::InputItem::ReasoningState { .. })) + .expect("msg thinking"); + assert!(matches!( + &msg_state, + model_connector::InputItem::ReasoningState { provider, model, .. } + if provider == "msg-custom" && model == "msg-alias" + )); + + // 4. ReasoningState isolation CLI -> Messages: prior-turn drops, in-flight refuses. + let msg_inflight = invoke( + &client, + "caller-mixed", + "r-msg-inf", + "msg-alias", + vec![user("hi"), cli_state.clone()], + ); + assert!(matches!( + msg_inflight.disposition, + model_connector::TransportDisposition::Refused( + model_connector::Refusal::ForeignReasoningState + ) + )); + let msg_2 = invoke( + &client, + "caller-mixed", + "r-msg-2", + "msg-alias", + vec![user("hi"), cli_state, user("next")], + ); + let model_connector::TransportDisposition::Transported { + receipt: r_msg_2, .. + } = &msg_2.disposition + else { + panic!("msg_2 failed: {msg_2:?}"); + }; + assert_eq!(r_msg_2.foreign_reasoning_dropped, 1); + + // 5. ReasoningState isolation Messages -> CLI: in-flight refuses, prior-turn drops & seeds fresh (and triggers rejected quota). + let cli_inflight = invoke( + &client, + "caller-mixed", + "r-cli-inf", + "cli-alias", + vec![user("hi"), msg_state.clone()], + ); + assert!(matches!( + cli_inflight.disposition, + model_connector::TransportDisposition::Refused( + model_connector::Refusal::ForeignReasoningState + ) + )); + let cli_3 = invoke( + &client, + "caller-mixed", + "r-cli-3", + "cli-alias", + vec![user("hi"), msg_state, user("next")], + ); + let model_connector::TransportDisposition::Transported { + receipt: r_cli_3, .. + } = &cli_3.disposition + else { + panic!("cli_3 failed: {cli_3:?}"); + }; + assert_eq!(r_cli_3.foreign_reasoning_dropped, 1); + + // 6. CLI `plan_quota()` tagged `cli-custom`: ProviderRejected refuses CLI only, Messages still executes. + let cli_rejected = invoke( + &client, + "caller-mixed", + "r-cli-4", + "cli-alias", + vec![user("after reject")], + ); + assert!(matches!( + cli_rejected.disposition, + model_connector::TransportDisposition::Refused( + model_connector::Refusal::ProviderRejected + ) + )); + let msg_3 = invoke( + &client, + "caller-mixed", + "r-msg-3", + "msg-alias", + vec![user("still works")], + ); + assert!(matches!( + msg_3.disposition, + model_connector::TransportDisposition::Transported { .. } + )); + + let argv_lines: Vec = std::fs::read_to_string(at("argv.log")) + .unwrap() + .lines() + .map(str::to_string) + .collect(); + assert_eq!(argv_lines.len(), 3); + assert!(argv_lines[0].contains("--model cli-wire-model")); + assert!(!argv_lines[0].contains("--resume")); + assert!(argv_lines[1].contains(&format!("--resume {session_1} --fork-session"))); + assert!(!argv_lines[2].contains("--resume")); + + let seen_http = msg_seen.lock().unwrap(); + assert_eq!(seen_http.len(), 3); + assert_eq!(seen_http[0].body["model"], "msg-wire-model"); + // Prior-turn CLI handle was dropped before Messages saw it. + assert_eq!(seen_http[1].body["messages"].as_array().unwrap().len(), 1); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + #[test] + fn serve_config_with_readiness_names_failing_entry_id_without_leaking_secret() { + const SECRET_1: &str = "sk-canary-serve-ready-111"; + const CRED_1: &str = "serve-cred-one"; + const CRED_2: &str = "serve-cred-two"; + + let _env_guard = CREDENTIALS_ENV_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + + let dir = std::env::temp_dir().join(format!( + "claude-connector-serve-readiness-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + let creds = dir.join("creds"); + std::fs::create_dir_all(&creds).unwrap(); + std::fs::write(creds.join(CRED_1), SECRET_1).unwrap(); + let key_file = dir.join("caller.key"); + std::fs::write(&key_file, "k".repeat(48)).unwrap(); + + let config = ClaudeConnectorConfig { + listen: "127.0.0.1:0".to_string(), + replay_store: dir.join("replay.cc"), + max_frame_bytes: 2 << 20, + max_connections: 8, + socket_timeout_ms: 10_000, + max_expiry_skew_ms: 300_000, + providers: vec![ + ProviderEntry { + id: "entry-one".to_string(), + credential: Some(CRED_1.to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: "https://one.example.test".to_string(), + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ProviderEntry { + id: "entry-two".to_string(), + credential: Some(CRED_2.to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: "https://two.example.test".to_string(), + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ], + models: vec![test_model("m1", "entry-one"), test_model("m2", "entry-two")], + callers: vec![CallerConfig { + caller_runtime_id: "caller-a".to_string(), + connection_key_file: key_file, + connection_key_epoch: 1, + allowed_models: vec!["m1".to_string(), "m2".to_string()], + max_concurrent_requests: 2, + max_payload_bytes: MIN_PAYLOAD_BYTES, + max_output_tokens: 4_096, + }], + lease_socket: None, + lease_holders: Vec::new(), + lease_max_ms: 3_600_000, + }; + let cfg_path = dir.join("connector.cc"); + write_config(&cfg_path, &config).unwrap(); + // SAFETY: guarded by CREDENTIALS_ENV_LOCK across all in-process tests touching CREDENTIALS_DIRECTORY. + unsafe { std::env::set_var("CREDENTIALS_DIRECTORY", &creds) }; + + let err = + serve_config_with(&cfg_path, |_| panic!("serve should fail readiness")).unwrap_err(); + let rendered = format!("{err} {err:?}"); + assert!( + matches!( + err, + ConfigError::UnusableEntry { ref id, field: "credential" } if id == "entry-two" + ), + "{rendered}" + ); + assert!(rendered.contains("entry-two"), "{rendered}"); + for secret in [SECRET_1, CRED_1, CRED_2] { + assert!(!rendered.contains(secret), "leaked {secret}: {rendered}"); + } + let _ = std::fs::remove_dir_all(&dir); } @@ -756,6 +1898,513 @@ mod tests { assert!(!written.contains("canary")); } + #[test] + fn systemd_unit_names_allow_plain_and_instanced_services_only() { + assert!(is_systemd_unit_name("agent.service")); + assert!(is_systemd_unit_name("agent@alice.service")); + assert!(is_systemd_unit_name("foo.bar@baz-1_2.service")); + let max_len = format!("{}.service", "a".repeat(256 - ".service".len())); + assert_eq!(max_len.len(), 256); + assert!(is_systemd_unit_name(&max_len)); + + let too_long = format!("{}.service", "a".repeat(257 - ".service".len())); + for bad in [ + "agent@.service", + "@a.service", + "a@b@c.service", + ".service", + "agent", + "a/b.service", + "a..b.service", + ".a.service", + "a.@b.service", + "a@.b.service", + "a b.service", + too_long.as_str(), + ] { + assert!(!is_systemd_unit_name(bad), "unexpectedly accepted {bad:?}"); + } + } + + #[test] + fn routes_for_maps_all_allowed_models_to_configured_provider() { + let caller_with = |id: &str, models: &[&str]| CallerConfig { + caller_runtime_id: id.to_string(), + connection_key_file: PathBuf::from("/tmp/caller.key"), + connection_key_epoch: 1, + allowed_models: models.iter().map(|model| (*model).to_string()).collect(), + max_concurrent_requests: 2, + max_payload_bytes: MIN_PAYLOAD_BYTES, + max_output_tokens: 4_096, + }; + let config = ClaudeConnectorConfig { + listen: "127.0.0.1:0".to_string(), + replay_store: PathBuf::from("/tmp/replay.cc"), + max_frame_bytes: 2 << 20, + max_connections: 8, + socket_timeout_ms: 10_000, + max_expiry_skew_ms: 300_000, + providers: vec![ + ProviderEntry { + id: "anthropic-primary".to_string(), + credential: Some("anthropic-key".to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: "https://primary.example.test".to_string(), + deadline_ms: 600_000, + max_response_bytes: 64 << 20, + }, + }, + ProviderEntry { + id: "local-stub".to_string(), + credential: None, + wire: ProviderWire::AnthropicMessages { + base_url: "http://127.0.0.1:9000".to_string(), + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ], + models: vec![ + test_model("claude-haiku-5-5", "anthropic-primary"), + test_model("claude-sonnet-5-5", "anthropic-primary"), + test_model("custom-model", "local-stub"), + ], + callers: vec![ + caller_with("caller-a", &["claude-haiku-5-5", "custom-model"]), + caller_with("caller-b", &["claude-sonnet-5-5"]), + ], + lease_socket: None, + lease_holders: Vec::new(), + lease_max_ms: 3_600_000, + }; + + let routes = routes_for(&config).unwrap(); + assert_eq!( + routes.provider_for("claude-haiku-5-5"), + Some("anthropic-primary") + ); + assert_eq!( + routes.provider_for("claude-sonnet-5-5"), + Some("anthropic-primary") + ); + assert_eq!(routes.provider_for("custom-model"), Some("local-stub")); + assert_eq!(routes.provider_for("unlisted-model"), None); + } + + #[test] + fn readiness_of_in_checks_every_entry_and_names_failing_id_without_leaking_secret() { + const SECRET_A: &str = "canary-secret-alpha-91c2"; + const SECRET_B: &str = "canary-secret-beta-47f0"; + const CRED_A: &str = "canary-cred-a"; + const CRED_B: &str = "canary-cred-b"; + + let dir = + std::env::temp_dir().join(format!("claude-connector-ready-in-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let creds = dir.join("creds"); + std::fs::create_dir_all(&creds).unwrap(); + let key_file = dir.join("caller.key"); + std::fs::write(&key_file, "k".repeat(48)).unwrap(); + std::fs::write(creds.join(CRED_A), SECRET_A).unwrap(); + std::fs::write(creds.join(CRED_B), SECRET_B).unwrap(); + + let config = ClaudeConnectorConfig { + listen: "127.0.0.1:0".to_string(), + replay_store: dir.join("replay.cc"), + max_frame_bytes: 2 << 20, + max_connections: 8, + socket_timeout_ms: 10_000, + max_expiry_skew_ms: 300_000, + providers: vec![ + ProviderEntry { + id: "provider-one".to_string(), + credential: Some(CRED_A.to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: "https://one.example.test".to_string(), + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ProviderEntry { + id: "provider-two".to_string(), + credential: Some(CRED_B.to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: "https://two.example.test".to_string(), + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ProviderEntry { + id: "loopback-keyless".to_string(), + credential: None, + wire: ProviderWire::AnthropicMessages { + base_url: "http://127.0.0.1:8080".to_string(), + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ], + models: vec![ + test_model("model-one", "provider-one"), + test_model("model-two", "provider-two"), + test_model("model-local", "loopback-keyless"), + ], + callers: vec![CallerConfig { + caller_runtime_id: "caller-a".to_string(), + connection_key_file: key_file, + connection_key_epoch: 1, + allowed_models: vec!["model-one".to_string(), "model-two".to_string()], + max_concurrent_requests: 2, + max_payload_bytes: MIN_PAYLOAD_BYTES, + max_output_tokens: 4_096, + }], + lease_socket: None, + lease_holders: Vec::new(), + lease_max_ms: 3_600_000, + }; + + assert!(readiness_of_in(&config, Some(&creds)).is_ok()); + + // Missing credentials directory names the first entry needing one. + let no_dir = readiness_of_in(&config, None).map(drop).unwrap_err(); + assert!(matches!( + no_dir, + ConfigError::UnusableEntry { ref id, field: "credentials_directory" } + if id == "provider-one" + )); + + // Empty credential on the second entry fails naming `provider-two` and never leaks secrets. + std::fs::write(creds.join(CRED_B), "").unwrap(); + let empty = readiness_of_in(&config, Some(&creds)) + .map(drop) + .unwrap_err(); + let rendered = format!("{empty} {empty:?}"); + assert!( + matches!( + empty, + ConfigError::UnusableEntry { ref id, field: "credential" } + if id == "provider-two" + ), + "{rendered}" + ); + assert!(rendered.contains("provider-two"), "{rendered}"); + for secret in [SECRET_A, SECRET_B, CRED_A, CRED_B] { + assert!(!rendered.contains(secret), "leaked {secret}: {rendered}"); + } + + // Missing credential file on the second entry also fails naming `provider-two`. + std::fs::remove_file(creds.join(CRED_B)).unwrap(); + let missing = readiness_of_in(&config, Some(&creds)) + .map(drop) + .unwrap_err(); + assert!(matches!( + missing, + ConfigError::UnusableEntry { ref id, field: "credential" } + if id == "provider-two" + )); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + #[test] + fn openai_chat_serve_routes_isolates_state_and_checks_readiness() { + const SECRET_OAI: &str = "sk-canary-oai-daemon-3333"; + const SECRET_MSG: &str = "sk-canary-msg-daemon-4444"; + + let _env_guard = CREDENTIALS_ENV_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + + let dir = + std::env::temp_dir().join(format!("claude-connector-oai-serve-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let creds = dir.join("creds"); + std::fs::create_dir_all(&creds).unwrap(); + std::fs::write(creds.join("oai-cred"), SECRET_OAI).unwrap(); + std::fs::write(creds.join("msg-cred"), SECRET_MSG).unwrap(); + let key_file = dir.join("caller.key"); + let caller_secret = "m".repeat(48); + std::fs::write(&key_file, &caller_secret).unwrap(); + + let (url_keyed, seen_keyed) = spawn_http_mock(vec![ + serde_json::json!({ + "id": "oai_k_1", + "choices": [{ + "index": 0, + "message": { + "role": "assistant", + "content": null, + "reasoning_content": "oai reasoning", + "tool_calls": [{ + "id": "call_oai_1", + "type": "function", + "function": {"name": "lookup", "arguments": "{\"q\":\"x\"}"} + }] + }, + "finish_reason": "tool_calls" + }], + "usage": {"prompt_tokens": 5, "completion_tokens": 3} + }), + serde_json::json!({ + "id": "oai_k_2", + "choices": [{ + "index": 0, + "message": {"role": "assistant", "content": "replayed ok"}, + "finish_reason": "stop" + }], + "usage": {"prompt_tokens": 8, "completion_tokens": 2} + }), + ]); + let (url_local, seen_local) = spawn_http_mock(vec![serde_json::json!({ + "id": "oai_l_1", + "choices": [{ + "index": 0, + "message": {"role": "assistant", "content": "local ok"}, + "finish_reason": "stop" + }], + "usage": {"prompt_tokens": 4, "completion_tokens": 2} + })]); + let (url_msg, seen_msg) = spawn_http_mock(vec![serde_json::json!({ + "id": "msg_1", + "content": [ + {"type": "thinking", "thinking": "msg thought", "signature": "sig-msg"}, + {"type": "text", "text": "msg ok"} + ], + "stop_reason": "end_turn", + "usage": {"input_tokens": 4, "output_tokens": 2} + })]); + + let model_row = |id: &str, provider: &str, upstream: &str| ModelRow { + id: id.to_string(), + provider: provider.to_string(), + upstream: upstream.to_string(), + ..test_model(id, provider) + }; + + let config = ClaudeConnectorConfig { + listen: "127.0.0.1:0".to_string(), + replay_store: dir.join("replay.cc"), + max_frame_bytes: 2 << 20, + max_connections: 8, + socket_timeout_ms: 10_000, + max_expiry_skew_ms: 300_000, + providers: vec![ + ProviderEntry { + id: "oai-keyed".to_string(), + credential: Some("oai-cred".to_string()), + wire: ProviderWire::OpenAiChat { + base_url: format!("{url_keyed}/v1"), + strict_unsupported: vec!["minLength".to_string()], + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ProviderEntry { + id: "oai-local".to_string(), + credential: None, + wire: ProviderWire::OpenAiChat { + base_url: format!("{url_local}/v1"), + strict_unsupported: vec![], + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ProviderEntry { + id: "msg-entry".to_string(), + credential: Some("msg-cred".to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: url_msg, + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ], + models: vec![ + model_row("model-oai-keyed", "oai-keyed", "deepseek-chat"), + model_row("model-oai-local", "oai-local", "local-model"), + model_row("model-msg", "msg-entry", "claude-upstream"), + ], + callers: vec![CallerConfig { + caller_runtime_id: "caller-oai".to_string(), + connection_key_file: key_file, + connection_key_epoch: 1, + allowed_models: vec![ + "model-oai-keyed".to_string(), + "model-oai-local".to_string(), + "model-msg".to_string(), + ], + max_concurrent_requests: 4, + max_payload_bytes: 1 << 20, + max_output_tokens: 32_768, + }], + lease_socket: None, + lease_holders: Vec::new(), + lease_max_ms: 3_600_000, + }; + + // Readiness check fails naming `oai-keyed` when its credential is empty and never leaks secret. + std::fs::write(creds.join("oai-cred"), "").unwrap(); + let bad_ready = readiness_of_in(&config, Some(&creds)) + .map(drop) + .unwrap_err(); + let rendered = format!("{bad_ready} {bad_ready:?}"); + assert!( + matches!( + bad_ready, + ConfigError::UnusableEntry { ref id, field: "credential" } + if id == "oai-keyed" + ), + "{rendered}" + ); + assert!(!rendered.contains(SECRET_OAI), "{rendered}"); + assert!(!rendered.contains(SECRET_MSG), "{rendered}"); + std::fs::write(creds.join("oai-cred"), SECRET_OAI).unwrap(); + assert!(readiness_of_in(&config, Some(&creds)).is_ok()); + + let cfg_path = dir.join("connector.cc"); + write_config(&cfg_path, &config).unwrap(); + // SAFETY: guarded by CREDENTIALS_ENV_LOCK across all in-process tests touching CREDENTIALS_DIRECTORY. + unsafe { std::env::set_var("CREDENTIALS_DIRECTORY", &creds) }; + + let (addr_tx, addr_rx) = std::sync::mpsc::channel(); + let cfg_thread = cfg_path.clone(); + std::thread::spawn(move || { + let _ = serve_bound_with( + &cfg_thread, + |addr| { + let _ = addr_tx.send(addr); + }, + |_| (), + ); + }); + let endpoint = addr_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let client = model_connector::ConnectorClient::new( + endpoint, + &caller_secret, + 2 << 20, + Some(Duration::from_secs(5)), + ) + .unwrap(); + + let user_msg = vec![model_connector::InputItem::UserText { + text: "hello".to_string(), + }]; + let res_keyed = invoke( + &client, + "caller-oai", + "req-oai-1", + "model-oai-keyed", + user_msg.clone(), + ); + let res_local = invoke( + &client, + "caller-oai", + "req-oai-local", + "model-oai-local", + user_msg.clone(), + ); + let res_msg = invoke( + &client, + "caller-oai", + "req-msg-1", + "model-msg", + user_msg.clone(), + ); + + for (res, expected_provider, expected_model) in [ + (&res_keyed, "oai-keyed", "model-oai-keyed"), + (&res_local, "oai-local", "model-oai-local"), + (&res_msg, "msg-entry", "model-msg"), + ] { + let model_connector::TransportDisposition::Transported { receipt, .. } = + &res.disposition + else { + panic!("expected transported for {expected_provider}: {res:?}"); + }; + assert_eq!(receipt.provider, expected_provider); + assert_eq!(receipt.model, expected_model); + let dbg = format!("{res:?}"); + assert!(!dbg.contains(SECRET_OAI)); + assert!(!dbg.contains(SECRET_MSG)); + } + + // Replay own OpenAiChat state + tool result back to oai-keyed succeeds. + let mut own_replay = user_msg.clone(); + own_replay.extend(res_keyed.transcript_items()); + own_replay.push(model_connector::InputItem::ToolResult { + call_id: "call_oai_1".to_string(), + output: "found".to_string(), + }); + let res_replayed = invoke( + &client, + "caller-oai", + "req-oai-2", + "model-oai-keyed", + own_replay, + ); + assert!(matches!( + res_replayed.disposition, + model_connector::TransportDisposition::Transported { .. } + )); + + // Foreign ReasoningState between OpenAiChat and AnthropicMessages is refused in-flight. + let mut oai_to_msg = user_msg.clone(); + oai_to_msg.extend(res_keyed.transcript_items()); + let refused_msg = invoke( + &client, + "caller-oai", + "req-cross-1", + "model-msg", + oai_to_msg, + ); + assert_eq!( + refused_msg.disposition, + model_connector::TransportDisposition::Refused( + model_connector::Refusal::ForeignReasoningState + ) + ); + + let mut msg_to_oai = user_msg; + msg_to_oai.extend(res_msg.transcript_items()); + let refused_oai = invoke( + &client, + "caller-oai", + "req-cross-2", + "model-oai-keyed", + msg_to_oai, + ); + assert_eq!( + refused_oai.disposition, + model_connector::TransportDisposition::Refused( + model_connector::Refusal::ForeignReasoningState + ) + ); + + let sk = seen_keyed.lock().unwrap(); + assert_eq!(sk.len(), 2); + assert_eq!( + sk[0].authorization.as_deref(), + Some(format!("Bearer {SECRET_OAI}").as_str()) + ); + assert_eq!(sk[0].body["model"], "deepseek-chat"); + assert_eq!( + sk[1].body["messages"][2]["reasoning_content"], + "oai reasoning" + ); + + let sl = seen_local.lock().unwrap(); + assert_eq!(sl.len(), 1); + assert_eq!(sl[0].authorization, None); + assert_eq!(sl[0].body["model"], "local-model"); + + let sm = seen_msg.lock().unwrap(); + assert_eq!(sm.len(), 1); + assert_eq!(sm[0].x_api_key.as_deref(), Some(SECRET_MSG)); + + let _ = std::fs::remove_dir_all(&dir); + } + #[cfg(unix)] mod prompt_dir { use std::os::unix::fs::{PermissionsExt, chown, symlink}; diff --git a/crates/claude-connector/src/handle.rs b/crates/claude-connector/src/handle.rs index 30cf6cf..e5e793f 100644 --- a/crates/claude-connector/src/handle.rs +++ b/crates/claude-connector/src/handle.rs @@ -10,7 +10,7 @@ use model_connector::{InputItem, ProviderRequest}; use serde::{Deserialize, Serialize}; use sha2::Sha256; -use crate::config::{ClaudeCodeConfig, PROVIDER}; +use crate::config::ClaudeCodeConfig; /// The state this backend hands a caller inside `ReasoningState`. A new /// variant is a new version. @@ -190,9 +190,9 @@ pub(crate) fn plan( return Err(PlanError::NoUserText); } - let last_own = input.iter().rposition( - |item| matches!(item, InputItem::ReasoningState { provider, .. } if provider == PROVIDER), - ); + let last_own = input.iter().rposition(|item| { + matches!(item, InputItem::ReasoningState { provider, .. } if provider == &config.provider_id) + }); if let Some(at) = last_own { let InputItem::ReasoningState { state, .. } = &input[at] else { unreachable!("rposition matched a reasoning state"); diff --git a/crates/claude-connector/src/http.rs b/crates/claude-connector/src/http.rs new file mode 100644 index 0000000..57ccb72 --- /dev/null +++ b/crates/claude-connector/src/http.rs @@ -0,0 +1,233 @@ +use std::time::Duration; + +use model_connector::{FailureKind, TransportEvent, TransportOutcome, Usage}; +use serde_json::Value; +use zeroize::Zeroizing; + +use crate::credential::TokenSource; + +/// The longest provider message a receipt carries. +pub(crate) const MESSAGE_BYTES: usize = 2048; + +/// Builds the HTTP client used by every HTTP backend: global deadline, status +/// errors returned as responses, no redirects (so credentials cannot leak to a +/// redirect target), and no environment proxy lookup. +pub(crate) fn build_agent(deadline: Duration) -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_global(Some(deadline)) + .http_status_as_error(false) + .max_redirects(0) + .proxy(None) + .build() + .into() +} + +pub(crate) fn read_key( + keys: Option<&dyn TokenSource>, + label: &str, +) -> Result>, (Vec, TransportOutcome)> { + match keys { + Some(source) => match source.read() { + Some(key) => Ok(Some(key)), + None => Err(failed( + FailureKind::Authentication, + format!("{label}: the connector has no API key"), + Some(zero_usage()), + )), + }, + None => Ok(None), + } +} + +/// The Persona drain treats `RateLimited`, `Unavailable`, `Timeout` and +/// `Authentication` as outages and every other kind as a strike against the +/// line the turn was waking on. A fault of the key's account or of the path to +/// the API is never the line's. +/// +/// 402 is a credential-level fault, not a transient one: the key's account +/// cannot pay and only the operator fixes it, as with 401 and 403, so it is +/// `Authentication`; `Unavailable` would promise that it heals itself. +pub(crate) fn kind_of_status(status: u16) -> FailureKind { + match status { + 401..=403 => FailureKind::Authentication, + 408 | 504 => FailureKind::Timeout, + 429 => FailureKind::RateLimited, + 300..=399 | 500..=599 => FailureKind::Unavailable, + 400 => FailureKind::InvalidRequest, + _ => FailureKind::Provider, + } +} + +/// A failure the provider answered: its own type/code and message, bounded and +/// scrubbed of any credential bytes. +pub(crate) fn http_failure( + label: &str, + status: u16, + body: &[u8], + secret: Option<&str>, + spend_exhausted: impl FnOnce(u16, &Value) -> bool, +) -> (Vec, TransportOutcome) { + let parsed: Value = serde_json::from_slice(body).unwrap_or(Value::Null); + let error = if parsed["error"].is_object() { + &parsed["error"] + } else { + &parsed + }; + let mut message = format!("{label}: HTTP {status}"); + if let Some(kind) = error["type"].as_str().or_else(|| error["code"].as_str()) { + message.push(' '); + message.push_str(kind); + } + if let Some(text) = error["message"].as_str().filter(|text| !text.is_empty()) { + message.push_str(": "); + message.push_str(text); + } + if let Some(secret) = secret.filter(|s| !s.is_empty()) { + message = message.replace(secret, "[redacted]"); + } + let kind = if spend_exhausted(status, error) { + FailureKind::Authentication + } else { + kind_of_status(status) + }; + failed(kind, bounded(message), None) +} + +/// A failure before an answer: the deadline, the size cap, the connection. +pub(crate) fn transport_failure( + label: &str, + error: &ureq::Error, +) -> (Vec, TransportOutcome) { + let (kind, what) = match error { + ureq::Error::Timeout(_) => ( + FailureKind::Timeout, + "the deadline passed before a response", + ), + ureq::Error::BodyExceedsLimit(_) => { + (FailureKind::Provider, "the response passed its size cap") + } + ureq::Error::BadUri(_) | ureq::Error::Http(_) | ureq::Error::InvalidProxyUrl => { + (FailureKind::Provider, "the request could not be built") + } + _ => (FailureKind::Unavailable, "the API could not be reached"), + }; + failed(kind, format!("{label}: {what}"), None) +} + +pub(crate) fn bounded(mut message: String) -> String { + if message.len() > MESSAGE_BYTES { + let mut end = MESSAGE_BYTES; + while !message.is_char_boundary(end) { + end -= 1; + } + message.truncate(end); + } + message +} + +pub(crate) fn zero_usage() -> Usage { + Usage { + input_tokens: 0, + cache_read_tokens: 0, + cache_write_tokens: 0, + output_tokens: 0, + reasoning_tokens: None, + } +} + +pub(crate) fn failed( + kind: FailureKind, + message: String, + usage: Option, +) -> (Vec, TransportOutcome) { + ( + Vec::new(), + TransportOutcome::Failed { + kind, + message, + usage, + }, + ) +} + +#[cfg(test)] +pub(crate) static PROXY_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[cfg(test)] +mod tests { + use std::io::{Read, Write}; + use std::net::TcpListener; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::thread; + use std::time::Duration; + + use super::{PROXY_ENV_LOCK, build_agent}; + + struct EnvRestore { + http: Option, + https: Option, + } + + impl Drop for EnvRestore { + fn drop(&mut self) { + // SAFETY: guarded by PROXY_ENV_LOCK across tests touching proxy env vars. + unsafe { + match &self.http { + Some(v) => std::env::set_var("HTTP_PROXY", v), + None => std::env::remove_var("HTTP_PROXY"), + } + match &self.https { + Some(v) => std::env::set_var("HTTPS_PROXY", v), + None => std::env::remove_var("HTTPS_PROXY"), + } + } + } + } + + #[test] + fn build_agent_ignores_http_and_https_proxy_env() { + let _guard = PROXY_ENV_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let _restore = EnvRestore { + http: std::env::var_os("HTTP_PROXY"), + https: std::env::var_os("HTTPS_PROXY"), + }; + + let proxy_listener = TcpListener::bind("127.0.0.1:0").unwrap(); + proxy_listener.set_nonblocking(true).unwrap(); + let proxy_url = format!("http://{}", proxy_listener.local_addr().unwrap()); + + let target_listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let target_url = format!("http://{}/ok", target_listener.local_addr().unwrap()); + let target_hits = Arc::new(AtomicUsize::new(0)); + let hits = target_hits.clone(); + let handle = thread::spawn(move || { + let (mut stream, _) = target_listener.accept().unwrap(); + hits.fetch_add(1, Ordering::SeqCst); + let mut buf = [0u8; 512]; + let _ = stream.read(&mut buf); + let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"); + }); + + // SAFETY: guarded by PROXY_ENV_LOCK. + unsafe { + std::env::set_var("HTTP_PROXY", &proxy_url); + std::env::set_var("HTTPS_PROXY", &proxy_url); + } + + let agent = build_agent(Duration::from_secs(5)); + let mut resp = agent.get(&target_url).call().unwrap(); + assert_eq!(resp.status().as_u16(), 200); + let body = resp.body_mut().read_to_string().unwrap(); + assert_eq!(body, "ok"); + + handle.join().unwrap(); + assert_eq!(target_hits.load(Ordering::SeqCst), 1); + assert!( + matches!(proxy_listener.accept(), Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock), + "proxy listener must never be contacted" + ); + } +} diff --git a/crates/claude-connector/src/launch.rs b/crates/claude-connector/src/launch.rs index 1f8dbd0..8387bfc 100644 --- a/crates/claude-connector/src/launch.rs +++ b/crates/claude-connector/src/launch.rs @@ -8,18 +8,18 @@ use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -use model_connector::{ProviderRequest, ReasoningEffort}; +use model_connector::ProviderRequest; use crate::config::ClaudeCodeConfig; use crate::handle::Plan; -/// The variable that tells the CLI which file descriptor holds its credential. -/// The token itself never enters the environment: the process port writes it -/// into a pipe and hands the child the read end at [`TOKEN_FD`]. -pub(crate) const TOKEN_FD_VAR: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR"; -/// The descriptor number the child finds the token pipe at: the first one -/// after stdin, stdout and stderr. +/// The credential never enters the environment: +/// the process port writes it into a pipe and hands the child the read end at +/// [`TOKEN_FD`], the first descriptor after stdin, stdout and stderr, and the +/// environment names that descriptor. pub(crate) const TOKEN_FD: i32 = 3; +/// The variable that tells the CLI which descriptor holds the subscription token. +pub(crate) const TOKEN_FD_VAR: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR"; const CHILD_PATH: &str = "/usr/local/bin:/usr/bin:/bin"; /// The environment of the child: exactly these names and nothing inherited. @@ -94,15 +94,6 @@ impl Drop for PromptFile { } } -fn effort(effort: ReasoningEffort) -> &'static str { - match effort { - ReasoningEffort::Low => "low", - ReasoningEffort::Medium => "medium", - ReasoningEffort::High => "high", - ReasoningEffort::Max => "max", - } -} - /// The program and its arguments. The system prompt is replaced, by a file /// rather than an argument because one argument is capped near 128 KiB /// (E2BIG) and instructions are not, the child has @@ -115,6 +106,7 @@ pub(crate) fn argv( request: &ProviderRequest, plan: &Plan, system_prompt_file: &Path, + effort: Option<&str>, ephemeral: bool, ) -> Vec { let mut argv: Vec = [ @@ -144,8 +136,8 @@ pub(crate) fn argv( if ephemeral { argv.push("--no-session-persistence".to_string()); } - if let Some(level) = request.reasoning_effort { - argv.extend(["--effort".to_string(), effort(level).to_string()]); + if let Some(level) = effort { + argv.extend(["--effort".to_string(), level.to_string()]); } if let Some(schema) = &request.output_schema_json { argv.extend(["--json-schema".to_string(), schema.clone()]); diff --git a/crates/claude-connector/src/lease.rs b/crates/claude-connector/src/lease.rs index a049bba..b6c0a30 100644 --- a/crates/claude-connector/src/lease.rs +++ b/crates/claude-connector/src/lease.rs @@ -1,23 +1,22 @@ -//! The Self-run credential lease. The connector is the only holder of the -//! subscription token and the one owner of Self-run admission (rulings -//! self-runs-through-connector and self-run-credential-lease). A Self run asks +//! The credential lease. The connector is the only holder of the +//! subscription token and the one owner of lease admission. A holder asks //! over a unix socket for a lease. The connector decides who may ask (the //! peer's uid, and the systemd unit invocation its process runs in), and hands //! back one pipe fd that holds the token, with the plan's usage windows. The //! lease lasts while the holder keeps the socket open: it ends when the holder //! closes it, when its unit invocation ends, or when its expiry passes. Nothing //! is reserved and nothing is billed; the only usage-derived refusal is the -//! provider's own, repeated until its own reset. Nothing the run says about +//! provider's own, repeated until its own reset. Nothing the holder says about //! itself decides who it is or what the plan allows. //! //! The same socket also answers a usage readout to any peer that can reach it //! (the claude-lease group): no lease, no caller check, no token read and no -//! wake of the meter. Usage is state every Mind reads. +//! wake of the meter. Usage is state every peer with socket access reads. //! //! The token exists in this process only as the value the token source returns //! and in the pipe. It is not in an environment, an argument, a file, a log or -//! a reply frame. The connector spawns nothing here: the Self run's `claude` -//! stays in the Self run's own unit. +//! a reply frame. The connector spawns nothing here: the holder's `claude` +//! stays in the holder's own unit. use std::ffi::CString; use std::io::{self, Read, Write}; @@ -31,7 +30,7 @@ use std::thread; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use model_connector::{ - LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseTurn, PlanQuota, TransportService, UsageReadout, + LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseScope, PlanQuota, TransportService, UsageReadout, }; use serde::{Deserialize, Serialize}; @@ -173,28 +172,16 @@ fn read_message(stream: &mut impl Bounded, deadline: Instant) -> io::Result` of `mind-self@.service` or - /// `mind-persona@.service`. - pub unit_instance: String, -} - -impl LeaseCaller { - /// The one unit a lease to this caller may be requested from. - pub fn unit(&self) -> String { - match self.turn { - LeaseTurn::SelfRun => format!("mind-self@{}.service", self.unit_instance), - LeaseTurn::PersonaTurn => format!("mind-persona@{}.service", self.unit_instance), - } - } + pub provider: String, + pub unit: String, + pub scope: LeaseScope, } /// The systemd unit invocation a process runs in. @@ -389,7 +376,7 @@ impl Drop for Permit { } struct Lender { - callers: Vec, + holders: Vec, limits: LeaseLimits, service: Arc>, quota: Arc, @@ -410,14 +397,13 @@ const READOUT_CONNECTIONS: usize = 4; /// one usage readout. A lease: request, then grant or refusal, then (after a /// grant) the hold. A readout: request, then one frame, then close; its reach /// is the socket's group, and it reads the plan's windows without waking the -/// meter. A caller is -/// the account whose uid the kernel reports for the connection, and only a -/// process in that caller's unit may lease, once per unit invocation for a Self -/// run and once per turn for a Persona; no -/// field of any message names either. +/// meter. A holder is the account whose uid the kernel reports for the +/// connection, and only a process in that holder's configured unit may lease, +/// once per caller for `PerCaller` and once per unit invocation for +/// `PerInvocation`; no field of any message names either. pub fn serve_leases( listener: &UnixListener, - callers: Vec, + holders: Vec, limits: LeaseLimits, service: Arc>, quota: Arc, @@ -425,7 +411,7 @@ pub fn serve_leases( units: Arc, ) -> io::Result<()> { let lender = Arc::new(Lender { - callers, + holders, limits, service, quota, @@ -487,7 +473,7 @@ impl Lender { peer: PeerCredentials, request: LeaseRequest, ) -> io::Result<()> { - let Some(caller) = self.callers.iter().find(|caller| caller.uid == peer.uid) else { + let Some(holder) = self.holders.iter().find(|holder| holder.uid == peer.uid) else { return refuse( &mut stream, LeaseRefusalKind::UnknownCaller, @@ -499,13 +485,13 @@ impl Lender { let Some(invocation) = peer .process .as_ref() - .and_then(|process| self.units.invocation_in(process.as_fd(), &caller.unit())) - .filter(|found| found.unit == caller.unit()) + .and_then(|process| self.units.invocation_in(process.as_fd(), &holder.unit)) + .filter(|found| found.unit == holder.unit) else { return refuse( &mut stream, LeaseRefusalKind::UnknownCaller, - "this process is not in the Self unit", + "this process is not in the configured unit", ); }; let now = unix_ms(); @@ -522,7 +508,7 @@ impl Lender { // plan the refusal reads is the one this process last observed, but a // cell with no weekly reading (a restart empties it) gets the meter's // first read, bounded, before the lease is lent "unobserved" for its - // whole life. The request is the swarm's sign of life, however it + // whole life. The request is the holder's sign of life, however it // ends: the meter reads while one is held or lately asked for. let _asking = self.quota.asking(); let plan = self.quota.snapshot_with_week(FIRST_READ_WAIT); @@ -532,8 +518,8 @@ impl Lender { .lock() .map_err(|_| io::Error::other("service lock"))? .begin_lease( - &caller.caller_id, - caller.turn, + &holder.caller_id, + holder.scope, &invocation.invocation_id, request.expires_at_unix_ms, now, @@ -562,7 +548,7 @@ impl Lender { }; self.hold( stream, - caller, + holder, &grant, &invocation, peer.process, @@ -579,7 +565,7 @@ impl Lender { fn hold( &self, mut stream: UnixStream, - caller: &LeaseCaller, + holder: &LeaseHolder, grant: &LeaseGrant, invocation: &PeerUnit, process: Option, @@ -588,7 +574,7 @@ impl Lender { ) -> io::Result<()> { let held = self.keep( &mut stream, - caller, + holder, grant, invocation, process.as_ref(), @@ -598,7 +584,7 @@ impl Lender { self.service .lock() .map_err(|_| io::Error::other("service lock"))? - .end_lease(&caller.caller_id, &grant.lease_id); + .end_lease(&holder.caller_id, &grant.lease_id); held } @@ -607,7 +593,7 @@ impl Lender { fn keep( &self, stream: &mut UnixStream, - caller: &LeaseCaller, + holder: &LeaseHolder, grant: &LeaseGrant, invocation: &PeerUnit, process: Option<&OwnedFd>, @@ -651,7 +637,7 @@ impl Lender { Err(_) => return Ok(()), } let still = process - .and_then(|process| self.units.invocation_in(process.as_fd(), &caller.unit())) + .and_then(|process| self.units.invocation_in(process.as_fd(), &holder.unit)) .is_some_and(|found| found == *invocation); if !still { return Ok(()); @@ -707,7 +693,11 @@ mod tests { let service = Arc::new(Mutex::new( TransportService::open( &dir.join("replay.cc"), - "claude-code", + model_connector::ProviderRoutes::new([( + "model".to_string(), + "claude-code".to_string(), + )]) + .unwrap(), [model_connector::CallerAdmission::new( "lease-test-caller", "lease-test-connection-key", @@ -723,7 +713,7 @@ mod tests { .unwrap(), )); let lender = Lender { - callers: Vec::new(), + holders: Vec::new(), limits: LeaseLimits { socket_timeout: Duration::from_secs(2), max_lease_ms: 3_600_000, @@ -747,7 +737,7 @@ mod tests { thread::spawn(move || { let _ = serve_leases( &listener, - lender.callers, + lender.holders, lender.limits, service, quota, diff --git a/crates/claude-connector/src/lease_run.rs b/crates/claude-connector/src/lease_run.rs new file mode 100644 index 0000000..0ad25b3 --- /dev/null +++ b/crates/claude-connector/src/lease_run.rs @@ -0,0 +1,379 @@ +//! Runs a command with a lent subscription token delivered on descriptor 3 +//! (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3`). +//! +//! Connects to the connector's lease socket, requests a lease, receives the +//! grant frame and the pipe read descriptor via `SCM_RIGHTS`, spawns the child +//! with the descriptor placed at fd 3, drops the parent's copy of the pipe, +//! holds the unix socket open until the child exits, and returns the child's +//! exit status. Never reads the token bytes or writes them (or any path or +//! refusal detail) to the environment, argv, or stderr. + +use std::io::{self, ErrorKind, Write}; +use std::mem::{size_of, zeroed}; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; +use std::os::unix::net::UnixStream; +use std::os::unix::process::CommandExt; +use std::path::PathBuf; +use std::process::{Command, ExitStatus}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use crate::launch::{TOKEN_FD, TOKEN_FD_VAR}; +use crate::lease::{ + LeaseMessage, LeaseRefusalKind, LeaseRequest, MAX_LEASE_FRAME_BYTES, decode_frame, encode_frame, +}; +use crate::process::place_fd; + +/// Default lease lifetime requested when `--ttl-secs` is omitted (59 minutes). +pub const DEFAULT_TTL_SECS: u64 = 3_540; + +/// Timeout applied to the initial request write and grant frame read. +const SOCKET_TIMEOUT: Duration = Duration::from_secs(30); + +/// Arguments for [`lease_run`]. +#[derive(Debug, Clone)] +pub struct LeaseRunArgs { + pub socket: PathBuf, + pub ttl: Duration, + pub program: String, + pub args: Vec, +} + +/// Failures from requesting a lease or launching the child; never echoes +/// input paths, program names, token bytes, or lender refusal detail text. +#[derive(Debug, thiserror::Error)] +pub enum LeaseRunError { + #[error("the lease ttl is invalid")] + Ttl, + #[error("the system clock could not be read")] + Clock, + #[error("the lease program is missing")] + Program, + #[error("the lease socket connection failed: {0}")] + Connect(ErrorKind), + #[error("the lease request could not be sent: {0}")] + Send(ErrorKind), + #[error("the lease reply could not be read: {0}")] + Receive(ErrorKind), + #[error("the lease reply frame is malformed")] + Frame, + #[error("the lease grant did not carry exactly one token descriptor")] + UnexpectedFds, + #[error("the lease request was refused: {0:?}")] + Refused(LeaseRefusalKind), + #[error("the leased command could not be spawned: {0}")] + Spawn(ErrorKind), + #[error("waiting on the leased command failed: {0}")] + Wait(ErrorKind), +} + +/// Requests a credential lease over `args.socket`, spawns `args.program` with +/// `args.args` and the token pipe placed at [`TOKEN_FD`] (`TOKEN_FD_VAR=3`), +/// holds the socket open until the child exits, and returns the child's status. +pub fn lease_run(args: &LeaseRunArgs) -> Result { + if args.program.is_empty() { + return Err(LeaseRunError::Program); + } + let ttl_ms = u64::try_from(args.ttl.as_millis()) + .ok() + .filter(|ms| *ms > 0) + .ok_or(LeaseRunError::Ttl)?; + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|_| LeaseRunError::Clock) + .and_then(|elapsed| u64::try_from(elapsed.as_millis()).map_err(|_| LeaseRunError::Clock))?; + let expires_at_unix_ms = now_ms.checked_add(ttl_ms).ok_or(LeaseRunError::Ttl)?; + + let mut stream = + UnixStream::connect(&args.socket).map_err(|error| LeaseRunError::Connect(error.kind()))?; + stream + .set_write_timeout(Some(SOCKET_TIMEOUT)) + .map_err(|error| LeaseRunError::Send(error.kind()))?; + stream + .set_read_timeout(Some(SOCKET_TIMEOUT)) + .map_err(|error| LeaseRunError::Receive(error.kind()))?; + + let request = encode_frame(&LeaseMessage::ClaudeLeaseRequest(LeaseRequest { + expires_at_unix_ms, + })); + stream + .write_all(&request) + .map_err(|error| LeaseRunError::Send(error.kind()))?; + + let (frame, fds) = recv_frame_with_fds(&stream)?; + let message = decode_frame(&frame).ok_or(LeaseRunError::Frame)?; + match message { + LeaseMessage::ClaudeLeaseRefusal(refusal) => Err(LeaseRunError::Refused(refusal.kind)), + LeaseMessage::ClaudeLeaseGrant(_) => { + if fds.len() != 1 { + return Err(LeaseRunError::UnexpectedFds); + } + let token_fd = fds.into_iter().next().ok_or(LeaseRunError::UnexpectedFds)?; + spawn_and_hold(stream, token_fd, &args.program, &args.args) + } + _ => Err(LeaseRunError::Frame), + } +} + +fn spawn_and_hold( + stream: UnixStream, + token_fd: OwnedFd, + program: &str, + args: &[String], +) -> Result { + let mut command = Command::new(program); + command.args(args).env(TOKEN_FD_VAR, TOKEN_FD.to_string()); + let source = token_fd.as_raw_fd(); + // SAFETY: `place_fd` calls only async-signal-safe `dup2` and `fcntl`. + unsafe { + command.pre_exec(move || place_fd(source, TOKEN_FD)); + } + let mut child = command + .spawn() + .map_err(|error| LeaseRunError::Spawn(error.kind()))?; + drop(token_fd); + let status = child + .wait() + .map_err(|error| LeaseRunError::Wait(error.kind()))?; + drop(stream); + Ok(status) +} + +fn recv_frame_with_fds(stream: &UnixStream) -> Result<(Vec, Vec), LeaseRunError> { + let mut frame = Vec::new(); + let mut fds = Vec::new(); + let mut expected_total: Option = None; + let mut chunk = vec![0_u8; 4 + MAX_LEASE_FRAME_BYTES + 1]; + + loop { + let read_cap = match expected_total { + None => chunk.len(), + Some(total) => (total - frame.len()) + 1, + }; + let (received, mut chunk_fds) = recv_chunk(stream, &mut chunk[..read_cap])?; + fds.append(&mut chunk_fds); + if received == 0 { + return Err(LeaseRunError::Frame); + } + frame.extend_from_slice(&chunk[..received]); + if expected_total.is_none() && frame.len() >= 4 { + let len = u32::from_be_bytes([frame[0], frame[1], frame[2], frame[3]]) as usize; + if len == 0 || len > MAX_LEASE_FRAME_BYTES { + return Err(LeaseRunError::Frame); + } + expected_total = Some(4 + len); + } + if let Some(total) = expected_total { + if frame.len() > total { + return Err(LeaseRunError::Frame); + } + if frame.len() == total { + return Ok((frame, fds)); + } + } + } +} + +fn recv_chunk(stream: &UnixStream, buf: &mut [u8]) -> Result<(usize, Vec), LeaseRunError> { + const MAX_CMSG_FDS: usize = 16; + // SAFETY: `CMSG_SPACE` is a pure size computation. + let space = unsafe { libc::CMSG_SPACE((MAX_CMSG_FDS * size_of::()) as u32) } as usize; + let mut control = vec![0_u64; space.div_ceil(size_of::())]; + let mut vector = libc::iovec { + iov_base: buf.as_mut_ptr().cast(), + iov_len: buf.len(), + }; + // SAFETY: `buf` and `control` outlive `recvmsg`; `msg_controllen` matches the + // byte length of `control`; descriptors received via `SCM_RIGHTS` with + // `MSG_CMSG_CLOEXEC` are newly installed in this process and owned nowhere else. + unsafe { + let mut message: libc::msghdr = zeroed(); + message.msg_iov = &mut vector; + message.msg_iovlen = 1; + message.msg_control = control.as_mut_ptr().cast(); + message.msg_controllen = (control.len() * size_of::()) as _; + let received = loop { + let n = libc::recvmsg(stream.as_raw_fd(), &mut message, libc::MSG_CMSG_CLOEXEC); + if n >= 0 || io::Error::last_os_error().kind() != ErrorKind::Interrupted { + break n; + } + }; + if received < 0 { + return Err(LeaseRunError::Receive(io::Error::last_os_error().kind())); + } + let mut fds = Vec::new(); + let mut header = libc::CMSG_FIRSTHDR(&message); + while !header.is_null() { + if (*header).cmsg_level == libc::SOL_SOCKET && (*header).cmsg_type == libc::SCM_RIGHTS { + let cmsg_len = (*header).cmsg_len as usize; + let base = libc::CMSG_LEN(0) as usize; + if cmsg_len >= base { + let data = libc::CMSG_DATA(header).cast::(); + for index in 0..(cmsg_len - base) / size_of::() { + fds.push(OwnedFd::from_raw_fd(data.add(index).read_unaligned())); + } + } + } + header = libc::CMSG_NXTHDR(&message, header); + } + if (message.msg_flags & libc::MSG_CTRUNC) != 0 { + return Err(LeaseRunError::UnexpectedFds); + } + Ok((received as usize, fds)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::lease::{LeaseGranted, LeaseRefused}; + + fn roundtrip_bytes(bytes: &[u8]) -> Result<(Vec, Vec), LeaseRunError> { + let (rx, mut tx) = UnixStream::pair().unwrap(); + let data = bytes.to_vec(); + let writer = std::thread::spawn(move || { + let _ = tx.write_all(&data); + drop(tx); + }); + let result = recv_frame_with_fds(&rx); + writer.join().unwrap(); + result + } + + #[test] + fn zero_ttl_is_rejected_before_connecting() { + let args = LeaseRunArgs { + socket: PathBuf::from("/nonexistent/lease.sock"), + ttl: Duration::ZERO, + program: "/bin/true".to_string(), + args: vec![], + }; + assert!(matches!(lease_run(&args), Err(LeaseRunError::Ttl))); + } + + #[test] + fn recv_rejects_zero_over_bound_truncated_and_trailing_frames() { + assert!(matches!(roundtrip_bytes(&[]), Err(LeaseRunError::Frame))); + assert!(matches!( + roundtrip_bytes(&[0, 0, 0, 0]), + Err(LeaseRunError::Frame) + )); + let over = (MAX_LEASE_FRAME_BYTES as u32 + 1).to_be_bytes(); + assert!(matches!(roundtrip_bytes(&over), Err(LeaseRunError::Frame))); + + let valid = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused { + kind: LeaseRefusalKind::Busy, + detail: "busy".to_string(), + })); + assert!(matches!( + roundtrip_bytes(&valid[..valid.len() - 1]), + Err(LeaseRunError::Frame) + )); + let mut trailing = valid.clone(); + trailing.push(0); + assert!(matches!( + roundtrip_bytes(&trailing), + Err(LeaseRunError::Frame) + )); + let (read, fds) = roundtrip_bytes(&valid).unwrap(); + assert_eq!(read, valid); + assert!(fds.is_empty()); + + // Exact MAX_LEASE_FRAME_BYTES body must be accepted. + let probe = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused { + kind: LeaseRefusalKind::Busy, + detail: "x".repeat(300), + })); + let overhead = probe.len() - 4 - 300; + let max_frame = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused { + kind: LeaseRefusalKind::Busy, + detail: "x".repeat(MAX_LEASE_FRAME_BYTES - overhead), + })); + assert_eq!(max_frame.len(), 4 + MAX_LEASE_FRAME_BYTES); + let (read_max, _) = roundtrip_bytes(&max_frame).unwrap(); + assert_eq!(read_max, max_frame); + } + + #[test] + fn recv_handles_chunked_header_and_body_and_catches_chunked_trailing() { + let valid = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused { + kind: LeaseRefusalKind::Busy, + detail: "chunked-frame-payload".to_string(), + })); + let (rx, mut tx) = UnixStream::pair().unwrap(); + let expected = valid.clone(); + let writer = std::thread::spawn(move || { + tx.write_all(&expected[..2]).unwrap(); + std::thread::sleep(Duration::from_millis(10)); + tx.write_all(&expected[2..expected.len() - 1]).unwrap(); + std::thread::sleep(Duration::from_millis(10)); + tx.write_all(&expected[expected.len() - 1..]).unwrap(); + }); + let (read, fds) = recv_frame_with_fds(&rx).unwrap(); + assert_eq!(read, valid); + assert!(fds.is_empty()); + writer.join().unwrap(); + + let (rx2, mut tx2) = UnixStream::pair().unwrap(); + let mut with_trailing = valid.clone(); + with_trailing.push(0xaa); + let writer2 = std::thread::spawn(move || { + tx2.write_all(&with_trailing[..2]).unwrap(); + std::thread::sleep(Duration::from_millis(10)); + tx2.write_all(&with_trailing[2..]).unwrap(); + }); + assert!(matches!( + recv_frame_with_fds(&rx2), + Err(LeaseRunError::Frame) + )); + writer2.join().unwrap(); + } + + #[test] + fn grant_without_fd_is_rejected_and_refusal_never_echoes_detail() { + let dir = std::env::temp_dir().join(format!("lease-run-unit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let socket = dir.join("lease.sock"); + let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap(); + + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut buf = [0_u8; 256]; + let _ = io::Read::read(&mut stream, &mut buf); + let grant = encode_frame(&LeaseMessage::ClaudeLeaseGrant(LeaseGranted { + lease_id: "lease:1".to_string(), + plan_quota: vec![], + })); + stream.write_all(&grant).unwrap(); + + let (mut stream, _) = listener.accept().unwrap(); + let _ = io::Read::read(&mut stream, &mut buf); + let refusal = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused { + kind: LeaseRefusalKind::ProviderRejected, + detail: "CANARY-DETAIL-SECRET".to_string(), + })); + stream.write_all(&refusal).unwrap(); + }); + + let args = LeaseRunArgs { + socket: socket.clone(), + ttl: Duration::from_secs(DEFAULT_TTL_SECS), + program: "/bin/true".to_string(), + args: vec![], + }; + assert!(matches!( + lease_run(&args), + Err(LeaseRunError::UnexpectedFds) + )); + let err = lease_run(&args).unwrap_err(); + let text = format!("{err} {err:?}"); + assert!(matches!( + err, + LeaseRunError::Refused(LeaseRefusalKind::ProviderRejected) + )); + assert!(!text.contains("CANARY-DETAIL-SECRET"), "{text}"); + + server.join().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/claude-connector/src/lib.rs b/crates/claude-connector/src/lib.rs index 88de37b..e35805c 100644 --- a/crates/claude-connector/src/lib.rs +++ b/crates/claude-connector/src/lib.rs @@ -3,24 +3,36 @@ //! stream-json in and out, with every tool, MCP server, settings source and //! plugin switched off. A binary wires it to [`model_connector::serve`]. +pub mod ask; mod backend; mod config; +mod credential; mod daemon; mod handle; +mod http; mod launch; #[cfg(target_os = "linux")] mod lease; +#[cfg(target_os = "linux")] +pub mod lease_run; +mod messages; mod meter; +mod openai_chat; mod process; mod quota; +mod router; mod stream; #[cfg(target_os = "linux")] mod unit; -pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource}; -pub use config::{ClaudeCodeConfig, ClaudeCodeLimits}; +pub use backend::{ClaudeCodeBackend, StderrSink}; +pub use config::{ + ClaudeCodeConfig, ClaudeCodeLimits, EffortMap, ForcedToolChoice, ModelRow, OutputSchemaSupport, + ProviderEntry, ProviderWire, +}; +pub use credential::{CredentialTokenSource, TokenSource}; pub use daemon::{ - ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, check_ready, load_config, write_config, + ClaudeConnectorConfig, ConfigError, LeaseHolderConfig, check_ready, load_config, write_config, }; #[cfg(unix)] pub use daemon::{check_prompt_dir, serve_config}; @@ -28,13 +40,16 @@ pub use handle::{FsSessionStore, MIN_SECRET_BYTES, SessionStore}; pub use launch::ChildEnv; #[cfg(target_os = "linux")] pub use lease::{ - LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused, + LeaseGranted, LeaseHolder, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused, LeaseRequest, LeaseUsageReadoutRequest, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit, PeerUnits, decode_frame, encode_frame, peer_credentials, serve_leases, user_uid, }; +pub use messages::{MessagesBackend, MessagesConfig}; +pub use openai_chat::{OpenAiChatBackend, OpenAiChatConfig}; #[cfg(unix)] pub use process::StdProcessPort; pub use process::{ProcessPort, RunningChild, StdoutRead}; pub use quota::QuotaCell; +pub use router::RouterBackend; #[cfg(target_os = "linux")] pub use unit::SystemdUnits; diff --git a/crates/claude-connector/src/main.rs b/crates/claude-connector/src/main.rs index 273a4a1..d366be8 100644 --- a/crates/claude-connector/src/main.rs +++ b/crates/claude-connector/src/main.rs @@ -2,37 +2,55 @@ //! //! claude-connector serve --config PATH.cc //! claude-connector config init PATH.cc --flag value ... +//! claude-connector config add-provider PATH.cc --provider ID --wire KIND ... +//! claude-connector config add-model PATH.cc --model ID --provider ID --upstream NAME ... //! claude-connector config add-caller PATH.cc --caller-id ID --connection-key-file F ... -//! claude-connector config add-lease-caller PATH.cc --lease-user U --caller-id ID ... +//! claude-connector config add-lease-holder PATH.cc --lease-user U --caller-id ID --provider P --unit NAME --scope per-caller|per-invocation //! claude-connector config check PATH.cc +//! claude-connector ask --caller-id ID --connection-key-file F --model M (--system TEXT | --system-file F) < prompt +//! claude-connector lease run --socket PATH [--ttl-secs N] -- PROGRAM [ARGS...] //! //! `serve` takes its configuration from the typed document alone. The flags of -//! `config init` exist only to author that document. No message here echoes a -//! value that was typed or stored; refusals name a field or a flag. +//! `config init`, `add-provider`, and `add-model` exist only to author that document. +//! No message here echoes a value that was typed or stored; refusals name a field or a flag. use std::collections::BTreeMap; use std::path::PathBuf; use std::process::ExitCode; +use claude_connector::ask::{self, AskArgs, AskError}; use claude_connector::{ - ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready, + ClaudeConnectorConfig, ConfigError, EffortMap, ForcedToolChoice, LeaseHolderConfig, + MIN_SECRET_BYTES, ModelRow, OutputSchemaSupport, ProviderEntry, ProviderWire, check_ready, load_config, write_config, }; -use model_connector::{CallerConfig, LeaseTurn, frame_bytes_for_payload}; +use model_connector::{CallerConfig, LeaseScope, frame_bytes_for_payload}; fn main() -> ExitCode { let args: Vec = std::env::args().skip(1).collect(); let args: Vec<&str> = args.iter().map(String::as_str).collect(); let result = match args.as_slice() { - ["serve", "--config", path] => serve(path), - ["config", "init", path, flags @ ..] => init(path, flags), - ["config", "add-caller", path, flags @ ..] => add_caller(path, flags), - ["config", "add-lease-caller", path, flags @ ..] => add_lease_caller(path, flags), - ["config", "check", path] => check(path), + ["serve", "--config", path] => serve(path).map(|()| ExitCode::SUCCESS), + ["config", "init", path, flags @ ..] => init(path, flags).map(|()| ExitCode::SUCCESS), + ["config", "add-provider", path, flags @ ..] => { + add_provider(path, flags).map(|()| ExitCode::SUCCESS) + } + ["config", "add-model", path, flags @ ..] => { + add_model(path, flags).map(|()| ExitCode::SUCCESS) + } + ["config", "add-caller", path, flags @ ..] => { + add_caller(path, flags).map(|()| ExitCode::SUCCESS) + } + ["config", "add-lease-holder", path, flags @ ..] => { + add_lease_holder(path, flags).map(|()| ExitCode::SUCCESS) + } + ["config", "check", path] => check(path).map(|()| ExitCode::SUCCESS), + ["ask", flags @ ..] => run_ask(flags).map(|()| ExitCode::SUCCESS), + ["lease", "run", rest @ ..] => run_lease(rest), _ => Err(Failure::Usage), }; match result { - Ok(()) => ExitCode::SUCCESS, + Ok(code) => code, Err(failure) => { eprintln!("claude-connector: {failure}"); ExitCode::FAILURE @@ -43,7 +61,7 @@ fn main() -> ExitCode { #[derive(Debug, thiserror::Error)] enum Failure { #[error( - "usage: serve --config PATH | config init PATH --flag value ... | config add-caller PATH --flag value ... | config add-lease-caller PATH --flag value ... | config check PATH (check reads the credentials from the environment it runs in: run it in the unit's environment)" + "usage: serve --config PATH | config init PATH --flag value ... | config add-provider PATH --flag value ... | config add-model PATH --flag value ... | config add-caller PATH --flag value ... | config add-lease-holder PATH --flag value ... | config check PATH | ask --caller-id ID --connection-key-file FILE --model MODEL (--system TEXT | --system-file FILE) [--endpoint HOST:PORT] [--effort low|medium|high|max] [--max-output-tokens N] [--timeout-secs N] | lease run --socket PATH [--ttl-secs N] -- PROGRAM [ARGS...] (prompt on stdin, answer on stdout) (check reads the credentials from the environment it runs in: run it in the unit's environment)" )] Usage, #[error(transparent)] @@ -52,8 +70,15 @@ enum Failure { Missing(&'static str), #[error("flag {0} is malformed")] Malformed(&'static str), + #[error("flag {0} conflicts with --wire")] + Conflict(&'static str), #[error("a flag is unknown, repeated or has no value")] Flags, + #[error("{0}")] + Ask(#[from] AskError), + #[cfg(target_os = "linux")] + #[error("{0}")] + LeaseRun(#[from] claude_connector::lease_run::LeaseRunError), } #[cfg(unix)] @@ -70,11 +95,75 @@ fn check(path: &str) -> Result<(), Failure> { let config = load_config(path.as_ref())?; check_ready(&config)?; println!("claude connector configuration is valid and ready to serve"); + println!("providers: {}", config.providers.len()); + println!("models: {}", config.models.len()); println!("callers: {}", config.callers.len()); - println!("lease_callers: {}", config.lease_callers.len()); + println!("lease_holders: {}", config.lease_holders.len()); Ok(()) } +const ASK: [&str; 9] = [ + "--endpoint", + "--caller-id", + "--connection-key-file", + "--model", + "--system", + "--system-file", + "--effort", + "--max-output-tokens", + "--timeout-secs", +]; + +/// One no-tools completion: the prompt is all of stdin, the answer is stdout. +fn run_ask(args: &[&str]) -> Result<(), Failure> { + use std::io::{Read, Write}; + + let flags = Flags::parse(args, &[&ASK], &[])?; + let instructions = match ( + flags.single.get("--system"), + flags.single.get("--system-file"), + ) { + (Some(text), None) => text.clone(), + (None, Some(path)) => ask::read_system_file(std::path::Path::new(path))?, + _ => return Err(Failure::Missing("--system or --system-file (exactly one)")), + }; + let effort = match flags.single.get("--effort").map(String::as_str) { + None => None, + Some("low") => Some(model_connector::ReasoningEffort::Low), + Some("medium") => Some(model_connector::ReasoningEffort::Medium), + Some("high") => Some(model_connector::ReasoningEffort::High), + Some("max") => Some(model_connector::ReasoningEffort::Max), + Some(_) => return Err(Failure::Malformed("--effort")), + }; + let endpoint = flags + .single + .get("--endpoint") + .map_or(ask::DEFAULT_ENDPOINT, String::as_str) + .parse() + .map_err(|_| Failure::Malformed("--endpoint"))?; + let mut raw = Vec::new(); + std::io::stdin() + .take(ask::PAYLOAD_BYTES as u64 + 1) + .read_to_end(&mut raw) + .map_err(|_| AskError::StdinRead)?; + let prompt = String::from_utf8(raw).map_err(|_| AskError::StdinNotText)?; + let answer = ask::ask(&AskArgs { + endpoint, + caller_id: flags.text("--caller-id")?, + key_file: flags.path("--connection-key-file")?, + model: flags.text("--model")?, + instructions, + effort, + max_output_tokens: flags.number_or("--max-output-tokens", 8192)?, + timeout: std::time::Duration::from_secs(flags.number_or("--timeout-secs", 300)?), + prompt, + })?; + let mut out = std::io::stdout(); + out.write_all(answer.as_bytes()) + .and_then(|()| out.flush()) + .map_err(|_| AskError::StdoutWrite.into()) +} + /// The flags of one config verb: each single flag at most once, each list /// flag any number of times. struct Flags { @@ -92,31 +181,60 @@ const CALLER: [&str; 5] = [ "--max-output-tokens", ]; -const INIT: [&str; 21] = [ +const INIT: [&str; 8] = [ "--listen", "--replay-store", + "--max-payload-bytes", + "--socket-timeout-ms", + "--lease-socket", + "--lease-max-ms", + "--unit", + "--scope", +]; + +const PROVIDER: [&str; 18] = [ + "--provider", + "--wire", + "--credential", + "--base-url", + "--deadline-ms", + "--max-response-bytes", "--claude-binary", "--claude-sha256", "--work-dir", "--config-dir", "--prompt-dir", - "--instance", - "--token-credential", "--handle-secret-credential", "--handle-secret-file", - "--deadline-ms", + "--instance", "--max-line-bytes", "--max-total-bytes", "--stderr-tail-bytes", - "--max-payload-bytes", - "--socket-timeout-ms", - "--lease-socket", - "--lease-max-ms", - "--turn", - "--lease-unit-instance", + "--meter-model", ]; -const LEASE_CALLER: [&str; 3] = ["--caller-id", "--turn", "--lease-unit-instance"]; +const MODEL: [&str; 11] = [ + "--model", + "--provider", + "--upstream", + "--effort-low", + "--effort-medium", + "--effort-high", + "--effort-max", + "--unset-effort", + "--forced-tool-choice", + "--output-schema", + "--strict-tools", +]; + +const LEASE_HOLDER: [&str; 4] = ["--caller-id", "--provider", "--unit", "--scope"]; + +#[derive(Clone, Copy)] +enum WireKind { + AnthropicMessages, + OpenAiChat, + ClaudeCodeCli, +} impl Flags { fn parse( @@ -159,6 +277,10 @@ impl Flags { self.lists.get(name).map_or(&[], Vec::as_slice) } + fn optional_text(&self, name: &'static str) -> Option { + self.single.get(name).cloned() + } + fn text(&self, name: &'static str) -> Result { self.single.get(name).cloned().ok_or(Failure::Missing(name)) } @@ -173,12 +295,135 @@ impl Flags { .map_err(|_| Failure::Malformed(name)) } - /// The kind of turn a leasing account serves: `self` or `persona`. - fn turn(&self) -> Result { - match self.text("--turn")?.as_str() { - "self" => Ok(LeaseTurn::SelfRun), - "persona" => Ok(LeaseTurn::PersonaTurn), - _ => Err(Failure::Malformed("--turn")), + fn reject_any(&self, conflicting: &[&'static str]) -> Result<(), Failure> { + for &flag in conflicting { + if self.single.contains_key(flag) || self.lists.contains_key(flag) { + return Err(Failure::Conflict(flag)); + } + } + Ok(()) + } + + fn wire(&self) -> Result { + match self.text("--wire")?.as_str() { + "anthropic-messages" => Ok(WireKind::AnthropicMessages), + "openai-chat" => Ok(WireKind::OpenAiChat), + "claude-code-cli" => Ok(WireKind::ClaudeCodeCli), + _ => Err(Failure::Malformed("--wire")), + } + } + + fn forced_tool_choice(&self) -> Result { + match self.text("--forced-tool-choice")?.as_str() { + "always" => Ok(ForcedToolChoice::Always), + "without-thinking" => Ok(ForcedToolChoice::WithoutThinking), + "never" => Ok(ForcedToolChoice::Never), + _ => Err(Failure::Malformed("--forced-tool-choice")), + } + } + + fn output_schema(&self) -> Result { + match self.text("--output-schema")?.as_str() { + "native" => Ok(OutputSchemaSupport::Native), + "none" => Ok(OutputSchemaSupport::None), + _ => Err(Failure::Malformed("--output-schema")), + } + } + + fn bool_flag(&self, name: &'static str) -> Result { + match self.text(name)?.as_str() { + "true" => Ok(true), + "false" => Ok(false), + _ => Err(Failure::Malformed(name)), + } + } + + fn provider_entry(&self, provider_id: &str) -> Result { + const CLI_ONLY: &[&str] = &[ + "--claude-binary", + "--claude-sha256", + "--work-dir", + "--config-dir", + "--prompt-dir", + "--handle-secret-credential", + "--handle-secret-file", + "--instance", + "--max-line-bytes", + "--max-total-bytes", + "--stderr-tail-bytes", + "--meter-model", + ]; + const HTTP_ONLY: &[&str] = &["--base-url", "--max-response-bytes", "--strict-unsupported"]; + + let wire = match self.wire()? { + WireKind::AnthropicMessages => { + self.reject_any(CLI_ONLY)?; + self.reject_any(&["--strict-unsupported"])?; + ProviderWire::AnthropicMessages { + base_url: self.text("--base-url")?, + deadline_ms: self.number_or("--deadline-ms", 600_000)?, + max_response_bytes: self.number_or("--max-response-bytes", 64 << 20)?, + } + } + WireKind::OpenAiChat => { + self.reject_any(CLI_ONLY)?; + ProviderWire::OpenAiChat { + base_url: self.text("--base-url")?, + strict_unsupported: self.list("--strict-unsupported").to_vec(), + deadline_ms: self.number_or("--deadline-ms", 600_000)?, + max_response_bytes: self.number_or("--max-response-bytes", 64 << 20)?, + } + } + WireKind::ClaudeCodeCli => { + self.reject_any(HTTP_ONLY)?; + ProviderWire::ClaudeCodeCli { + binary: self.path("--claude-binary")?, + binary_sha256: sha256(&self.text("--claude-sha256")?) + .ok_or(Failure::Malformed("--claude-sha256"))?, + work_dir: self.path("--work-dir")?, + config_dir: self.path("--config-dir")?, + prompt_dir: self.path("--prompt-dir")?, + handle_secret_credential: self.text("--handle-secret-credential")?, + instance: self.text("--instance")?, + deadline_ms: self.number_or("--deadline-ms", 600_000)?, + max_line_bytes: self.number_or("--max-line-bytes", 4 << 20)?, + max_total_bytes: self.number_or("--max-total-bytes", 64 << 20)?, + stderr_tail_bytes: self.number_or("--stderr-tail-bytes", 8192)?, + meter_model: self.optional_text("--meter-model"), + } + } + }; + Ok(ProviderEntry { + id: provider_id.to_string(), + credential: self.optional_text("--credential"), + wire, + }) + } + + fn model_row(&self, provider_id: &str) -> Result { + Ok(ModelRow { + id: self.text("--model")?, + provider: provider_id.to_string(), + upstream: self.text("--upstream")?, + efforts: EffortMap { + low: self.optional_text("--effort-low"), + medium: self.optional_text("--effort-medium"), + high: self.optional_text("--effort-high"), + max: self.optional_text("--effort-max"), + }, + unset_effort: self.optional_text("--unset-effort"), + forced_tool_choice: self.forced_tool_choice()?, + output_schema: self.output_schema()?, + strict_tools: self.bool_flag("--strict-tools")?, + }) + } + + /// The exclusivity scope a leasing account holds: `per-caller` or `per-invocation`. + fn scope(&self) -> Result { + match self.text("--scope")?.as_str() { + "per-caller" => Ok(LeaseScope::PerCaller), + "per-invocation" => Ok(LeaseScope::PerInvocation), + _ => Err(Failure::Malformed("--scope")), } } @@ -283,51 +528,77 @@ fn ensure_secret_file(_: &std::path::Path) -> Result<(), Failure> { fn init(path: &str, args: &[&str]) -> Result<(), Failure> { let flags = Flags::parse( args, - &[&INIT, &CALLER], - &["--allowed-model", "--lease-user"], + &[&INIT, &PROVIDER, &MODEL, &CALLER], + &["--allowed-model", "--lease-user", "--strict-unsupported"], )?; + let provider_id = flags.text("--provider")?; + let provider = flags.provider_entry(&provider_id)?; + let model = flags.model_row(&provider_id)?; let first = flags.caller()?; - let lease_callers = flags + let lease_holders = flags .list("--lease-user") .iter() .map(|unix_user| { - Ok(LeaseCallerConfig { + Ok(LeaseHolderConfig { unix_user: unix_user.clone(), caller_id: first.caller_runtime_id.clone(), - turn: flags.turn()?, - unit_instance: flags.text("--lease-unit-instance")?, + provider: provider_id.clone(), + unit: flags.text("--unit")?, + scope: flags.scope()?, }) }) .collect::, Failure>>()?; - let secret_file = flags.path("--handle-secret-file")?; + let secret_file = matches!(provider.wire, ProviderWire::ClaudeCodeCli { .. }) + .then(|| flags.single.get("--handle-secret-file").map(PathBuf::from)) + .flatten(); let config = ClaudeConnectorConfig { listen: flags.text("--listen")?, replay_store: flags.path("--replay-store")?, - claude_binary: flags.path("--claude-binary")?, - claude_binary_sha256: sha256(&flags.text("--claude-sha256")?) - .ok_or(Failure::Malformed("--claude-sha256"))?, - work_dir: flags.path("--work-dir")?, - config_dir: flags.path("--config-dir")?, - prompt_dir: flags.path("--prompt-dir")?, - instance: flags.text("--instance")?, - token_credential: flags.text("--token-credential")?, - deadline_ms: flags.number_or("--deadline-ms", 600_000)?, - max_line_bytes: flags.number_or("--max-line-bytes", 4 << 20)?, - max_total_bytes: flags.number_or("--max-total-bytes", 64 << 20)?, - stderr_tail_bytes: flags.number_or("--stderr-tail-bytes", 8192)?, max_frame_bytes: frame_bytes_for_payload(first.max_payload_bytes), max_connections: first.max_concurrent_requests.max(8), socket_timeout_ms: flags.number_or("--socket-timeout-ms", 10_000)?, max_expiry_skew_ms: 300_000, + providers: vec![provider], + models: vec![model], callers: vec![first], lease_socket: flags.single.get("--lease-socket").map(PathBuf::from), - lease_callers, + lease_holders, lease_max_ms: flags.number_or("--lease-max-ms", 3_600_000)?, - handle_secret_credential: flags.text("--handle-secret-credential")?, }; // Validate before the secret file exists: a refused document leaves nothing. config.validate()?; - ensure_secret_file(&secret_file)?; + if let Some(secret_file) = secret_file { + ensure_secret_file(&secret_file)?; + } + write_config(path.as_ref(), &config)?; + Ok(()) +} + +/// Appends one provider entry to an existing document. +fn add_provider(path: &str, args: &[&str]) -> Result<(), Failure> { + let flags = Flags::parse(args, &[&PROVIDER], &["--strict-unsupported"])?; + let provider_id = flags.text("--provider")?; + let provider = flags.provider_entry(&provider_id)?; + let secret_file = matches!(provider.wire, ProviderWire::ClaudeCodeCli { .. }) + .then(|| flags.single.get("--handle-secret-file").map(PathBuf::from)) + .flatten(); + let mut config = load_config(path.as_ref())?; + config.providers.push(provider); + config.validate()?; + if let Some(secret_file) = secret_file { + ensure_secret_file(&secret_file)?; + } + write_config(path.as_ref(), &config)?; + Ok(()) +} + +/// Appends one model row to an existing document. +fn add_model(path: &str, args: &[&str]) -> Result<(), Failure> { + let flags = Flags::parse(args, &[&MODEL], &[])?; + let provider_id = flags.text("--provider")?; + let model = flags.model_row(&provider_id)?; + let mut config = load_config(path.as_ref())?; + config.models.push(model); write_config(path.as_ref(), &config)?; Ok(()) } @@ -356,20 +627,62 @@ fn add_caller(path: &str, args: &[&str]) -> Result<(), Failure> { Ok(()) } -/// Appends one leasing account to an existing document that lends a token. -fn add_lease_caller(path: &str, args: &[&str]) -> Result<(), Failure> { - let flags = Flags::parse(args, &[&LEASE_CALLER, &["--lease-user"]], &[])?; +/// Appends one lease holder to an existing document that lends a token. +fn add_lease_holder(path: &str, args: &[&str]) -> Result<(), Failure> { + let flags = Flags::parse(args, &[&LEASE_HOLDER, &["--lease-user"]], &[])?; let mut config = load_config(path.as_ref())?; - config.lease_callers.push(LeaseCallerConfig { + config.lease_holders.push(LeaseHolderConfig { unix_user: flags.text("--lease-user")?, caller_id: flags.text("--caller-id")?, - turn: flags.turn()?, - unit_instance: flags.text("--lease-unit-instance")?, + provider: flags.text("--provider")?, + unit: flags.text("--unit")?, + scope: flags.scope()?, }); write_config(path.as_ref(), &config)?; Ok(()) } +#[cfg(target_os = "linux")] +fn run_lease(args: &[&str]) -> Result { + use std::os::unix::process::ExitStatusExt; + use std::time::Duration; + + use claude_connector::lease_run::{DEFAULT_TTL_SECS, LeaseRunArgs, lease_run}; + + let Some(sep) = args.iter().position(|arg| *arg == "--") else { + return Err(Failure::Usage); + }; + let (flag_args, cmd_args) = (&args[..sep], &args[sep + 1..]); + let Some((&program, program_args)) = cmd_args.split_first() else { + return Err(Failure::Usage); + }; + if program.is_empty() { + return Err(Failure::Usage); + } + let flags = Flags::parse(flag_args, &[&["--socket", "--ttl-secs"]], &[])?; + let socket = flags.path("--socket")?; + let ttl_secs: u64 = flags.number_or("--ttl-secs", DEFAULT_TTL_SECS)?; + if ttl_secs == 0 { + return Err(Failure::Malformed("--ttl-secs")); + } + let status = lease_run(&LeaseRunArgs { + socket, + ttl: Duration::from_secs(ttl_secs), + program: program.to_string(), + args: program_args.iter().map(|arg| (*arg).to_string()).collect(), + })?; + let code = status + .code() + .or_else(|| status.signal().map(|signal| 128 + signal)) + .unwrap_or(1); + Ok(ExitCode::from(u8::try_from(code).unwrap_or(1))) +} + +#[cfg(not(target_os = "linux"))] +fn run_lease(_: &[&str]) -> Result { + Err(Failure::Usage) +} + #[cfg(all(test, unix))] mod tests { use std::os::unix::fs::{MetadataExt, PermissionsExt}; diff --git a/crates/claude-connector/src/messages.rs b/crates/claude-connector/src/messages.rs new file mode 100644 index 0000000..5037a30 --- /dev/null +++ b/crates/claude-connector/src/messages.rs @@ -0,0 +1,522 @@ +//! The Messages API backend: one non-streaming `POST /v1/messages` per call +//! against a configured `base_url` with an optional systemd API key credential +//! (omitted only for keyless loopback HTTP). The `claude` CLI is never spawned +//! for it. Tools, tool calls and results, thinking blocks, cache breakpoints +//! and cache usage map natively; the contract's shapes are unchanged. +//! +//! API facts this module follows were read from the Claude API reference on +//! 2026-11-29 (`anthropic-version: 2026-10-21`): +//! - Per-model `ModelRow` policies govern forced `tool_choice` +//! (`Always`, `WithoutThinking`, `Never`), `OutputSchemaSupport`, and +//! `EffortMap` / `unset_effort`. [`ToolChoice::Required`] is `tool_choice: any` +//! when permitted and a typed refusal before sending otherwise; the request's +//! `system` never depends on it. Thinking is `{"type":"adaptive"}` with +//! `output_config.effort`, and a request's output schema is +//! `output_config.format` (`json_schema`) when `OutputSchemaSupport::Native`. +//! - A thinking block is replayed unchanged when tagged with this entry's +//! `provider_id`, in transcript order; the API drops one its model cannot +//! read. Its `signature` is the provider's. +//! - Usage reports thinking tokens in `output_tokens_details.thinking_tokens` +//! (a detail of `output_tokens`) and `input_tokens` apart from `cache_read_input_tokens` and +//! `cache_creation_input_tokens`. +//! +//! When configured, the key is read from the systemd credential at every call +//! and reaches the HTTP client as the `x-api-key` header; it is in no +//! environment, argument, log line or message. A failed call is never run again, +//! and a redirect is never followed: it would carry the key to whatever host it +//! names. +//! +//! Failures are typed as the Persona drain reads them: no answer could be had +//! (connection, deadline, 5xx, 429, 402, 3xx) is an outage kind, and only a +//! request or answer the provider refused is a strike. Two 400 +//! `invalid_request_error` answers are the exception: the provider reports a +//! spent balance and the operator's Console spend limit as a 400 whose message +//! begins with a fixed string (`SPEND_EXHAUSTED`), and only that string tells +//! them from a bad request, so they are matched, as 402 is, to `Authentication`. +//! +//! The assistant turn is replayed from what the contract carries: thinking +//! blocks as parsed, text by its text, tool calls by id, name and input. The +//! contract has no shape for a block of another type or for a tool call's other +//! fields, and the API rejects an empty text block, so those are not replayed; +//! with no server tools sent, no response carries one. + +use std::time::Duration; + +use model_connector::{ + CacheRetention, FailureKind, InputItem, ProviderRequest, StopReason, ToolChoice, + TransportEvent, TransportEventPayload, TransportOutcome, Usage, +}; +use serde_json::{Map, Value, json}; + +use crate::config::{ModelRow, OutputSchemaSupport}; +use crate::credential::{CredentialTokenSource, TokenSource, credential_ready}; +use crate::http::{build_agent, failed, read_key, transport_failure, zero_usage}; + +const API_VERSION: &str = "2026-10-21"; +const BACKEND_LABEL: &str = "anthropic-messages"; + +/// What the connector's binary hands the backend. +#[derive(Debug, Clone)] +pub struct MessagesConfig { + /// Provider tag written on receipts and matched on reasoning state items. + pub provider_id: String, + /// Base URL for the Messages API (`https://...` or loopback `http://...`). + pub base_url: String, + /// The name of the systemd credential that holds the API key, under + /// `$CREDENTIALS_DIRECTORY`; `None` only for a loopback HTTP `base_url`. + pub key_credential: Option, + /// The whole call, connect to the last byte of the response. + pub deadline: Duration, + /// The largest response body read. + pub max_response_bytes: usize, +} + +/// Answers each call with one HTTP request to the Messages API. +pub struct MessagesBackend { + provider_id: String, + agent: ureq::Agent, + base_url: String, + keys: Option>, + max_response_bytes: u64, +} + +impl MessagesBackend { + /// The backend over the configured base URL, with an optional key read from + /// the credential `config.key_credential` names. + pub fn new(config: MessagesConfig) -> Self { + let keys = config.key_credential.as_ref().map(|name| { + Box::new(CredentialTokenSource::from_environment(name.clone())) as Box + }); + Self::with_parts(config, keys) + } + + pub(crate) fn with_parts(config: MessagesConfig, keys: Option>) -> Self { + Self { + provider_id: config.provider_id, + agent: build_agent(config.deadline), + base_url: config.base_url, + keys, + max_response_bytes: config.max_response_bytes as u64, + } + } + + pub fn provider_id(&self) -> &str { + &self.provider_id + } + + pub fn ready(&self) -> Result<(), &'static str> { + match &self.keys { + Some(source) => credential_ready(source.as_ref()), + None => Ok(()), + } + } + + pub(crate) fn run_model( + &self, + request: &ProviderRequest, + row: &ModelRow, + ) -> (Vec, TransportOutcome) { + let key = match read_key(self.keys.as_deref(), BACKEND_LABEL) { + Ok(key) => key, + Err(failure) => return failure, + }; + let body = match render(request, &self.provider_id, row).and_then(|body| { + serde_json::to_vec(&body).map_err(|_| "the request could not be encoded".to_string()) + }) { + Ok(body) => body, + Err(message) => { + return failed( + FailureKind::InvalidRequest, + format!("{BACKEND_LABEL}: {message}"), + Some(zero_usage()), + ); + } + }; + let mut post = self + .agent + .post(format!("{}/v1/messages", self.base_url)) + .header("anthropic-version", API_VERSION) + .header("content-type", "application/json"); + if let Some(key) = &key { + post = post.header("x-api-key", key.as_str()); + } + let sent = post.send(&body[..]); + let mut response = match sent { + Ok(response) => response, + Err(error) => return transport_failure(BACKEND_LABEL, &error), + }; + let status = response.status().as_u16(); + let text = match response + .body_mut() + .with_config() + .limit(self.max_response_bytes) + .read_to_vec() + { + Ok(bytes) => bytes, + Err(error) => return transport_failure(BACKEND_LABEL, &error), + }; + if !(200..300).contains(&status) { + return crate::http::http_failure( + BACKEND_LABEL, + status, + &text, + key.as_deref().map(String::as_str), + spend_exhausted, + ); + } + let required = request.tool_choice == ToolChoice::Required && !request.tools.is_empty(); + match parse(&text, required) { + Ok(done) => { + let events = done + .payloads + .into_iter() + .enumerate() + .map(|(sequence, payload)| TransportEvent { + sequence: sequence as u64, + payload, + }) + .collect(); + ( + events, + TransportOutcome::Completed { + provider_response_id: done.id, + stop_reason: done.stop_reason, + usage: done.usage, + }, + ) + } + Err(failure) => failed(failure.kind, failure.message, failure.usage), + } + } +} + +// ---- request ---- + +/// The request body, or what is wrong with the request. +fn render(request: &ProviderRequest, provider_id: &str, row: &ModelRow) -> Result { + let effort = row.resolve_effort(request.reasoning_effort)?; + if request.tool_choice == ToolChoice::Required + && !row.allows_forced_tool_choice(ModelRow::thinking_active(effort)) + { + return Err(format!( + "model {} does not accept a required tool choice", + row.id + )); + } + + let mut body = Map::new(); + body.insert("model".into(), json!(request.model)); + body.insert("max_tokens".into(), json!(request.max_output_tokens)); + + // Breakpoints, when caching is asked: after the tools, after the system + // prompt and on the last message (three of the API's four). The render + // order is tools, system, messages, and an entry is written only where a + // breakpoint sits, so the stable prefix is reused by a later turn whose + // messages differ. + let mark = request.cache_retention.map(cache_mark); + + let mut system = json!({"type": "text", "text": request.instructions}); + if let Some(mark) = &mark { + system["cache_control"] = mark.clone(); + } + body.insert("system".into(), json!([system])); + + let mut messages = messages_of(&request.input, provider_id)?; + if let Some(mark) = &mark { + mark_last_message(&mut messages, mark.clone()); + } + body.insert("messages".into(), Value::Array(messages)); + + if !request.tools.is_empty() { + let mut tools = Vec::with_capacity(request.tools.len()); + for tool in &request.tools { + let schema: Value = serde_json::from_str(&tool.parameters_json) + .map_err(|_| format!("tool {} has parameters that are not JSON", tool.name))?; + tools.push(json!({ + "name": tool.name, + "description": tool.description, + "input_schema": schema, + })); + } + if let (Some(mark), Some(last)) = (&mark, tools.last_mut()) { + last["cache_control"] = mark.clone(); + } + body.insert("tools".into(), Value::Array(tools)); + let kind = if request.tool_choice == ToolChoice::Required { + Some("any") + } else if !request.parallel_tool_calls { + Some("auto") + } else { + None + }; + if let Some(kind) = kind { + let mut choice = json!({"type": kind}); + if !request.parallel_tool_calls { + choice["disable_parallel_tool_use"] = json!(true); + } + body.insert("tool_choice".into(), choice); + } + } + + let mut output = Map::new(); + if let Some(level) = effort { + body.insert("thinking".into(), json!({"type": "adaptive"})); + output.insert("effort".into(), json!(level)); + } + if let Some(schema) = &request.output_schema_json { + if row.output_schema == OutputSchemaSupport::None { + return Err(format!("model {} does not accept an output schema", row.id)); + } + let schema: Value = serde_json::from_str(schema) + .map_err(|_| "the output schema is not JSON".to_string())?; + output.insert( + "format".into(), + json!({"type": "json_schema", "schema": schema}), + ); + } + if !output.is_empty() { + body.insert("output_config".into(), Value::Object(output)); + } + Ok(Value::Object(body)) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Role { + User, + Assistant, +} + +/// The transcript as alternating messages: consecutive assistant-side items +/// (reasoning, text, tool calls) are one assistant message in their order, +/// consecutive user-side items (text, tool results) one user message with its +/// tool results first, as the API requires. +fn messages_of(input: &[InputItem], provider_id: &str) -> Result, String> { + let mut messages: Vec = Vec::new(); + let mut open: Option<(Role, Vec)> = None; + for item in input { + let (role, block) = block_of(item, provider_id)?; + match &mut open { + Some((current, blocks)) if *current == role => blocks.push(block), + _ => { + if let Some(done) = open.take() { + messages.push(message_of(done)); + } + open = Some((role, vec![block])); + } + } + } + if let Some(done) = open { + messages.push(message_of(done)); + } + Ok(messages) +} + +fn message_of((role, mut blocks): (Role, Vec)) -> Value { + if role == Role::User { + blocks.sort_by_key(|block| block["type"] != "tool_result"); + } + json!({ + "role": if role == Role::User { "user" } else { "assistant" }, + "content": blocks, + }) +} + +fn block_of(item: &InputItem, provider_id: &str) -> Result<(Role, Value), String> { + Ok(match item { + InputItem::UserText { text } => (Role::User, json!({"type": "text", "text": text})), + InputItem::AssistantText { text } => { + (Role::Assistant, json!({"type": "text", "text": text})) + } + InputItem::ToolCall { + call_id, + name, + arguments, + } => { + let input: Value = serde_json::from_str(arguments) + .ok() + .filter(Value::is_object) + .ok_or_else(|| format!("the arguments of call {call_id} are not a JSON object"))?; + ( + Role::Assistant, + json!({"type": "tool_use", "id": call_id, "name": name, "input": input}), + ) + } + InputItem::ToolResult { call_id, output } => ( + Role::User, + json!({"type": "tool_result", "tool_use_id": call_id, "content": output}), + ), + InputItem::ReasoningState { + provider, state, .. + } => { + let block: Value = serde_json::from_slice(state) + .ok() + .filter(|block: &Value| { + provider == provider_id + && matches!( + block["type"].as_str(), + Some("thinking" | "redacted_thinking") + ) + }) + .ok_or_else(|| { + "a reasoning state is not a thinking block of this provider".to_string() + })?; + (Role::Assistant, block) + } + }) +} + +fn cache_mark(retention: CacheRetention) -> Value { + match retention { + CacheRetention::Short => json!({"type": "ephemeral"}), + CacheRetention::Long => json!({"type": "ephemeral", "ttl": "1h"}), + } +} + +/// Puts the breakpoint on the last block of the last message that can carry +/// it (a thinking block cannot). +fn mark_last_message(messages: &mut [Value], mark: Value) { + let Some(blocks) = messages + .last_mut() + .and_then(|message| message["content"].as_array_mut()) + else { + return; + }; + if let Some(block) = blocks.iter_mut().rev().find(|block| { + !matches!( + block["type"].as_str(), + Some("thinking" | "redacted_thinking") + ) + }) { + block["cache_control"] = mark; + } +} + +// ---- response ---- + +struct Done { + id: Option, + payloads: Vec, + stop_reason: StopReason, + usage: Usage, +} + +struct Failure { + kind: FailureKind, + message: String, + usage: Option, +} + +/// `required`: the request forced a tool call, so an answer without one is a +/// failure, never a completed turn. +fn parse(bytes: &[u8], required: bool) -> Result { + let provider_failure = |message: &str, usage: Option| Failure { + kind: FailureKind::Provider, + message: format!("anthropic-messages: {message}"), + usage, + }; + let response: Value = serde_json::from_slice(bytes) + .map_err(|_| provider_failure("the response is not JSON", None))?; + let usage = usage_of(&response["usage"]); + let blocks = response["content"] + .as_array() + .ok_or_else(|| provider_failure("the response has no content", usage.clone()))?; + let mut payloads = Vec::new(); + for block in blocks { + match block["type"].as_str() { + Some("text") => { + if let Some(text) = block["text"].as_str().filter(|text| !text.is_empty()) { + payloads.push(TransportEventPayload::TextDelta { + text: text.to_string(), + }); + } + } + Some("tool_use") => { + let (Some(id), Some(name)) = (block["id"].as_str(), block["name"].as_str()) else { + return Err(provider_failure("a tool call has no id or name", usage)); + }; + payloads.push(TransportEventPayload::ToolCall { + call_id: id.to_string(), + name: name.to_string(), + arguments: serde_json::to_string(&block["input"]).unwrap_or_default(), + }); + } + Some("thinking" | "redacted_thinking") => { + payloads.push(TransportEventPayload::ReasoningState { + state: serde_json::to_vec(block).unwrap_or_default(), + }); + } + _ => {} + } + } + if required + && !payloads + .iter() + .any(|payload| matches!(payload, TransportEventPayload::ToolCall { .. })) + { + return Err(provider_failure("a required tool call did not come", usage)); + } + let stop_reason = match response["stop_reason"].as_str() { + Some("end_turn") => StopReason::EndTurn, + Some("tool_use") => StopReason::ToolUse, + Some("max_tokens") => StopReason::MaxOutputTokens, + Some("stop_sequence") => StopReason::StopSequence, + Some("refusal") => StopReason::Refusal, + Some("model_context_window_exceeded") => StopReason::ContextWindow, + _ => { + return Err(provider_failure( + "the stop reason is not one this backend maps", + usage, + )); + } + }; + Ok(Done { + id: response["id"].as_str().map(str::to_string), + payloads, + stop_reason, + usage: usage.unwrap_or_else(zero_usage), + }) +} + +fn usage_of(usage: &Value) -> Option { + usage.is_object().then(|| { + let count = |name: &str| usage[name].as_u64().unwrap_or(0); + Usage { + input_tokens: count("input_tokens"), + cache_read_tokens: count("cache_read_input_tokens"), + cache_write_tokens: count("cache_creation_input_tokens"), + output_tokens: count("output_tokens"), + reasoning_tokens: usage["output_tokens_details"]["thinking_tokens"].as_u64(), + } + }) +} + +// ---- failures ---- + +/// The fixed beginnings of the provider's 400 messages for a spent balance +/// and a reached Console spend limit, lower-cased. +const SPEND_EXHAUSTED: [&str; 2] = [ + "your credit balance is too low", + "you have reached your specified api usage limits", +]; + +fn spend_exhausted(status: u16, error: &Value) -> bool { + status == 400 + && error["type"].as_str() == Some("invalid_request_error") + && error["message"].as_str().is_some_and(|text| { + let text = text.trim_start().to_lowercase(); + SPEND_EXHAUSTED + .iter() + .any(|prefix| text.starts_with(prefix)) + }) +} + +#[cfg(test)] +use crate::http::{MESSAGE_BYTES, bounded}; + +#[cfg(test)] +fn http_failure(status: u16, body: &[u8]) -> (Vec, TransportOutcome) { + crate::http::http_failure(BACKEND_LABEL, status, body, None, spend_exhausted) +} + +#[cfg(test)] +mod tests; diff --git a/crates/claude-connector/src/messages/tests.rs b/crates/claude-connector/src/messages/tests.rs new file mode 100644 index 0000000..a4ada87 --- /dev/null +++ b/crates/claude-connector/src/messages/tests.rs @@ -0,0 +1,1252 @@ +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::sync::{Arc, Mutex}; +use std::thread; + +use model_connector::{ReasoningEffort, ToolDefinition}; +use zeroize::Zeroizing; + +use super::*; +use crate::config::{EffortMap, ForcedToolChoice}; +use crate::router::RouterBackend; + +const PROVIDER: &str = "anthropic-messages"; +const KEY: &str = "sk-ant-test-key-canary-0001"; +const MODEL: &str = "claude-sonnet-5-5"; + +fn default_row(model: &str) -> ModelRow { + ModelRow { + id: model.to_string(), + provider: PROVIDER.to_string(), + upstream: model.to_string(), + efforts: EffortMap { + low: Some("low".to_string()), + medium: Some("medium".to_string()), + high: Some("high".to_string()), + max: Some("max".to_string()), + }, + unset_effort: None, + forced_tool_choice: ForcedToolChoice::Always, + output_schema: OutputSchemaSupport::Native, + strict_tools: false, + } +} + +fn render(request: &ProviderRequest) -> Result { + super::render(request, PROVIDER, &default_row(&request.model)) +} + +trait RunDefault { + fn run(&self, request: &ProviderRequest) -> (Vec, TransportOutcome); +} + +impl RunDefault for MessagesBackend { + fn run(&self, request: &ProviderRequest) -> (Vec, TransportOutcome) { + self.run_model(request, &default_row(&request.model)) + } +} + +struct Fixed(Option<&'static str>); + +impl TokenSource for Fixed { + fn read(&self) -> Option> { + self.0.map(|key| Zeroizing::new(key.to_string())) + } +} + +/// One request a mock server saw. +struct Seen { + path: String, + headers: Vec<(String, String)>, + body: Value, +} + +impl Seen { + fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.as_str()) + } +} + +/// A server on loopback that answers each connection with the next reply +/// and records what it was sent. +fn mock(replies: Vec<(u16, String)>) -> (String, Arc>>) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let seen = Arc::new(Mutex::new(Vec::new())); + let log = seen.clone(); + thread::spawn(move || { + for (status, reply) in replies { + let Ok((mut stream, _)) = listener.accept() else { + return; + }; + let mut raw = Vec::new(); + let mut chunk = [0_u8; 4096]; + let split = loop { + let n = stream.read(&mut chunk).unwrap(); + raw.extend_from_slice(&chunk[..n]); + if let Some(at) = raw.windows(4).position(|w| w == b"\r\n\r\n") { + break at + 4; + } + assert!(n > 0, "the client closed before its headers ended"); + }; + let head = String::from_utf8(raw[..split].to_vec()).unwrap(); + let mut lines = head.split("\r\n"); + let path = lines.next().unwrap().split(' ').nth(1).unwrap().to_string(); + let headers: Vec<(String, String)> = lines + .filter_map(|line| line.split_once(": ")) + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + let length: usize = headers + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case("content-length")) + .map_or(0, |(_, v)| v.parse().unwrap()); + while raw.len() < split + length { + let n = stream.read(&mut chunk).unwrap(); + raw.extend_from_slice(&chunk[..n]); + } + log.lock().unwrap().push(Seen { + path, + headers, + body: serde_json::from_slice(&raw[split..split + length]).unwrap(), + }); + let response = format!( + "HTTP/1.1 {status} X\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}", + reply.len() + ); + stream.write_all(response.as_bytes()).unwrap(); + } + }); + (url, seen) +} + +fn backend(url: String, key: Option<&'static str>) -> MessagesBackend { + MessagesBackend::with_parts( + MessagesConfig { + provider_id: PROVIDER.to_string(), + base_url: url, + key_credential: Some("claude-key".to_string()), + deadline: Duration::from_secs(10), + max_response_bytes: 1 << 20, + }, + Some(Box::new(Fixed(key))), + ) +} + +fn request() -> ProviderRequest { + let mut request = ProviderRequest::new("req-1", "conv-1", MODEL, "Be brief.", 1024); + request.input = vec![InputItem::UserText { + text: "hello".to_string(), + }]; + request +} + +fn weather_tool() -> ToolDefinition { + ToolDefinition { + name: "get_weather".to_string(), + description: "Weather for a city.".to_string(), + parameters_json: + r#"{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}"# + .to_string(), + } +} + +fn answer(content: Value, stop_reason: &str, usage: Value) -> String { + json!({ + "id": "msg_01ABC", + "type": "message", + "role": "assistant", + "model": MODEL, + "content": content, + "stop_reason": stop_reason, + "usage": usage, + }) + .to_string() +} + +fn plain_usage() -> Value { + json!({"input_tokens": 12, "output_tokens": 7}) +} + +fn completed(outcome: &TransportOutcome) -> (&StopReason, &Usage) { + match outcome { + TransportOutcome::Completed { + stop_reason, usage, .. + } => (stop_reason, usage), + other => panic!("expected a completed call, got {other:?}"), + } +} + +fn failure_of(outcome: &TransportOutcome) -> (FailureKind, &str, &Option) { + match outcome { + TransportOutcome::Failed { + kind, + message, + usage, + } => (*kind, message.as_str(), usage), + other => panic!("expected a failed call, got {other:?}"), + } +} + +#[test] +fn t_c0_tool_use_maps_to_tool_call() { + let reply = answer( + json!([ + {"type": "text", "text": "Checking."}, + {"type": "tool_use", "id": "toolu_01X", "name": "get_weather", "input": {"city": "Oslo"}} + ]), + "tool_use", + plain_usage(), + ); + let (url, seen) = mock(vec![(200, reply)]); + let mut asked = request(); + asked.tools = vec![weather_tool()]; + let (events, outcome) = backend(url, Some(KEY)).run(&asked); + + assert_eq!(events.len(), 2); + assert_eq!( + events[0].payload, + TransportEventPayload::TextDelta { + text: "Checking.".to_string() + } + ); + let TransportEventPayload::ToolCall { + call_id, + name, + arguments, + } = &events[1].payload + else { + panic!("not a tool call: {:?}", events[1]); + }; + assert_eq!( + (call_id.as_str(), name.as_str()), + ("toolu_01X", "get_weather") + ); + assert_eq!( + serde_json::from_str::(arguments).unwrap(), + json!({"city": "Oslo"}) + ); + assert_eq!(completed(&outcome).0, &StopReason::ToolUse); + assert!(matches!( + &outcome, + TransportOutcome::Completed { provider_response_id: Some(id), .. } if id == "msg_01ABC" + )); + + let seen = seen.lock().unwrap(); + assert_eq!(seen[0].path, "/v1/messages"); + assert_eq!(seen[0].header("x-api-key"), Some(KEY)); + assert_eq!(seen[0].header("anthropic-version"), Some(API_VERSION)); + let body = &seen[0].body; + assert_eq!(body["model"], MODEL); + assert_eq!(body["max_tokens"], 1024); + assert_eq!( + body["system"], + json!([{"type": "text", "text": "Be brief."}]) + ); + assert_eq!(body["tools"][0]["name"], "get_weather"); + assert_eq!( + body["tools"][0]["input_schema"]["required"], + json!(["city"]) + ); + assert_eq!( + body["tool_choice"], + json!({"type": "auto", "disable_parallel_tool_use": true}) + ); + assert!(body.get("stream").is_none()); +} + +#[test] +fn t_c0_tool_result_round_trip() { + let mut asked = request(); + asked.input = vec![ + InputItem::UserText { + text: "weather in Oslo and Rome?".to_string(), + }, + InputItem::AssistantText { + text: "Checking both.".to_string(), + }, + InputItem::ToolCall { + call_id: "toolu_01X".to_string(), + name: "get_weather".to_string(), + arguments: r#"{"city":"Oslo"}"#.to_string(), + }, + InputItem::ToolCall { + call_id: "toolu_01Y".to_string(), + name: "get_weather".to_string(), + arguments: r#"{"city":"Rome"}"#.to_string(), + }, + InputItem::ToolResult { + call_id: "toolu_01X".to_string(), + output: "cold".to_string(), + }, + InputItem::ToolResult { + call_id: "toolu_01Y".to_string(), + output: "warm".to_string(), + }, + ]; + asked.tools = vec![weather_tool()]; + asked.parallel_tool_calls = true; + let body = render(&asked).unwrap(); + + assert_eq!( + body["messages"], + json!([ + {"role": "user", "content": [{"type": "text", "text": "weather in Oslo and Rome?"}]}, + {"role": "assistant", "content": [ + {"type": "text", "text": "Checking both."}, + {"type": "tool_use", "id": "toolu_01X", "name": "get_weather", "input": {"city": "Oslo"}}, + {"type": "tool_use", "id": "toolu_01Y", "name": "get_weather", "input": {"city": "Rome"}} + ]}, + {"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": "toolu_01X", "content": "cold"}, + {"type": "tool_result", "tool_use_id": "toolu_01Y", "content": "warm"} + ]} + ]) + ); + assert!( + body.get("tool_choice").is_none(), + "parallel calls are the default" + ); + + // Text after a tool result stays in the same user message, after the results. + asked.input.push(InputItem::UserText { + text: "and be brief".to_string(), + }); + let body = render(&asked).unwrap(); + let last = &body["messages"][2]["content"]; + assert_eq!(last[2], json!({"type": "text", "text": "and be brief"})); +} + +#[test] +fn a_tool_call_whose_arguments_are_not_an_object_is_refused_before_sending() { + let mut asked = request(); + asked.input.push(InputItem::ToolCall { + call_id: "toolu_01X".to_string(), + name: "get_weather".to_string(), + arguments: "[1]".to_string(), + }); + assert!(render(&asked).is_err()); +} + +#[test] +fn t_c0_thinking_replayed_verbatim() { + let thinking = json!({ + "type": "thinking", + "thinking": "The user wants the weather; call the tool. \u{1F326}", + "signature": "EqQBCkYIBxgCKkA+/abc123==" + }); + let redacted = json!({"type": "redacted_thinking", "data": "EmwKAhgBEgy3va3pzix/LafPsn4="}); + let reply = answer( + json!([ + thinking, + redacted, + {"type": "tool_use", "id": "toolu_01X", "name": "get_weather", "input": {"city": "Oslo"}} + ]), + "tool_use", + plain_usage(), + ); + let (url, _) = mock(vec![(200, reply)]); + let mut asked = request(); + asked.tools = vec![weather_tool()]; + let (events, _) = backend(url, Some(KEY)).run(&asked); + + let states: Vec<&Vec> = events + .iter() + .filter_map(|event| match &event.payload { + TransportEventPayload::ReasoningState { state } => Some(state), + _ => None, + }) + .collect(); + assert_eq!(states.len(), 2); + assert_eq!(states[0], &serde_json::to_vec(&thinking).unwrap()); + + // The next request: the connector's own result items, as the contract replays them. + let mut next = request(); + next.input + .extend(events.iter().map(|event| match &event.payload { + TransportEventPayload::ReasoningState { state } => InputItem::ReasoningState { + provider: PROVIDER.to_string(), + model: MODEL.to_string(), + state: state.clone(), + }, + TransportEventPayload::ToolCall { + call_id, + name, + arguments, + } => InputItem::ToolCall { + call_id: call_id.clone(), + name: name.clone(), + arguments: arguments.clone(), + }, + TransportEventPayload::TextDelta { text } => { + InputItem::AssistantText { text: text.clone() } + } + })); + next.input.push(InputItem::ToolResult { + call_id: "toolu_01X".to_string(), + output: "cold".to_string(), + }); + next.tools = vec![weather_tool()]; + let body = render(&next).unwrap(); + let assistant = &body["messages"][1]["content"]; + assert_eq!( + assistant[0], thinking, + "the block comes back unchanged and first" + ); + assert_eq!(assistant[1], redacted); + assert_eq!(assistant[2]["type"], "tool_use"); +} + +#[test] +fn a_reasoning_state_that_is_not_this_providers_thinking_block_is_refused() { + let state = |provider: &str, bytes: &[u8]| InputItem::ReasoningState { + provider: provider.to_string(), + model: MODEL.to_string(), + state: bytes.to_vec(), + }; + for item in [ + state( + "claude-code", + br#"{"type":"thinking","thinking":"x","signature":"s"}"#, + ), + state(PROVIDER, b"not json"), + state(PROVIDER, br#"{"type":"text","text":"x"}"#), + ] { + let mut asked = request(); + asked.input.push(item); + assert!(render(&asked).is_err()); + } +} + +#[test] +fn effort_is_adaptive_thinking_with_an_effort_and_never_a_budget() { + let mut asked = request(); + let plain = render(&asked).unwrap(); + assert!(plain.get("thinking").is_none() && plain.get("output_config").is_none()); + + asked.reasoning_effort = Some(ReasoningEffort::Medium); + let body = render(&asked).unwrap(); + assert_eq!(body["thinking"], json!({"type": "adaptive"})); + assert_eq!(body["output_config"], json!({"effort": "medium"})); + assert!(!body.to_string().contains("budget_tokens")); +} + +#[test] +fn t_c0_cache_control_long() { + let mut asked = request(); + asked.input = vec![ + InputItem::UserText { + text: "first".to_string(), + }, + InputItem::AssistantText { + text: "second".to_string(), + }, + InputItem::UserText { + text: "third".to_string(), + }, + InputItem::UserText { + text: "fourth".to_string(), + }, + ]; + let count = |body: &Value| body.to_string().matches("cache_control").count(); + + assert_eq!(count(&render(&asked).unwrap()), 0); + + asked.cache_retention = Some(CacheRetention::Long); + let body = render(&asked).unwrap(); + assert_eq!(count(&body), 2, "the system prompt and the last message"); + assert_eq!( + body["system"][0]["cache_control"], + json!({"type": "ephemeral", "ttl": "1h"}) + ); + let blocks = &body["messages"][2]["content"]; + assert!(blocks[0].get("cache_control").is_none()); + assert_eq!( + blocks[1]["cache_control"], + json!({"type": "ephemeral", "ttl": "1h"}) + ); + + asked.cache_retention = Some(CacheRetention::Short); + let body = render(&asked).unwrap(); + assert_eq!(count(&body), 2); + assert_eq!( + body["system"][0]["cache_control"], + json!({"type": "ephemeral"}) + ); + assert_eq!( + body["messages"][2]["content"][1]["cache_control"], + json!({"type": "ephemeral"}) + ); +} + +#[test] +fn caching_marks_the_last_tool_and_the_system_prompt_so_the_prefix_outlives_the_turn() { + let mut asked = request(); + asked.tools = vec![ + ToolDefinition { + name: "first".to_string(), + description: "one".to_string(), + parameters_json: r#"{"type":"object"}"#.to_string(), + }, + ToolDefinition { + name: "second".to_string(), + description: "two".to_string(), + parameters_json: r#"{"type":"object"}"#.to_string(), + }, + ]; + let count = |body: &Value| body.to_string().matches("cache_control").count(); + assert_eq!( + count(&render(&asked).unwrap()), + 0, + "no retention, no breakpoint" + ); + + asked.cache_retention = Some(CacheRetention::Long); + let body = render(&asked).unwrap(); + let mark = json!({"type": "ephemeral", "ttl": "1h"}); + assert_eq!(count(&body), 3, "at most the API's four: {body}"); + assert!(body["tools"][0].get("cache_control").is_none()); + assert_eq!(body["tools"][1]["cache_control"], mark); + assert_eq!(body["system"][0]["cache_control"], mark); +} + +#[test] +fn a_breakpoint_skips_a_trailing_thinking_block() { + let mut asked = request(); + asked.cache_retention = Some(CacheRetention::Short); + asked.input.push(InputItem::AssistantText { + text: "answer".to_string(), + }); + asked.input.push(InputItem::ReasoningState { + provider: PROVIDER.to_string(), + model: MODEL.to_string(), + state: br#"{"type":"thinking","thinking":"","signature":"s"}"#.to_vec(), + }); + let body = render(&asked).unwrap(); + let blocks = &body["messages"][1]["content"]; + assert_eq!(blocks[0]["cache_control"], json!({"type": "ephemeral"})); + assert!(blocks[1].get("cache_control").is_none()); +} + +#[test] +fn t_c0_usage_cache_fields() { + let reply = answer( + json!([{"type": "text", "text": "hi"}]), + "end_turn", + json!({ + "input_tokens": 5, + "cache_read_input_tokens": 2000, + "cache_creation_input_tokens": 300, + "output_tokens": 9 + }), + ); + let (url, _) = mock(vec![(200, reply)]); + let (_, outcome) = backend(url, Some(KEY)).run(&request()); + let (stop, usage) = completed(&outcome); + assert_eq!(*stop, StopReason::EndTurn); + assert_eq!( + usage, + &Usage { + input_tokens: 5, + cache_read_tokens: 2000, + cache_write_tokens: 300, + output_tokens: 9, + reasoning_tokens: None, + } + ); +} + +#[test] +fn every_stop_reason_the_api_names_maps() { + for (name, expected) in [ + ("end_turn", StopReason::EndTurn), + ("tool_use", StopReason::ToolUse), + ("max_tokens", StopReason::MaxOutputTokens), + ("stop_sequence", StopReason::StopSequence), + ("refusal", StopReason::Refusal), + ("model_context_window_exceeded", StopReason::ContextWindow), + ] { + let reply = answer(json!([]), name, plain_usage()); + let done = + parse(reply.as_bytes(), false).unwrap_or_else(|_| panic!("{name} did not parse")); + assert_eq!(done.stop_reason, expected); + } + let unknown = parse( + answer(json!([]), "pause_turn", plain_usage()).as_bytes(), + false, + ); + let failure = unknown.err().unwrap(); + assert_eq!(failure.kind, FailureKind::Provider); + assert_eq!(failure.usage.unwrap().output_tokens, 7); +} + +#[test] +fn t_c0_schema_by_forced_tool() { + let schema = r#"{"type":"object","properties":{"ok":{"type":"boolean"}},"required":["ok"],"additionalProperties":false}"#; + let reply = answer( + json!([{"type": "text", "text": "{\"ok\":true}"}]), + "end_turn", + plain_usage(), + ); + let (url, seen) = mock(vec![(200, reply)]); + let mut asked = request(); + asked.output_schema_json = Some(schema.to_string()); + asked.reasoning_effort = Some(ReasoningEffort::Low); + let (events, outcome) = backend(url, Some(KEY)).run(&asked); + + assert_eq!(events.len(), 1); + assert_eq!( + events[0].payload, + TransportEventPayload::TextDelta { + text: "{\"ok\":true}".to_string() + } + ); + assert_eq!(completed(&outcome).0, &StopReason::EndTurn); + let seen = seen.lock().unwrap(); + let body = &seen[0].body; + // The models this connector serves reject a forced tool, so the schema is + // the response format and no tool is named, forced or otherwise. + assert_eq!( + body["output_config"], + json!({ + "effort": "low", + "format": {"type": "json_schema", "schema": serde_json::from_str::(schema).unwrap()} + }) + ); + assert!(body.get("tools").is_none() && body.get("tool_choice").is_none()); +} + +#[test] +fn model_row_policies_gate_forced_tool_choice_output_schema_and_efforts() { + // 1. ForcedToolChoice::Always accepts Required even when thinking is active. + let mut always_row = default_row(MODEL); + always_row.forced_tool_choice = ForcedToolChoice::Always; + let mut asked = request(); + asked.tools = vec![weather_tool()]; + asked.tool_choice = ToolChoice::Required; + asked.reasoning_effort = Some(ReasoningEffort::Low); + asked.parallel_tool_calls = true; + let auto = { + let mut a = asked.clone(); + a.tool_choice = ToolChoice::Auto; + super::render(&a, PROVIDER, &always_row).unwrap() + }; + let body = super::render(&asked, PROVIDER, &always_row).unwrap(); + assert_eq!(body["tool_choice"], json!({"type": "any"})); + assert_eq!(body["system"], auto["system"]); + asked.parallel_tool_calls = false; + assert_eq!( + super::render(&asked, PROVIDER, &always_row).unwrap()["tool_choice"], + json!({"type": "any", "disable_parallel_tool_use": true}) + ); + + // 2. ForcedToolChoice::Never refuses Required before sending. + let mut never_row = default_row(MODEL); + never_row.forced_tool_choice = ForcedToolChoice::Never; + let (url, seen) = mock(vec![(200, answer(json!([]), "end_turn", plain_usage()))]); + let mut asked = request(); + asked.tools = vec![weather_tool()]; + asked.tool_choice = ToolChoice::Required; + let (events, outcome) = backend(url, Some(KEY)).run_model(&asked, &never_row); + assert!(events.is_empty()); + assert_eq!(failure_of(&outcome).0, FailureKind::InvalidRequest); + assert!(seen.lock().unwrap().is_empty()); + + // 3. ForcedToolChoice::WithoutThinking refuses Required iff resolved effort is Some. + let mut without_thinking = default_row(MODEL); + without_thinking.forced_tool_choice = ForcedToolChoice::WithoutThinking; + without_thinking.unset_effort = Some("default-think".to_string()); + + // Active via explicit reasoning_effort -> refused before sending. + let (url, seen) = mock(vec![]); + let mut asked = request(); + asked.tools = vec![weather_tool()]; + asked.tool_choice = ToolChoice::Required; + asked.reasoning_effort = Some(ReasoningEffort::Low); + let (_, outcome) = backend(url, Some(KEY)).run_model(&asked, &without_thinking); + assert_eq!(failure_of(&outcome).0, FailureKind::InvalidRequest); + assert!(seen.lock().unwrap().is_empty()); + + // Active via unset_effort -> refused before sending. + let (url, seen) = mock(vec![]); + asked.reasoning_effort = None; + let (_, outcome) = backend(url, Some(KEY)).run_model(&asked, &without_thinking); + assert_eq!(failure_of(&outcome).0, FailureKind::InvalidRequest); + assert!(seen.lock().unwrap().is_empty()); + + // Thinking inactive (unset_effort is None and request effort is None) -> accepted. + without_thinking.unset_effort = None; + asked.parallel_tool_calls = true; + let body = super::render(&asked, PROVIDER, &without_thinking).unwrap(); + assert_eq!(body["tool_choice"], json!({"type": "any"})); + + // 4. OutputSchemaSupport::None refuses output_schema_json before sending. + let mut no_schema_row = default_row(MODEL); + no_schema_row.output_schema = OutputSchemaSupport::None; + let (url, seen) = mock(vec![]); + let mut asked = request(); + asked.output_schema_json = Some(r#"{"type":"object"}"#.to_string()); + let (events, outcome) = backend(url, Some(KEY)).run_model(&asked, &no_schema_row); + assert!(events.is_empty()); + assert_eq!(failure_of(&outcome).0, FailureKind::InvalidRequest); + assert!(seen.lock().unwrap().is_empty()); + + // 5. EffortMap maps efforts to custom wire values, refuses unmapped, and uses unset_effort. + let mut effort_row = default_row(MODEL); + effort_row.efforts = EffortMap { + low: Some("lo-wire".to_string()), + medium: None, + high: Some("hi-wire".to_string()), + max: None, + }; + effort_row.unset_effort = Some("default-wire".to_string()); + + let mut asked = request(); + asked.reasoning_effort = Some(ReasoningEffort::Low); + let rendered = super::render(&asked, PROVIDER, &effort_row).unwrap(); + assert_eq!(rendered["thinking"], json!({"type": "adaptive"})); + assert_eq!(rendered["output_config"]["effort"], "lo-wire"); + + // Unmapped effort refuses before sending. + let (url, seen) = mock(vec![]); + asked.reasoning_effort = Some(ReasoningEffort::Medium); + let (events, outcome) = backend(url, Some(KEY)).run_model(&asked, &effort_row); + assert!(events.is_empty()); + assert_eq!(failure_of(&outcome).0, FailureKind::InvalidRequest); + assert!(seen.lock().unwrap().is_empty()); + + // Request effort None -> applies unset_effort when Some, omits when None. + asked.reasoning_effort = None; + let with_unset = super::render(&asked, PROVIDER, &effort_row).unwrap(); + assert_eq!(with_unset["thinking"], json!({"type": "adaptive"})); + assert_eq!(with_unset["output_config"]["effort"], "default-wire"); + + effort_row.unset_effort = None; + let without_unset = super::render(&asked, PROVIDER, &effort_row).unwrap(); + assert!(without_unset.get("thinking").is_none()); + assert!(without_unset.get("output_config").is_none()); +} + +#[test] +fn a_required_turn_without_a_tool_call_fails_and_is_never_completed() { + let mut asked = request(); + asked.model = "claude-haiku-5-5".to_string(); + asked.tools = vec![weather_tool()]; + asked.tool_choice = ToolChoice::Required; + let (url, _) = mock(vec![( + 200, + answer( + json!([{"type": "text", "text": "No tool needed."}]), + "end_turn", + plain_usage(), + ), + )]); + let (events, outcome) = backend(url, Some(KEY)).run(&asked); + assert!(events.is_empty()); + let (kind, message, usage) = failure_of(&outcome); + assert_eq!(kind, FailureKind::Provider); + assert!(message.contains("required tool call did not come")); + assert_eq!(usage.as_ref().map(|u| u.output_tokens), Some(7)); + + // With the call present it completes; an Auto turn without one completes too. + let (url, _) = mock(vec![( + 200, + answer( + json!([{"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {"city": "Oslo"}}]), + "tool_use", + plain_usage(), + ), + )]); + let (_, outcome) = backend(url, Some(KEY)).run(&asked); + assert_eq!(*completed(&outcome).0, StopReason::ToolUse); + let (url, _) = mock(vec![( + 200, + answer( + json!([{"type": "text", "text": "hi"}]), + "end_turn", + plain_usage(), + ), + )]); + asked.tool_choice = ToolChoice::Auto; + let (_, outcome) = backend(url, Some(KEY)).run(&asked); + assert_eq!(*completed(&outcome).0, StopReason::EndTurn); +} + +#[test] +fn t_c0_http_errors_typed() { + for (status, kind, body) in [ + ( + 401, + FailureKind::Authentication, + r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#, + ), + ( + 403, + FailureKind::Authentication, + r#"{"type":"error","error":{"type":"permission_error","message":"no"}}"#, + ), + ( + 429, + FailureKind::RateLimited, + r#"{"type":"error","error":{"type":"rate_limit_error","message":"slow down"}}"#, + ), + ( + 529, + FailureKind::Unavailable, + r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#, + ), + ( + 503, + FailureKind::Unavailable, + r#"{"type":"error","error":{"type":"api_error","message":"down"}}"#, + ), + ( + 400, + FailureKind::InvalidRequest, + r#"{"type":"error","error":{"type":"invalid_request_error","message":"max_tokens must be positive"}}"#, + ), + ( + 402, + FailureKind::Authentication, + r#"{"type":"error","error":{"type":"billing_error","message":"credit exhausted"}}"#, + ), + ( + 500, + FailureKind::Unavailable, + r#"{"type":"error","error":{"type":"api_error","message":"internal"}}"#, + ), + (502, FailureKind::Unavailable, "bad gateway"), + ( + 504, + FailureKind::Timeout, + r#"{"type":"error","error":{"type":"timeout_error","message":"slow"}}"#, + ), + ( + 404, + FailureKind::Provider, + r#"{"type":"error","error":{"type":"not_found_error","message":"no model"}}"#, + ), + ] { + let (url, _) = mock(vec![(status, body.to_string())]); + let (events, outcome) = backend(url, Some(KEY)).run(&request()); + assert!(events.is_empty()); + let (got, message, usage) = failure_of(&outcome); + assert_eq!(got, kind, "status {status}"); + assert!(message.starts_with(&format!("anthropic-messages: HTTP {status}"))); + assert!(usage.is_none()); + assert!(!message.contains(KEY)); + } + // The provider's own words survive, so a drained balance reads as one. + let (url, _) = mock(vec![( + 400, + r#"{"type":"error","error":{"type":"invalid_request_error","message":"Your credit balance is too low"}}"# + .to_string(), + )]); + let (_, outcome) = backend(url, Some(KEY)).run(&request()); + assert!(failure_of(&outcome).1.contains("credit balance is too low")); +} + +#[test] +fn a_spent_balance_or_a_reached_spend_limit_is_not_a_strike() { + let body = |kind: &str, message: &str| { + json!({"type": "error", "error": {"type": kind, "message": message}}).to_string() + }; + for (kind, message, expected) in [ + ( + "invalid_request_error", + "Your credit balance is too low", + FailureKind::Authentication, + ), + ( + "invalid_request_error", + "Your credit balance is too low to access the Anthropic API. Please go to Plans & Billing.", + FailureKind::Authentication, + ), + ( + "invalid_request_error", + "You have reached your specified API usage limits", + FailureKind::Authentication, + ), + ( + "invalid_request_error", + "You have reached your specified API usage limits. You will regain access on 2026-12-01 at 00:00 UTC.", + FailureKind::Authentication, + ), + ( + "invalid_request_error", + "YOU HAVE REACHED YOUR SPECIFIED API USAGE LIMITS. Later.", + FailureKind::Authentication, + ), + ( + "invalid_request_error", + "prompt is too long: 300000 tokens", + FailureKind::InvalidRequest, + ), + ( + "invalid_request_error", + "Note: your credit balance is too low is not how this starts", + FailureKind::InvalidRequest, + ), + ( + "api_error", + "Your credit balance is too low", + FailureKind::Unavailable, + ), + ] { + let status = if kind == "api_error" { 500 } else { 400 }; + let (url, _) = mock(vec![(status, body(kind, message))]); + let (_, outcome) = backend(url, Some(KEY)).run(&request()); + assert_eq!(failure_of(&outcome).0, expected, "{message}"); + } + // The same words on another status keep that status's kind. + let (_, outcome) = http_failure( + 404, + body("invalid_request_error", "Your credit balance is too low").as_bytes(), + ); + assert_eq!(failure_of(&outcome).0, FailureKind::Provider); +} + +#[test] +fn a_dead_endpoint_and_a_slow_one_are_typed() { + let dead = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", dead.local_addr().unwrap()); + drop(dead); + let (_, outcome) = backend(url, Some(KEY)).run(&request()); + assert_eq!(failure_of(&outcome).0, FailureKind::Unavailable); + + let silent = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", silent.local_addr().unwrap()); + let slow = MessagesBackend::with_parts( + MessagesConfig { + provider_id: PROVIDER.to_string(), + base_url: url, + key_credential: Some("claude-key".to_string()), + deadline: Duration::from_millis(200), + max_response_bytes: 1 << 20, + }, + Some(Box::new(Fixed(Some(KEY)))), + ); + let (_, outcome) = slow.run(&request()); + assert_eq!(failure_of(&outcome).0, FailureKind::Timeout); + drop(silent); +} + +#[test] +fn an_endpoint_that_is_no_uri_is_a_provider_failure_not_an_outage() { + let (events, outcome) = backend("not a uri".to_string(), Some(KEY)).run(&request()); + assert!(events.is_empty()); + let (kind, message, _) = failure_of(&outcome); + assert_eq!(kind, FailureKind::Provider); + assert_eq!( + message, + "anthropic-messages: the request could not be built" + ); +} + +#[test] +fn a_response_over_its_cap_is_a_provider_failure() { + let reply = answer( + json!([{"type": "text", "text": "x".repeat(4096)}]), + "end_turn", + plain_usage(), + ); + let (url, _) = mock(vec![(200, reply)]); + let small = MessagesBackend::with_parts( + MessagesConfig { + provider_id: PROVIDER.to_string(), + base_url: url, + key_credential: Some("claude-key".to_string()), + deadline: Duration::from_secs(10), + max_response_bytes: 1024, + }, + Some(Box::new(Fixed(Some(KEY)))), + ); + let (_, outcome) = small.run(&request()); + let (kind, message, _) = failure_of(&outcome); + assert_eq!(kind, FailureKind::Provider); + assert_eq!( + message, + "anthropic-messages: the response passed its size cap" + ); +} + +#[test] +fn a_receipt_message_is_bounded_on_a_char_boundary() { + let at_cap = "a".repeat(MESSAGE_BYTES); + assert_eq!(bounded(at_cap.clone()), at_cap); + assert_eq!(bounded("a".repeat(MESSAGE_BYTES + 1)), at_cap); + assert_eq!(bounded("short".to_string()), "short"); + // A three-byte char straddling the cap is dropped whole, one byte in or two. + for lead in [MESSAGE_BYTES - 1, MESSAGE_BYTES - 2] { + let text = format!("{}{}", "a".repeat(lead), "\u{20ac}\u{20ac}"); + let cut = bounded(text); + assert_eq!(cut, "a".repeat(lead)); + } + // A char that ends exactly on the cap is kept. + let text = format!("{}\u{20ac}tail", "a".repeat(MESSAGE_BYTES - 3)); + assert_eq!( + bounded(text), + format!("{}\u{20ac}", "a".repeat(MESSAGE_BYTES - 3)) + ); + // A provider's long message reaches the receipt bounded. + let long = + json!({"type": "error", "error": {"type": "api_error", "message": "x".repeat(5000)}}); + let (_, outcome) = http_failure(500, long.to_string().as_bytes()); + assert_eq!(failure_of(&outcome).1.len(), MESSAGE_BYTES); +} + +#[test] +fn a_redirect_is_a_failure_and_the_key_goes_nowhere_else() { + let target = TcpListener::bind("127.0.0.1:0").unwrap(); + let elsewhere = format!("http://{}/stolen", target.local_addr().unwrap()); + target.set_nonblocking(true).unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url2 = format!("http://{}", listener.local_addr().unwrap()); + let hits = Arc::new(Mutex::new(0_u32)); + let counted = hits.clone(); + let location = elsewhere.clone(); + thread::spawn(move || { + for _ in 0..2 { + let Ok((mut stream, _)) = listener.accept() else { + return; + }; + *counted.lock().unwrap() += 1; + let mut chunk = [0_u8; 8192]; + let _ = stream.read(&mut chunk); + let _ = stream.write_all( + format!( + "HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) + .as_bytes(), + ); + } + }); + let (events, outcome) = backend(url2, Some(KEY)).run(&request()); + assert!(events.is_empty()); + let (kind, message, _) = failure_of(&outcome); + assert_eq!(kind, FailureKind::Unavailable); + assert!(message.starts_with("anthropic-messages: HTTP 302")); + assert_eq!(*hits.lock().unwrap(), 1); + assert!( + target.accept().is_err(), + "the redirect target was contacted" + ); +} + +#[test] +fn thinking_tokens_are_reasoning_tokens() { + let reply = answer( + json!([{"type": "text", "text": "hi"}]), + "end_turn", + json!({ + "input_tokens": 5, + "output_tokens": 90, + "output_tokens_details": {"thinking_tokens": 64} + }), + ); + let (url, _) = mock(vec![(200, reply)]); + let (_, outcome) = backend(url, Some(KEY)).run(&request()); + let (_, usage) = completed(&outcome); + assert_eq!(usage.output_tokens, 90); + assert_eq!(usage.reasoning_tokens, Some(64)); +} + +#[test] +fn tool_results_come_first_in_their_user_message() { + let mut asked = request(); + asked.input = vec![ + InputItem::UserText { + text: "go".to_string(), + }, + InputItem::ToolCall { + call_id: "toolu_01X".to_string(), + name: "get_weather".to_string(), + arguments: r#"{"city":"Oslo"}"#.to_string(), + }, + InputItem::UserText { + text: "first, text".to_string(), + }, + InputItem::ToolResult { + call_id: "toolu_01X".to_string(), + output: "cold".to_string(), + }, + InputItem::UserText { + text: "then, more text".to_string(), + }, + ]; + asked.tools = vec![weather_tool()]; + let body = render(&asked).unwrap(); + let last = body["messages"][2]["content"].as_array().unwrap(); + let types: Vec<&str> = last.iter().map(|b| b["type"].as_str().unwrap()).collect(); + assert_eq!(types, ["tool_result", "text", "text"]); + assert_eq!(last[1]["text"], "first, text"); + assert_eq!(last[2]["text"], "then, more text"); + // An assistant message is never reordered. + let mut asked = request(); + asked.input = vec![ + InputItem::AssistantText { + text: "a".to_string(), + }, + InputItem::ToolCall { + call_id: "toolu_01X".to_string(), + name: "get_weather".to_string(), + arguments: "{}".to_string(), + }, + InputItem::AssistantText { + text: "b".to_string(), + }, + ]; + let body = render(&asked).unwrap(); + let types: Vec<&str> = body["messages"][0]["content"] + .as_array() + .unwrap() + .iter() + .map(|b| b["type"].as_str().unwrap()) + .collect(); + assert_eq!(types, ["text", "tool_use", "text"]); +} + +#[test] +fn no_key_means_no_request_and_no_readiness() { + let (url, seen) = mock(vec![(200, answer(json!([]), "end_turn", plain_usage()))]); + let missing_key = backend(url, None); + assert_eq!(missing_key.ready(), Err("token_credential")); + let (events, outcome) = missing_key.run(&request()); + assert!(events.is_empty()); + let (kind, _, usage) = failure_of(&outcome); + assert_eq!(kind, FailureKind::Authentication); + assert!(usage.is_some()); + assert!(seen.lock().unwrap().is_empty()); + assert_eq!(backend("http://x".to_string(), Some(KEY)).ready(), Ok(())); + + // Keyless loopback (`keys: None`) is ready and sends no `x-api-key` header. + let (url, seen) = mock(vec![( + 200, + answer( + json!([{"type": "text", "text": "local ok"}]), + "end_turn", + plain_usage(), + ), + )]); + let keyless = MessagesBackend::with_parts( + MessagesConfig { + provider_id: PROVIDER.to_string(), + base_url: url, + key_credential: None, + deadline: Duration::from_secs(10), + max_response_bytes: 1 << 20, + }, + None, + ); + assert_eq!(keyless.ready(), Ok(())); + let (_, outcome) = keyless.run(&request()); + assert_eq!(*completed(&outcome).0, StopReason::EndTurn); + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].header("x-api-key"), None); +} + +#[test] +fn the_key_is_in_the_header_only() { + let (url, seen) = mock(vec![( + 200, + answer( + json!([{"type": "text", "text": "hi"}]), + "end_turn", + plain_usage(), + ), + )]); + let backend = backend(url, Some(KEY)); + let (events, outcome) = backend.run(&request()); + let seen = seen.lock().unwrap(); + assert_eq!(seen[0].header("x-api-key"), Some(KEY)); + assert!(!seen[0].body.to_string().contains(KEY)); + assert!(!format!("{events:?} {outcome:?}").contains(KEY)); +} + +#[test] +fn a_call_through_the_serve_loop_reaches_the_caller_as_a_valid_result() { + use model_connector::{ + CallerAdmission, ConnectorClient, ProviderRoutes, ServeLimits, TransportDisposition, + TransportInvocation, frame_bytes_for_payload, provider_request_sha256, serve, + }; + + const FRAME: usize = 2 << 20; + const CALLER: &str = "persona-a"; + const CALLER_KEY: &str = "0123456789abcdef0123456789abcdef0123456789abcdef"; + + let reply = answer( + json!([ + {"type": "thinking", "thinking": "", "signature": "sig=="}, + {"type": "tool_use", "id": "toolu_01X", "name": "get_weather", "input": {"city": "Oslo"}} + ]), + "tool_use", + json!({"input_tokens": 3, "cache_read_input_tokens": 10, "output_tokens": 4}), + ); + let (url, _) = mock(vec![(200, reply)]); + let router = Arc::new( + RouterBackend::from_backends( + [backend(url, Some(KEY))], + [], + None, + vec![default_row(MODEL)], + ) + .unwrap(), + ); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let endpoint = listener.local_addr().unwrap(); + let admission = CallerAdmission::new( + CALLER, + CALLER_KEY, + 1, + [MODEL.to_string()], + 4, + 1 << 20, + 4_096, + ) + .unwrap(); + let limits = ServeLimits { + max_frame_bytes: FRAME.max(frame_bytes_for_payload(1 << 20)), + max_connections: 8, + socket_timeout_ms: 5_000, + max_expiry_skew_ms: 300_000, + }; + let store = std::env::temp_dir().join(format!("messages-serve-{}.cc", std::process::id())); + let _ = std::fs::remove_file(&store); + let frame = limits.max_frame_bytes; + let routes = ProviderRoutes::new([(MODEL.to_string(), PROVIDER.to_string())]).unwrap(); + thread::spawn(move || serve(listener, limits, vec![admission], &store, routes, router)); + + let mut asked = request(); + asked.tools = vec![weather_tool()]; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as u64; + let invocation = TransportInvocation::new( + CALLER, + now + 60_000, + provider_request_sha256(&asked).unwrap(), + asked, + ) + .unwrap(); + let client = + ConnectorClient::new(endpoint, CALLER_KEY, frame, Some(Duration::from_secs(5))).unwrap(); + let result = client.execute(&invocation).unwrap(); + result.validate_against(&invocation).unwrap(); + let TransportDisposition::Transported { receipt, .. } = &result.disposition else { + panic!("not transported: {:?}", result.disposition); + }; + assert_eq!(receipt.provider, PROVIDER); + let (stop, usage) = completed(&receipt.outcome); + assert_eq!(*stop, StopReason::ToolUse); + assert_eq!(usage.cache_read_tokens, 10); + // The transcript the caller appends is exactly what replays. + let items = result.transcript_items(); + assert!( + matches!(&items[0], InputItem::ReasoningState { provider, .. } if provider == PROVIDER) + ); + assert!(matches!(&items[1], InputItem::ToolCall { call_id, .. } if call_id == "toolu_01X")); +} diff --git a/crates/claude-connector/src/meter.rs b/crates/claude-connector/src/meter.rs index 2f572a2..1357abf 100644 --- a/crates/claude-connector/src/meter.rs +++ b/crates/claude-connector/src/meter.rs @@ -1,24 +1,23 @@ -//! The meter: keeps the plan's weekly reading fresh while the swarm is +//! The meter: keeps the plan's weekly reading fresh while lease holders are //! working. The subscription reports its windows only inside the CLI's -//! `rate_limit_event`, on a call the CLI makes, and Personas make theirs under -//! leases that report nothing back. So when the `seven_day` reading in the -//! [`QuotaCell`] is `STALE` old, the meter makes the smallest real call +//! `rate_limit_event`, on a call the CLI makes, and lease holders make theirs +//! under leases that report nothing back. So when the `seven_day` reading in +//! the [`QuotaCell`] is `STALE` old, the meter makes the smallest real call //! through the backend's own path (one `claude -p` on the cheapest model with //! a trivial prompt) and the stream fills the cell exactly as it does for any //! call. The meter holds no credential, speaks no protocol and writes nothing //! itself. //! //! The meter is driven by the connector's own lease state. It reads only -//! while a lease is held or one was asked for less than `STALE` ago: a held -//! swarm brake stops the units, they ask for nothing, and a braked or quiet -//! swarm spends nothing. A call that fails, or completes without refreshing -//! the reading, is not retried at the staleness period: the wait doubles per -//! consecutive miss, up to `CEILING`. +//! while a lease is held or one was asked for less than `STALE` ago: an idle +//! deployment asks for nothing, and idle lease holders spend nothing. A call +//! that fails, or completes without refreshing the reading, is not retried at +//! the staleness period: the wait doubles per consecutive miss, up to `CEILING`. use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use model_connector::Usage; +use model_connector::{PlanQuota, Usage}; use crate::backend::ClaudeCodeBackend; use crate::quota::{EXPIRED, QuotaCell, WEEK}; @@ -42,10 +41,16 @@ impl Probe for Arc { } } -/// Why the meter is waiting; logged once per change. +/// Why the meter is waiting. A refresh is logged every time, with the reading +/// it saw; the other states are logged once per change. #[derive(Debug, Clone, PartialEq, Eq)] enum State { - Read, + /// The week window as the refresh left it; a window with no reading is + /// `None`. + Read { + permille: Option, + resets_at_unix_ms: u64, + }, Idle, /// The call failed; the kind is the failure's kind, never its message. Failed(String), @@ -55,7 +60,15 @@ enum State { impl State { fn line(&self) -> String { match self { - Self::Read => "meter: weekly reading refreshed".to_string(), + Self::Read { + permille, + resets_at_unix_ms, + } => { + let permille = permille.map_or("unknown".to_string(), |p| p.to_string()); + format!( + "meter: weekly reading refreshed, permille {permille} resets_at_unix_ms {resets_at_unix_ms}" + ) + } Self::Idle => "meter: no lease asked lately, making no call".to_string(), Self::Failed(kind) => format!("meter: the call failed ({kind}), backing off"), Self::Unread => { @@ -105,9 +118,12 @@ impl Meter { // reports its windows and then errors. Only the cell says whether the // week was read. let called = self.probe.call(); - let state = if self.refreshed_since(now_ms) { + let state = if let Some(week) = self.week_refreshed_since(now_ms) { self.misses = 0; - State::Read + State::Read { + permille: week.utilization_permille, + resets_at_unix_ms: week.resets_at_unix_ms, + } } else { self.misses = self.misses.saturating_add(1); match called { @@ -139,16 +155,18 @@ impl Meter { stale_at.max(self.not_before_ms) } - fn refreshed_since(&self, since_ms: u64) -> bool { + /// The week window if it was observed at or after `since_ms`, from one + /// snapshot, so the logged value is the one that decided the refresh. + fn week_refreshed_since(&self, since_ms: u64) -> Option { self.cell .snapshot() .windows - .iter() - .any(|quota| quota.window == WEEK && quota.observed_at_unix_ms >= since_ms) + .into_iter() + .find(|quota| quota.window == WEEK && quota.observed_at_unix_ms >= since_ms) } fn report(&mut self, state: State) { - if self.last_state.as_ref() != Some(&state) { + if matches!(state, State::Read { .. }) || self.last_state.as_ref() != Some(&state) { (self.log)(&state.line()); self.last_state = Some(state); } @@ -181,7 +199,8 @@ fn unix_ms() -> u64 { } /// Starts the meter thread. It writes only through the calls it makes, and -/// logs one line to stderr when its state changes. From here a lease asked of +/// logs one line to stderr per refresh of the weekly reading and one per +/// change of any other state. From here a lease asked of /// a cell with no weekly reading waits for the meter's first read. pub(crate) fn start( cell: Arc, @@ -202,7 +221,6 @@ pub(crate) fn start( mod tests { use super::*; use crate::quota::Asking; - use model_connector::PlanQuota; use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -227,6 +245,10 @@ mod tests { reading_at: Option, status: String, fails_with: Option, + /// The used thousandths the reading reports; 60 when unset. + permille: Option, + /// The reset the reading reports; `RESET` when unset. + resets_at: Option, } /// A call that answers as scripted and feeds the cell the way the stream @@ -242,7 +264,10 @@ mod tests { self.made.fetch_add(1, Ordering::SeqCst); let script = self.script.lock().unwrap().clone(); if let Some(at) = script.reading_at { - self.cell.observe_at(at, reading(&script.status)); + let mut week = reading(&script.status); + week[0].utilization_permille = Some(script.permille.unwrap_or(60)); + week[0].resets_at_unix_ms = script.resets_at.unwrap_or(RESET); + self.cell.observe_at(at, week); } if let Some(kind) = script.fails_with { return Err(kind); @@ -263,7 +288,7 @@ mod tests { made: Arc, script: Arc>, log: Arc>>, - /// The lease the swarm holds until a test lets go of it. + /// The lease held until a test lets go of it. lease: Option, } @@ -299,6 +324,7 @@ mod tests { reading_at: Some(at), status: "allowed".to_string(), fails_with: None, + ..Script::default() }; } fn reads_nothing(&self) { @@ -355,7 +381,7 @@ mod tests { } #[test] - fn a_swarm_that_asks_for_nothing_spends_nothing_however_stale_the_reading() { + fn no_lease_requests_spends_nothing_however_stale_the_reading() { let mut rig = rig(); drop(rig.lease.take()); for step in 0..10 { @@ -398,7 +424,11 @@ mod tests { rig.reads(at); rig.meter.tick(at); } - assert_eq!(rig.calls(), 17, "one read per period, the lease never lapsing"); + assert_eq!( + rig.calls(), + 17, + "one read per period, the lease never lapsing" + ); } #[test] @@ -477,10 +507,16 @@ mod tests { reading_at: Some(NOW), status: "rejected".to_string(), fails_with: Some("RateLimited".to_string()), + ..Script::default() }; assert_eq!(rig.meter.tick(NOW), STALE, "the next read is a period away"); assert_eq!(rig.meter.misses, 0); - assert_eq!(rig.lines(), vec![State::Read.line()]); + assert_eq!( + rig.lines(), + vec![format!( + "meter: weekly reading refreshed, permille 60 resets_at_unix_ms {RESET}" + )] + ); rig.reads(NOW + 15 * MIN); rig.meter.tick(NOW + 15 * MIN); assert_eq!(rig.calls(), 2, "a rejected reading is kept fresh"); @@ -495,13 +531,83 @@ mod tests { assert_eq!(rig.meter.misses, 1); } + #[test] + fn a_refresh_logs_the_reading_and_an_unchanged_value_logs_again() { + let mut rig = rig(); + rig.reads(NOW); + rig.meter.tick(NOW); + rig.reads(NOW + 15 * MIN); + rig.meter.tick(NOW + 15 * MIN); + let line = + format!("meter: weekly reading refreshed, permille 60 resets_at_unix_ms {RESET}"); + assert_eq!(rig.lines(), vec![line.clone(), line]); + } + + #[test] + fn the_logged_value_follows_the_reading_and_an_expired_week_is_unknown() { + let mut rig = rig(); + for (at, permille) in [(NOW, 60), (NOW + 15 * MIN, 75)] { + *rig.script.lock().unwrap() = Script { + reading_at: Some(at), + status: "allowed".to_string(), + permille: Some(permille), + resets_at: Some(RESET + permille as u64), + ..Script::default() + }; + rig.meter.tick(at); + } + let mut expired = self::rig(); + let now = unix_ms(); + *expired.script.lock().unwrap() = Script { + reading_at: Some(now), + status: "allowed".to_string(), + resets_at: Some(1), + ..Script::default() + }; + expired.meter.tick(now); + assert_eq!( + expired.lines(), + vec!["meter: weekly reading refreshed, permille unknown resets_at_unix_ms 1"] + ); + assert_eq!( + rig.lines(), + vec![ + format!( + "meter: weekly reading refreshed, permille 60 resets_at_unix_ms {}", + RESET + 60 + ), + format!( + "meter: weekly reading refreshed, permille 75 resets_at_unix_ms {}", + RESET + 75 + ), + ] + ); + } + + #[test] + fn idle_logs_once_per_change_however_often_it_repeats() { + let mut rig = rig(); + rig.lease = None; + for step in 0..3 { + rig.meter.tick(NOW + 60 * MIN * (step + 1)); + } + assert_eq!(rig.lines(), vec![State::Idle.line()]); + } + #[test] fn the_log_says_what_the_meter_is_doing_in_words() { assert_eq!( State::Idle.line(), "meter: no lease asked lately, making no call" ); - assert_eq!(State::Read.line(), "meter: weekly reading refreshed"); + assert_eq!( + State::Read { + permille: None, + resets_at_unix_ms: 7 + } + .line(), + "meter: weekly reading refreshed, permille unknown resets_at_unix_ms 7" + ); assert_eq!( State::Unread.line(), "meter: the call completed without a weekly reading, backing off" @@ -527,6 +633,7 @@ mod tests { reading_at: Some(unix_ms() + 60 * MIN), status: "allowed".to_string(), fails_with: None, + ..Script::default() })), }; start(cell.clone(), Box::new(probe)).unwrap(); diff --git a/crates/claude-connector/src/openai_chat.rs b/crates/claude-connector/src/openai_chat.rs new file mode 100644 index 0000000..e86f0dd --- /dev/null +++ b/crates/claude-connector/src/openai_chat.rs @@ -0,0 +1,625 @@ +//! The OpenAI-compatible Chat Completions backend: one non-streaming +//! `POST {base_url}/chat/completions` per call against a configured `base_url` +//! with an optional systemd API key credential (sent as `Authorization: Bearer`, +//! omitted only for keyless loopback HTTP). +//! +//! No vendor dialect enum lives here. Non-standard non-null fields on the +//! assistant message (such as DeepSeek `reasoning_content`) and on each tool +//! call (such as Gemini `extra_content.google.thought_signature`) are captured +//! generically into one opaque `ReasoningState` JSON object +//! `{"message":{...},"tool_calls":{call_id:{...}}}` and restored byte-exact on +//! replay onto the same assistant message and tool calls. Foreign provider +//! state is refused before sending. +//! +//! Per-model `ModelRow` policies govern `efforts` / `unset_effort`, +//! `forced_tool_choice` (using `ModelRow::thinking_active` so +//! `unset_effort: Some("none")` counts as thinking-inactive), `output_schema`, +//! and `strict_tools`. + +use std::time::Duration; + +use model_connector::{ + FailureKind, InputItem, ProviderRequest, StopReason, ToolChoice, TransportEvent, + TransportEventPayload, TransportOutcome, Usage, +}; +use serde_json::{Map, Value, json}; +use zeroize::Zeroizing; + +use crate::config::{ModelRow, OutputSchemaSupport}; +use crate::credential::{CredentialTokenSource, TokenSource, credential_ready}; +use crate::http::{build_agent, failed, http_failure, read_key, transport_failure, zero_usage}; + +const BACKEND_LABEL: &str = "openai-chat"; + +const STANDARD_MESSAGE_FIELDS: &[&str] = &[ + "role", + "content", + "tool_calls", + "refusal", + "annotations", + "audio", + "function_call", +]; + +const STANDARD_TOOL_CALL_FIELDS: &[&str] = &["id", "type", "function", "index"]; + +/// What the connector's config hands the OpenAI-compatible backend. +#[derive(Debug, Clone)] +pub struct OpenAiChatConfig { + /// Provider tag written on receipts and matched on reasoning state items. + pub provider_id: String, + /// Base URL for the Chat Completions API (`https://...` or loopback `http://...`), + /// including any version path segment (e.g. `/v1` or `/v1beta/openai`). + pub base_url: String, + /// The name of the systemd credential that holds the bearer token, under + /// `$CREDENTIALS_DIRECTORY`; `None` only for a loopback HTTP `base_url`. + pub key_credential: Option, + /// Schema keywords to strip-and-describe in strict tool mode (handled in Cut 4). + pub strict_unsupported: Vec, + /// The whole call, connect to the last byte of the response. + pub deadline: Duration, + /// The largest response body read. + pub max_response_bytes: usize, +} + +/// Answers each call with one HTTP request to `POST {base_url}/chat/completions`. +pub struct OpenAiChatBackend { + provider_id: String, + agent: ureq::Agent, + endpoint: String, + keys: Option>, + max_response_bytes: u64, +} + +impl OpenAiChatBackend { + /// The backend over the configured base URL, with an optional bearer token + /// read from the credential `config.key_credential` names. + pub fn new(config: OpenAiChatConfig) -> Self { + let keys = config.key_credential.as_ref().map(|name| { + Box::new(CredentialTokenSource::from_environment(name.clone())) as Box + }); + Self::with_parts(config, keys) + } + + pub(crate) fn with_parts(config: OpenAiChatConfig, keys: Option>) -> Self { + let endpoint = format!("{}/chat/completions", config.base_url.trim_end_matches('/')); + Self { + provider_id: config.provider_id, + agent: build_agent(config.deadline), + endpoint, + keys, + max_response_bytes: config.max_response_bytes as u64, + } + } + + pub fn provider_id(&self) -> &str { + &self.provider_id + } + + pub fn ready(&self) -> Result<(), &'static str> { + match &self.keys { + Some(source) => credential_ready(source.as_ref()), + None => Ok(()), + } + } + + pub(crate) fn run_model( + &self, + request: &ProviderRequest, + row: &ModelRow, + ) -> (Vec, TransportOutcome) { + let key = match read_key(self.keys.as_deref(), BACKEND_LABEL) { + Ok(key) => key, + Err(failure) => return failure, + }; + let body = match render(request, &self.provider_id, row).and_then(|body| { + serde_json::to_vec(&body).map_err(|_| "the request could not be encoded".to_string()) + }) { + Ok(body) => body, + Err(message) => { + return failed( + FailureKind::InvalidRequest, + format!("{BACKEND_LABEL}: {message}"), + Some(zero_usage()), + ); + } + }; + let mut post = self + .agent + .post(&self.endpoint) + .header("content-type", "application/json"); + if let Some(key) = &key { + let bearer = Zeroizing::new(format!("Bearer {}", key.as_str())); + post = post.header("authorization", bearer.as_str()); + } + let sent = post.send(&body[..]); + let mut response = match sent { + Ok(response) => response, + Err(error) => return transport_failure(BACKEND_LABEL, &error), + }; + let status = response.status().as_u16(); + let text = match response + .body_mut() + .with_config() + .limit(self.max_response_bytes) + .read_to_vec() + { + Ok(bytes) => bytes, + Err(error) => return transport_failure(BACKEND_LABEL, &error), + }; + if !(200..300).contains(&status) { + return http_failure( + BACKEND_LABEL, + status, + &text, + key.as_deref().map(String::as_str), + spend_exhausted, + ); + } + let required = request.tool_choice == ToolChoice::Required && !request.tools.is_empty(); + match parse(&text, required) { + Ok(done) => { + let events = done + .payloads + .into_iter() + .enumerate() + .map(|(sequence, payload)| TransportEvent { + sequence: sequence as u64, + payload, + }) + .collect(); + ( + events, + TransportOutcome::Completed { + provider_response_id: done.id, + stop_reason: done.stop_reason, + usage: done.usage, + }, + ) + } + Err(failure) => failed(failure.kind, failure.message, failure.usage), + } + } +} + +// ---- request ---- + +/// Lowers `request` into a Chat Completions JSON body, or explains why the +/// request is refused before sending. +fn render(request: &ProviderRequest, provider_id: &str, row: &ModelRow) -> Result { + let effort = row.resolve_effort(request.reasoning_effort)?; + if request.tool_choice == ToolChoice::Required + && !row.allows_forced_tool_choice(ModelRow::thinking_active(effort)) + { + return Err(format!( + "model {} does not accept a required tool choice", + row.id + )); + } + if request.output_schema_json.is_some() && row.output_schema == OutputSchemaSupport::None { + return Err(format!("model {} does not accept an output schema", row.id)); + } + + let mut body = Map::new(); + body.insert("model".into(), json!(request.model)); + body.insert( + "max_completion_tokens".into(), + json!(request.max_output_tokens), + ); + if let Some(level) = effort { + body.insert("reasoning_effort".into(), json!(level)); + } + + let messages = messages_of(&request.instructions, &request.input, provider_id)?; + body.insert("messages".into(), Value::Array(messages)); + + if !request.tools.is_empty() { + let mut tools = Vec::with_capacity(request.tools.len()); + for tool in &request.tools { + let schema: Value = serde_json::from_str(&tool.parameters_json) + .map_err(|_| format!("tool {} has parameters that are not JSON", tool.name))?; + tools.push(json!({ + "type": "function", + "function": { + "name": tool.name, + "description": tool.description, + "parameters": schema, + "strict": row.strict_tools, + } + })); + } + body.insert("tools".into(), Value::Array(tools)); + body.insert( + "parallel_tool_calls".into(), + json!(request.parallel_tool_calls), + ); + if request.tool_choice == ToolChoice::Required { + body.insert("tool_choice".into(), json!("required")); + } + } + + if let Some(schema) = &request.output_schema_json { + let schema: Value = serde_json::from_str(schema) + .map_err(|_| "the output schema is not JSON".to_string())?; + body.insert( + "response_format".into(), + json!({ + "type": "json_schema", + "json_schema": { + "name": "output_schema", + "schema": schema, + "strict": true, + } + }), + ); + } + + Ok(Value::Object(body)) +} + +#[derive(Default)] +struct AssistantTurn { + text: String, + tool_calls: Vec, + restored_message: Map, + restored_tool_calls: Map, +} + +impl AssistantTurn { + fn flush(mut self) -> Value { + let mut message = Map::new(); + message.insert("role".into(), json!("assistant")); + message.insert( + "content".into(), + if self.text.is_empty() { + Value::Null + } else { + Value::String(self.text) + }, + ); + for (key, value) in self.restored_message { + if !matches!(key.as_str(), "role" | "content" | "tool_calls") { + message.insert(key, value); + } + } + if !self.tool_calls.is_empty() { + for tool_call in &mut self.tool_calls { + let Some(call_id) = tool_call["id"].as_str() else { + continue; + }; + if let Some(Value::Object(extra)) = self.restored_tool_calls.get(call_id) + && let Some(obj) = tool_call.as_object_mut() + { + for (key, value) in extra { + if !matches!(key.as_str(), "id" | "type" | "function") { + obj.insert(key.clone(), value.clone()); + } + } + } + } + message.insert("tool_calls".into(), Value::Array(self.tool_calls)); + } + Value::Object(message) + } +} + +fn messages_of( + instructions: &str, + input: &[InputItem], + provider_id: &str, +) -> Result, String> { + let mut messages = Vec::with_capacity(input.len() + 1); + messages.push(json!({ + "role": "system", + "content": instructions, + })); + + let mut open_assistant: Option = None; + for item in input { + match item { + InputItem::UserText { text } => { + if let Some(turn) = open_assistant.take() { + messages.push(turn.flush()); + } + messages.push(json!({ + "role": "user", + "content": text, + })); + } + InputItem::ToolResult { call_id, output } => { + if let Some(turn) = open_assistant.take() { + messages.push(turn.flush()); + } + messages.push(json!({ + "role": "tool", + "tool_call_id": call_id, + "content": output, + })); + } + InputItem::AssistantText { text } => { + let turn = open_assistant.get_or_insert_with(AssistantTurn::default); + turn.text.push_str(text); + } + InputItem::ToolCall { + call_id, + name, + arguments, + } => { + let turn = open_assistant.get_or_insert_with(AssistantTurn::default); + turn.tool_calls.push(json!({ + "id": call_id, + "type": "function", + "function": { + "name": name, + "arguments": arguments, + } + })); + } + InputItem::ReasoningState { + provider, state, .. + } => { + if provider != provider_id { + return Err("a reasoning state belongs to another provider".to_string()); + } + let turn = open_assistant.get_or_insert_with(AssistantTurn::default); + apply_reasoning_state(turn, state)?; + } + } + } + if let Some(turn) = open_assistant { + messages.push(turn.flush()); + } + Ok(messages) +} + +fn apply_reasoning_state(turn: &mut AssistantTurn, state: &[u8]) -> Result<(), String> { + let parsed: Value = serde_json::from_slice(state) + .map_err(|_| "a reasoning state is not valid JSON".to_string())?; + let Some(obj) = parsed.as_object() else { + return Err("a reasoning state is not a JSON object".to_string()); + }; + let (Some(msg_fields), Some(tc_fields)) = ( + obj.get("message").and_then(Value::as_object), + obj.get("tool_calls").and_then(Value::as_object), + ) else { + return Err("a reasoning state is missing message or tool_calls maps".to_string()); + }; + for (key, value) in msg_fields { + turn.restored_message.insert(key.clone(), value.clone()); + } + for (call_id, value) in tc_fields { + let Some(fields) = value.as_object() else { + return Err("a tool call reasoning state entry is not an object".to_string()); + }; + let entry = turn + .restored_tool_calls + .entry(call_id.clone()) + .or_insert_with(|| Value::Object(Map::new())); + if let Some(existing) = entry.as_object_mut() { + for (k, v) in fields { + existing.insert(k.clone(), v.clone()); + } + } + } + Ok(()) +} + +// ---- response ---- + +struct Done { + id: Option, + payloads: Vec, + stop_reason: StopReason, + usage: Usage, +} + +struct Failure { + kind: FailureKind, + message: String, + usage: Option, +} + +/// `required`: the request forced a tool call, so an answer without one is a +/// failure, never a completed turn. +fn parse(bytes: &[u8], required: bool) -> Result { + let provider_failure = |message: &str, usage: Option| Failure { + kind: FailureKind::Provider, + message: format!("{BACKEND_LABEL}: {message}"), + usage, + }; + let response: Value = serde_json::from_slice(bytes) + .map_err(|_| provider_failure("the response is not JSON", None))?; + let usage = usage_of(&response["usage"]); + let choice = response["choices"] + .as_array() + .and_then(|choices| choices.first()) + .ok_or_else(|| provider_failure("the response has no choices", usage.clone()))?; + + let stop_reason = match choice["finish_reason"].as_str() { + Some("stop") => StopReason::EndTurn, + Some("tool_calls") => StopReason::ToolUse, + Some("length") => StopReason::MaxOutputTokens, + Some("content_filter") => StopReason::Refusal, + Some("insufficient_system_resource") => { + return Err(Failure { + kind: FailureKind::Unavailable, + message: format!("{BACKEND_LABEL}: insufficient system resource"), + usage, + }); + } + Some("aborted") => return Err(provider_failure("the generation was aborted", usage)), + _ => { + return Err(provider_failure( + "the finish reason is not one this backend maps", + usage, + )); + } + }; + + let message = choice["message"] + .as_object() + .ok_or_else(|| provider_failure("the response choice has no message", usage.clone()))?; + + let mut payloads = Vec::new(); + let mut captured_message = Map::new(); + for (key, value) in message { + if !STANDARD_MESSAGE_FIELDS.contains(&key.as_str()) && !value.is_null() { + captured_message.insert(key.clone(), value.clone()); + } + } + + if let Some(text) = message + .get("content") + .and_then(Value::as_str) + .filter(|text| !text.is_empty()) + { + payloads.push(TransportEventPayload::TextDelta { + text: text.to_string(), + }); + } + + let mut captured_tool_calls = Map::new(); + let mut has_tool_call = false; + if let Some(tool_calls_val) = message.get("tool_calls").filter(|v| !v.is_null()) { + let Some(tool_calls) = tool_calls_val.as_array() else { + return Err(provider_failure("tool_calls is not an array", usage)); + }; + for tool_call in tool_calls { + let Some(tc_obj) = tool_call.as_object() else { + return Err(provider_failure("a tool call is not an object", usage)); + }; + let Some(id) = tc_obj + .get("id") + .and_then(Value::as_str) + .filter(|id| !id.is_empty()) + else { + return Err(provider_failure("a tool call has no id", usage)); + }; + let Some(function) = tc_obj.get("function").and_then(Value::as_object) else { + return Err(provider_failure("a tool call has no function", usage)); + }; + let Some(name) = function + .get("name") + .and_then(Value::as_str) + .filter(|name| !name.is_empty()) + else { + return Err(provider_failure("a tool call has no function name", usage)); + }; + let Some(arguments) = function + .get("arguments") + .and_then(Value::as_str) + .filter(|args| !args.is_empty()) + else { + return Err(provider_failure( + "a tool call has missing or empty arguments", + usage, + )); + }; + has_tool_call = true; + payloads.push(TransportEventPayload::ToolCall { + call_id: id.to_string(), + name: name.to_string(), + arguments: arguments.to_string(), + }); + + let mut tc_extra = Map::new(); + for (key, value) in tc_obj { + if !STANDARD_TOOL_CALL_FIELDS.contains(&key.as_str()) && !value.is_null() { + tc_extra.insert(key.clone(), value.clone()); + } + } + if !tc_extra.is_empty() { + captured_tool_calls.insert(id.to_string(), Value::Object(tc_extra)); + } + } + } + + if !captured_message.is_empty() || !captured_tool_calls.is_empty() { + let state = serde_json::to_vec(&json!({ + "message": captured_message, + "tool_calls": captured_tool_calls, + })) + .unwrap_or_default(); + payloads.push(TransportEventPayload::ReasoningState { state }); + } + + if required && !has_tool_call { + return Err(provider_failure("a required tool call did not come", usage)); + } + + Ok(Done { + id: response["id"].as_str().map(str::to_string), + payloads, + stop_reason, + usage: usage.unwrap_or_else(zero_usage), + }) +} + +fn usage_of(usage: &Value) -> Option { + usage.is_object().then(|| { + let prompt_tokens = usage["prompt_tokens"].as_u64().unwrap_or(0); + let cache_read_tokens = usage["prompt_tokens_details"]["cached_tokens"] + .as_u64() + .or_else(|| usage["prompt_cache_hit_tokens"].as_u64()) + .unwrap_or(0); + Usage { + input_tokens: prompt_tokens.saturating_sub(cache_read_tokens), + cache_read_tokens, + cache_write_tokens: 0, + output_tokens: usage["completion_tokens"].as_u64().unwrap_or(0), + reasoning_tokens: usage["completion_tokens_details"]["reasoning_tokens"].as_u64(), + } + }) +} + +// ---- failures ---- + +const SPENT_BALANCE_TYPES_OR_CODES: &[&str] = &[ + "insufficient_balance", + "insufficient_quota", + "billing_hard_limit_reached", +]; + +const SPENT_BALANCE_PREFIXES: &[&str] = &[ + "insufficient balance", + "your credit balance is too low", + "you have reached your specified api usage limits", + "you exceeded your current quota", + "insufficient quota", + "billing hard limit", +]; + +fn spend_exhausted(status: u16, error: &Value) -> bool { + let tag_matches = |tag: Option<&str>, allowed: &[&str]| { + tag.is_some_and(|v| { + let lowered = v.trim().to_ascii_lowercase(); + allowed.iter().any(|candidate| lowered == *candidate) + }) + }; + let msg_starts_with = |prefixes: &[&str]| { + error["message"].as_str().is_some_and(|text| { + let lowered = text.trim_start().to_ascii_lowercase(); + prefixes.iter().any(|prefix| lowered.starts_with(prefix)) + }) + }; + match status { + 400 => { + tag_matches(error["type"].as_str(), SPENT_BALANCE_TYPES_OR_CODES) + || tag_matches(error["code"].as_str(), SPENT_BALANCE_TYPES_OR_CODES) + || msg_starts_with(SPENT_BALANCE_PREFIXES) + } + 429 => { + tag_matches(error["type"].as_str(), &["insufficient_quota"]) + || tag_matches(error["code"].as_str(), &["insufficient_quota"]) + || msg_starts_with(&[ + "you exceeded your current quota", + "insufficient quota", + "insufficient_quota", + ]) + } + _ => false, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/claude-connector/src/openai_chat/tests.rs b/crates/claude-connector/src/openai_chat/tests.rs new file mode 100644 index 0000000..126222e --- /dev/null +++ b/crates/claude-connector/src/openai_chat/tests.rs @@ -0,0 +1,1083 @@ +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::sync::{Arc, Mutex}; +use std::thread; + +use model_connector::{ReasoningEffort, ToolDefinition}; +use serde_json::json; +use zeroize::Zeroizing; + +use super::*; +use crate::config::{EffortMap, ForcedToolChoice}; + +const PROVIDER: &str = "openai-compat"; +const KEY: &str = "sk-oai-test-canary-9876"; + +struct Fixed(Option<&'static str>); + +impl TokenSource for Fixed { + fn read(&self) -> Option> { + self.0.map(|key| Zeroizing::new(key.to_string())) + } +} + +struct Seen { + path: String, + headers: Vec<(String, String)>, + body: Value, +} + +impl Seen { + fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + } +} + +fn mock(responses: Vec<(u16, String)>) -> (String, Arc>>) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let seen = Arc::new(Mutex::new(Vec::new())); + let log = seen.clone(); + thread::spawn(move || { + for (status, body) in responses { + let Ok((mut stream, _)) = listener.accept() else { + return; + }; + let req = read_http_request(&mut stream); + log.lock().unwrap().push(req); + let reason = match status { + 200 => "OK", + 400 => "Bad Request", + 401 => "Unauthorized", + 402 => "Payment Required", + 403 => "Forbidden", + 404 => "Not Found", + 408 => "Request Timeout", + 429 => "Too Many Requests", + 500 => "Internal Server Error", + 502 => "Bad Gateway", + 503 => "Service Unavailable", + 504 => "Gateway Timeout", + _ => "Status", + }; + let _ = write!( + stream, + "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}", + body.len(), + body + ); + } + }); + (url, seen) +} + +fn read_http_request(stream: &mut std::net::TcpStream) -> Seen { + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + let mut header_end = None; + let mut content_len = 0usize; + loop { + let n = stream.read(&mut chunk).unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + if header_end.is_none() + && let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") + { + let end = pos + 4; + header_end = Some(end); + let headers = String::from_utf8_lossy(&buf[..pos]); + for line in headers.lines().skip(1) { + if let Some((k, v)) = line.split_once(':') + && k.eq_ignore_ascii_case("content-length") + { + content_len = v.trim().parse().unwrap_or(0); + } + } + } + if let Some(end) = header_end + && buf.len() >= end + content_len + { + break; + } + } + let end = header_end.unwrap_or(buf.len()); + let head = String::from_utf8_lossy(&buf[..end]); + let mut lines = head.lines(); + let path = lines + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .unwrap_or("") + .to_string(); + let headers = lines + .filter_map(|line| { + let (k, v) = line.split_once(':')?; + Some((k.trim().to_string(), v.trim().to_string())) + }) + .collect(); + let body = serde_json::from_slice(&buf[end..end + content_len]).unwrap_or(Value::Null); + Seen { + path, + headers, + body, + } +} + +fn backend(url: String, key: Option<&'static str>) -> OpenAiChatBackend { + OpenAiChatBackend::with_parts( + OpenAiChatConfig { + provider_id: PROVIDER.to_string(), + base_url: url, + key_credential: key.map(|_| "oai-key".to_string()), + strict_unsupported: Vec::new(), + deadline: Duration::from_secs(10), + max_response_bytes: 1 << 20, + }, + key.map(|k| Box::new(Fixed(Some(k))) as Box), + ) +} + +fn deepseek_row() -> ModelRow { + ModelRow { + id: "ds-flash".to_string(), + provider: PROVIDER.to_string(), + upstream: "deepseek-chat".to_string(), + efforts: EffortMap { + low: Some("low".to_string()), + medium: Some("high".to_string()), + high: Some("high".to_string()), + max: Some("max".to_string()), + }, + unset_effort: Some("none".to_string()), + forced_tool_choice: ForcedToolChoice::WithoutThinking, + output_schema: OutputSchemaSupport::None, + strict_tools: true, + } +} + +fn openai_row() -> ModelRow { + ModelRow { + id: "oai-5".to_string(), + provider: PROVIDER.to_string(), + upstream: "gpt-5".to_string(), + efforts: EffortMap { + low: Some("low".to_string()), + medium: Some("medium".to_string()), + high: Some("high".to_string()), + max: None, + }, + unset_effort: None, + forced_tool_choice: ForcedToolChoice::Never, + output_schema: OutputSchemaSupport::Native, + strict_tools: true, + } +} + +fn weather_tool() -> ToolDefinition { + ToolDefinition { + name: "get_weather".to_string(), + description: "Get current weather".to_string(), + parameters_json: json!({ + "type": "object", + "properties": {"city": {"type": "string"}}, + "required": ["city"], + "additionalProperties": false + }) + .to_string(), + } +} + +fn base_request(model: &str) -> ProviderRequest { + let mut req = ProviderRequest::new("req-1", "conv-1", model, "Be brief.", 1024); + req.input = vec![InputItem::UserText { + text: "Hello".to_string(), + }]; + req +} + +fn chat_ok(id: &str, message: Value, finish_reason: &str, usage: Value) -> String { + json!({ + "id": id, + "choices": [{ + "index": 0, + "message": message, + "finish_reason": finish_reason, + }], + "usage": usage, + }) + .to_string() +} + +fn failure_of(outcome: &TransportOutcome) -> (FailureKind, &str, Option<&Usage>) { + match outcome { + TransportOutcome::Failed { + kind, + message, + usage, + } => (*kind, message.as_str(), usage.as_ref()), + other => panic!("expected Failed, got {other:?}"), + } +} + +#[test] +fn golden_deepseek_and_openai_request_bodies() { + let reply_ds = chat_ok( + "ds-1", + json!({ + "role": "assistant", + "content": null, + "tool_calls": [{ + "id": "call_1", + "type": "function", + "function": {"name": "get_weather", "arguments": "{\"city\":\"Oslo\"}"} + }] + }), + "tool_calls", + json!({"prompt_tokens": 12, "completion_tokens": 8}), + ); + let reply_oai = chat_ok( + "oai-1", + json!({"role": "assistant", "content": "{\"ok\":true}", "refusal": null}), + "stop", + json!({"prompt_tokens": 10, "completion_tokens": 4}), + ); + let (url, seen) = mock(vec![(200, reply_ds), (200, reply_oai)]); + let client = backend(url, Some(KEY)); + + // DeepSeek-shaped row: unset_effort "none" permits Required under WithoutThinking. + let ds = deepseek_row(); + let mut ds_req = base_request(&ds.upstream); + ds_req.tools = vec![weather_tool()]; + ds_req.tool_choice = ToolChoice::Required; + ds_req.parallel_tool_calls = true; + + let (_, outcome) = client.run_model(&ds_req, &ds); + assert!(matches!(outcome, TransportOutcome::Completed { .. })); + + // DeepSeek-shaped row refuses active thinking + Required BEFORE sending. + let mut ds_thinking_req = ds_req.clone(); + ds_thinking_req.reasoning_effort = Some(ReasoningEffort::High); + let (_, outcome) = client.run_model(&ds_thinking_req, &ds); + assert_eq!(failure_of(&outcome).0, FailureKind::InvalidRequest); + + // DeepSeek-shaped row refuses output_schema when OutputSchemaSupport::None BEFORE sending. + let mut ds_schema_req = base_request(&ds.upstream); + ds_schema_req.output_schema_json = Some(json!({"type": "object"}).to_string()); + let (_, outcome) = client.run_model(&ds_schema_req, &ds); + assert_eq!(failure_of(&outcome).0, FailureKind::InvalidRequest); + + // OpenAI-shaped row: json_schema strict: true, max_completion_tokens, mapped reasoning_effort. + let oai = openai_row(); + let mut oai_req = base_request(&oai.upstream); + oai_req.reasoning_effort = Some(ReasoningEffort::Medium); + oai_req.output_schema_json = Some( + json!({ + "type": "object", + "properties": {"ok": {"type": "boolean"}}, + "required": ["ok"], + "additionalProperties": false + }) + .to_string(), + ); + let (_, outcome) = client.run_model(&oai_req, &oai); + assert!(matches!(outcome, TransportOutcome::Completed { .. })); + + // OpenAI-shaped row refuses unmapped effort BEFORE sending. + let mut oai_bad_effort = base_request(&oai.upstream); + oai_bad_effort.reasoning_effort = Some(ReasoningEffort::Max); + let (_, outcome) = client.run_model(&oai_bad_effort, &oai); + assert_eq!(failure_of(&outcome).0, FailureKind::InvalidRequest); + + // OpenAI-shaped row refuses ToolChoice::Required when ForcedToolChoice::Never BEFORE sending. + let mut oai_forced = base_request(&oai.upstream); + oai_forced.tools = vec![weather_tool()]; + oai_forced.tool_choice = ToolChoice::Required; + let (_, outcome) = client.run_model(&oai_forced, &oai); + assert_eq!(failure_of(&outcome).0, FailureKind::InvalidRequest); + + // Only the two valid requests reached the wire. + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 2); + assert_eq!( + seen[0].body, + json!({ + "model": "deepseek-chat", + "max_completion_tokens": 1024, + "reasoning_effort": "none", + "messages": [ + {"role": "system", "content": "Be brief."}, + {"role": "user", "content": "Hello"} + ], + "tools": [{ + "type": "function", + "function": { + "name": "get_weather", + "description": "Get current weather", + "parameters": { + "type": "object", + "properties": {"city": {"type": "string"}}, + "required": ["city"], + "additionalProperties": false + }, + "strict": true + } + }], + "parallel_tool_calls": true, + "tool_choice": "required" + }) + ); + assert_eq!( + seen[1].body, + json!({ + "model": "gpt-5", + "max_completion_tokens": 1024, + "reasoning_effort": "medium", + "messages": [ + {"role": "system", "content": "Be brief."}, + {"role": "user", "content": "Hello"} + ], + "response_format": { + "type": "json_schema", + "json_schema": { + "name": "output_schema", + "schema": { + "type": "object", + "properties": {"ok": {"type": "boolean"}}, + "required": ["ok"], + "additionalProperties": false + }, + "strict": true + } + } + }) + ); +} + +#[test] +fn two_tool_calls_collapse_into_one_assistant_message_and_tool_messages() { + let reply = chat_ok( + "c-1", + json!({"role": "assistant", "content": "All done."}), + "stop", + json!({"prompt_tokens": 20, "completion_tokens": 5}), + ); + let (url, seen) = mock(vec![(200, reply.clone()), (200, reply)]); + let client = backend(url, Some(KEY)); + let row = deepseek_row(); + + // Case 1: assistant text + two tool calls + two tool results. + let mut req = base_request(&row.upstream); + req.input.extend([ + InputItem::AssistantText { + text: "Checking both.".to_string(), + }, + InputItem::ToolCall { + call_id: "call_a".to_string(), + name: "get_weather".to_string(), + arguments: r#"{"city":"Oslo"}"#.to_string(), + }, + InputItem::ToolCall { + call_id: "call_b".to_string(), + name: "get_weather".to_string(), + arguments: r#"{"city":"Bergen"}"#.to_string(), + }, + InputItem::ToolResult { + call_id: "call_a".to_string(), + output: "4C".to_string(), + }, + InputItem::ToolResult { + call_id: "call_b".to_string(), + output: "7C".to_string(), + }, + ]); + let (_, outcome) = client.run_model(&req, &row); + assert!(matches!(outcome, TransportOutcome::Completed { .. })); + + // Case 2: tool-call-only assistant turn (no text) emits content: null. + let mut req_null = base_request(&row.upstream); + req_null.input.extend([ + InputItem::ToolCall { + call_id: "call_x".to_string(), + name: "get_weather".to_string(), + arguments: r#"{"city":"Trondheim"}"#.to_string(), + }, + InputItem::ToolResult { + call_id: "call_x".to_string(), + output: "2C".to_string(), + }, + ]); + let (_, outcome) = client.run_model(&req_null, &row); + assert!(matches!(outcome, TransportOutcome::Completed { .. })); + + let seen = seen.lock().unwrap(); + assert_eq!( + seen[0].body["messages"], + json!([ + {"role": "system", "content": "Be brief."}, + {"role": "user", "content": "Hello"}, + { + "role": "assistant", + "content": "Checking both.", + "tool_calls": [ + { + "id": "call_a", + "type": "function", + "function": {"name": "get_weather", "arguments": r#"{"city":"Oslo"}"#} + }, + { + "id": "call_b", + "type": "function", + "function": {"name": "get_weather", "arguments": r#"{"city":"Bergen"}"#} + } + ] + }, + {"role": "tool", "tool_call_id": "call_a", "content": "4C"}, + {"role": "tool", "tool_call_id": "call_b", "content": "7C"} + ]) + ); + assert_eq!(seen[1].body["messages"][2]["content"], Value::Null); +} + +#[test] +fn reasoning_content_and_extra_content_round_trip_byte_exact() { + let reply_with_state = chat_ok( + "r-state", + json!({ + "role": "assistant", + "content": null, + "refusal": null, + "annotations": [], + "reasoning_content": "Let me think step-by-step:\n1. check Oslo", + "tool_calls": [ + { + "index": 0, + "id": "call_1", + "type": "function", + "function": {"name": "get_weather", "arguments": r#"{"city":"Oslo"}"#}, + "extra_content": {"google": {"thought_signature": "SigBlob==/123"}} + }, + { + "index": 1, + "id": "call_2", + "type": "function", + "function": {"name": "get_weather", "arguments": r#"{"city":"Tromso"}"#} + } + ] + }), + "tool_calls", + json!({"prompt_tokens": 10, "completion_tokens": 15}), + ); + let reply_standard_only = chat_ok( + "r-std", + json!({ + "role": "assistant", + "content": "Plain answer", + "refusal": null, + "annotations": [], + "reasoning_content": null, + "tool_calls": [{ + "index": 0, + "id": "call_std", + "type": "function", + "function": {"name": "get_weather", "arguments": r#"{"city":"Oslo"}"#}, + "extra_content": null + }] + }), + "tool_calls", + json!({"prompt_tokens": 5, "completion_tokens": 5}), + ); + let reply_done = chat_ok( + "r-done", + json!({"role": "assistant", "content": "Done"}), + "stop", + json!({"prompt_tokens": 30, "completion_tokens": 5}), + ); + + let (url, seen) = mock(vec![ + (200, reply_with_state), + (200, reply_standard_only), + (200, reply_done), + ]); + let client = backend(url, Some(KEY)); + let row = deepseek_row(); + + // 1. Capture reasoning_content and tool_calls[].extra_content into one ReasoningState. + let (events, outcome) = client.run_model(&base_request(&row.upstream), &row); + assert!(matches!(outcome, TransportOutcome::Completed { .. })); + let state_events: Vec<&[u8]> = events + .iter() + .filter_map(|e| match &e.payload { + TransportEventPayload::ReasoningState { state } => Some(state.as_slice()), + _ => None, + }) + .collect(); + assert_eq!(state_events.len(), 1); + let state_json: Value = serde_json::from_slice(state_events[0]).unwrap(); + assert_eq!( + state_json, + json!({ + "message": {"reasoning_content": "Let me think step-by-step:\n1. check Oslo"}, + "tool_calls": { + "call_1": {"extra_content": {"google": {"thought_signature": "SigBlob==/123"}}} + } + }) + ); + + // 2. Standard fields (refusal, annotations, index) and null reasoning emit no ReasoningState. + let (std_events, outcome) = client.run_model(&base_request(&row.upstream), &row); + assert!(matches!(outcome, TransportOutcome::Completed { .. })); + assert!( + !std_events + .iter() + .any(|e| matches!(e.payload, TransportEventPayload::ReasoningState { .. })), + "standard/null fields must not emit ReasoningState: {std_events:?}" + ); + + // 3. Replay restores reasoning_content onto assistant message and extra_content onto call_1 byte-exact. + let mut replay_req = base_request(&row.upstream); + replay_req.input.extend([ + InputItem::ReasoningState { + provider: PROVIDER.to_string(), + model: row.id.clone(), + state: state_events[0].to_vec(), + }, + InputItem::ToolCall { + call_id: "call_1".to_string(), + name: "get_weather".to_string(), + arguments: r#"{"city":"Oslo"}"#.to_string(), + }, + InputItem::ToolCall { + call_id: "call_2".to_string(), + name: "get_weather".to_string(), + arguments: r#"{"city":"Tromso"}"#.to_string(), + }, + InputItem::ToolResult { + call_id: "call_1".to_string(), + output: "4C".to_string(), + }, + InputItem::ToolResult { + call_id: "call_2".to_string(), + output: "-2C".to_string(), + }, + ]); + let (_, outcome) = client.run_model(&replay_req, &row); + assert!(matches!(outcome, TransportOutcome::Completed { .. })); + + // 4. Foreign provider ReasoningState is refused before sending and never reaches the wire. + let mut foreign_req = base_request(&row.upstream); + foreign_req.input.push(InputItem::ReasoningState { + provider: "other-provider".to_string(), + model: "other-model".to_string(), + state: state_events[0].to_vec(), + }); + let (_, outcome) = client.run_model(&foreign_req, &row); + assert_eq!(failure_of(&outcome).0, FailureKind::InvalidRequest); + + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 3); + let replayed_assistant = &seen[2].body["messages"][2]; + assert_eq!( + replayed_assistant["reasoning_content"], + "Let me think step-by-step:\n1. check Oslo" + ); + assert_eq!( + replayed_assistant["tool_calls"][0]["extra_content"], + json!({"google": {"thought_signature": "SigBlob==/123"}}) + ); + assert!( + replayed_assistant["tool_calls"][1] + .get("extra_content") + .is_none() + ); +} + +#[test] +fn usage_maps_cached_tokens_and_prompt_cache_hit_tokens() { + let reply_openai_usage = chat_ok( + "u-1", + json!({"role": "assistant", "content": "a"}), + "stop", + json!({ + "prompt_tokens": 100, + "completion_tokens": 30, + "prompt_tokens_details": {"cached_tokens": 60}, + "completion_tokens_details": {"reasoning_tokens": 12} + }), + ); + let reply_deepseek_usage = chat_ok( + "u-2", + json!({"role": "assistant", "content": "b"}), + "stop", + json!({ + "prompt_tokens": 100, + "completion_tokens": 25, + "prompt_cache_hit_tokens": 80, + "prompt_cache_miss_tokens": 20, + "completion_tokens_details": {"reasoning_tokens": 9} + }), + ); + let reply_saturating = chat_ok( + "u-3", + json!({"role": "assistant", "content": "c"}), + "stop", + json!({ + "prompt_tokens": 10, + "completion_tokens": 2, + "prompt_tokens_details": {"cached_tokens": 50} + }), + ); + + let (url, _) = mock(vec![ + (200, reply_openai_usage), + (200, reply_deepseek_usage), + (200, reply_saturating), + ]); + let client = backend(url, Some(KEY)); + let row = deepseek_row(); + + let (_, outcome_1) = client.run_model(&base_request(&row.upstream), &row); + assert_eq!( + outcome_1, + TransportOutcome::Completed { + provider_response_id: Some("u-1".to_string()), + stop_reason: StopReason::EndTurn, + usage: Usage { + input_tokens: 40, + cache_read_tokens: 60, + cache_write_tokens: 0, + output_tokens: 30, + reasoning_tokens: Some(12), + }, + } + ); + + let (_, outcome_2) = client.run_model(&base_request(&row.upstream), &row); + assert_eq!( + outcome_2, + TransportOutcome::Completed { + provider_response_id: Some("u-2".to_string()), + stop_reason: StopReason::EndTurn, + usage: Usage { + input_tokens: 20, + cache_read_tokens: 80, + cache_write_tokens: 0, + output_tokens: 25, + reasoning_tokens: Some(9), + }, + } + ); + + let (_, outcome_3) = client.run_model(&base_request(&row.upstream), &row); + assert_eq!( + outcome_3, + TransportOutcome::Completed { + provider_response_id: Some("u-3".to_string()), + stop_reason: StopReason::EndTurn, + usage: Usage { + input_tokens: 0, + cache_read_tokens: 50, + cache_write_tokens: 0, + output_tokens: 2, + reasoning_tokens: None, + }, + } + ); +} + +#[test] +fn every_finish_reason_maps_and_required_without_tool_fails() { + let cases = [ + ("stop", Some(StopReason::EndTurn), None), + ("tool_calls", Some(StopReason::ToolUse), None), + ("length", Some(StopReason::MaxOutputTokens), None), + ("content_filter", Some(StopReason::Refusal), None), + ( + "insufficient_system_resource", + None, + Some(FailureKind::Unavailable), + ), + ("aborted", None, Some(FailureKind::Provider)), + ("unknown_reason", None, Some(FailureKind::Provider)), + ]; + let mut responses: Vec<(u16, String)> = cases + .iter() + .enumerate() + .map(|(i, (reason, _, _))| { + ( + 200, + chat_ok( + &format!("fr-{i}"), + json!({"role": "assistant", "content": "text"}), + reason, + json!({"prompt_tokens": 3, "completion_tokens": 2}), + ), + ) + }) + .collect(); + // Null finish_reason case. + responses.push(( + 200, + json!({ + "id": "fr-null", + "choices": [{ + "index": 0, + "message": {"role": "assistant", "content": "text"}, + "finish_reason": null, + }], + "usage": {"prompt_tokens": 3, "completion_tokens": 2}, + }) + .to_string(), + )); + // Required tool call returning zero tool calls. + responses.push(( + 200, + chat_ok( + "fr-req-miss", + json!({"role": "assistant", "content": "no tool called"}), + "stop", + json!({"prompt_tokens": 3, "completion_tokens": 2}), + ), + )); + // Auto tool choice with tools present and zero tool calls completes with TextDelta. + responses.push(( + 200, + chat_ok( + "fr-auto-text", + json!({"role": "assistant", "content": "plain reply"}), + "stop", + json!({"prompt_tokens": 3, "completion_tokens": 2}), + ), + )); + // Empty content string emits no TextDelta event. + responses.push(( + 200, + chat_ok( + "fr-empty-text", + json!({"role": "assistant", "content": ""}), + "stop", + json!({"prompt_tokens": 3, "completion_tokens": 2}), + ), + )); + + let (url, _) = mock(responses); + let client = backend(url, Some(KEY)); + let row = deepseek_row(); + + for (reason, expected_stop, expected_fail) in cases { + let (events, outcome) = client.run_model(&base_request(&row.upstream), &row); + match (expected_stop, expected_fail) { + (Some(stop), None) => { + assert!( + matches!(outcome, TransportOutcome::Completed { stop_reason, .. } if stop_reason == stop), + "{reason}: got {outcome:?}" + ); + assert!( + events.iter().any(|e| matches!( + &e.payload, + TransportEventPayload::TextDelta { text } if text == "text" + )), + "{reason}: missing TextDelta in {events:?}" + ); + } + (None, Some(kind)) => { + let (got_kind, msg, _) = failure_of(&outcome); + assert_eq!(got_kind, kind, "{reason}"); + if reason == "aborted" { + assert!(msg.contains("aborted"), "{msg}"); + } + } + _ => unreachable!(), + } + } + + let (_, null_outcome) = client.run_model(&base_request(&row.upstream), &row); + assert_eq!(failure_of(&null_outcome).0, FailureKind::Provider); + + let mut req_tool = base_request(&row.upstream); + req_tool.tools = vec![weather_tool()]; + req_tool.tool_choice = ToolChoice::Required; + let (_, req_outcome) = client.run_model(&req_tool, &row); + assert_eq!(failure_of(&req_outcome).0, FailureKind::Provider); + + let mut auto_tool = base_request(&row.upstream); + auto_tool.tools = vec![weather_tool()]; + auto_tool.tool_choice = ToolChoice::Auto; + let (auto_events, auto_outcome) = client.run_model(&auto_tool, &row); + assert!(matches!( + auto_outcome, + TransportOutcome::Completed { + stop_reason: StopReason::EndTurn, + .. + } + )); + assert_eq!(auto_events.len(), 1); + assert!(matches!( + &auto_events[0].payload, + TransportEventPayload::TextDelta { text } if text == "plain reply" + )); + + let (empty_events, empty_outcome) = client.run_model(&base_request(&row.upstream), &row); + assert!(matches!( + empty_outcome, + TransportOutcome::Completed { + stop_reason: StopReason::EndTurn, + .. + } + )); + assert!(empty_events.is_empty(), "empty content must emit no events"); +} + +#[test] +fn transport_auth_redirect_proxy_canary_and_http_errors() { + // 1. Version path preservation + Bearer sent vs keyless omitted + HTTP error mapping + canary. + let ok_reply = chat_ok( + "ok-1", + json!({"role": "assistant", "content": "ok"}), + "stop", + json!({"prompt_tokens": 1, "completion_tokens": 1}), + ); + let err_cases: Vec<(u16, Value, FailureKind)> = vec![ + ( + 402, + json!({"error": {"type": "billing_error", "message": format!("Insufficient Balance for {KEY}")}}), + FailureKind::Authentication, + ), + ( + 400, + json!({"error": {"type": "invalid_request_error", "message": format!("Insufficient Balance with key {KEY}")}}), + FailureKind::Authentication, + ), + ( + 400, + json!({"error": {"code": "insufficient_balance", "message": "Account balance is zero"}}), + FailureKind::Authentication, + ), + ( + 429, + json!({"error": {"type": "insufficient_quota", "message": "Quota reached"}}), + FailureKind::Authentication, + ), + ( + 429, + json!({"error": {"code": "insufficient_quota", "message": "Quota reached"}}), + FailureKind::Authentication, + ), + ( + 429, + json!({"error": {"type": "rate_limit_error", "message": "You exceeded your current quota"}}), + FailureKind::Authentication, + ), + ( + 429, + json!({"error": {"type": "rate_limit_error", "message": "Slow down"}}), + FailureKind::RateLimited, + ), + ( + 400, + json!({"error": {"type": "invalid_request_error", "message": "Bad parameter"}}), + FailureKind::InvalidRequest, + ), + ( + 401, + json!({"error": {"type": "authentication_error", "message": "Invalid token"}}), + FailureKind::Authentication, + ), + ( + 403, + json!({"error": {"type": "permission_error", "message": "Forbidden"}}), + FailureKind::Authentication, + ), + ( + 404, + json!({"error": {"type": "not_found_error", "message": "No model"}}), + FailureKind::Provider, + ), + ( + 408, + json!({"error": {"type": "timeout", "message": "Timed out"}}), + FailureKind::Timeout, + ), + ( + 504, + json!({"error": {"type": "timeout", "message": "Gateway timeout"}}), + FailureKind::Timeout, + ), + ( + 500, + json!({"error": {"type": "server_error", "message": "Boom"}}), + FailureKind::Unavailable, + ), + ]; + + let mut responses = vec![(200, ok_reply.clone())]; + responses.extend(err_cases.iter().map(|(s, body, _)| (*s, body.to_string()))); + let (base, seen) = mock(responses); + let versioned = format!("{base}/v1beta/openai/"); + let keyed = backend(versioned, Some(KEY)); + let row = deepseek_row(); + + let (_, ok) = keyed.run_model(&base_request(&row.upstream), &row); + assert!(matches!(ok, TransportOutcome::Completed { .. })); + + for (status, _, expected_kind) in &err_cases { + let (_, outcome) = keyed.run_model(&base_request(&row.upstream), &row); + let (kind, msg, _) = failure_of(&outcome); + assert_eq!(kind, *expected_kind, "status {status}: {msg}"); + assert!( + !msg.contains(KEY), + "bearer canary leaked in error for status {status}: {msg}" + ); + } + + { + let seen = seen.lock().unwrap(); + assert_eq!(seen[0].path, "/v1beta/openai/chat/completions"); + assert_eq!( + seen[0].header("authorization"), + Some(format!("Bearer {KEY}").as_str()) + ); + } + + // 2. Keyless loopback omits Authorization header. + let (url_keyless, seen_keyless) = mock(vec![(200, ok_reply.clone())]); + let keyless = backend(format!("{url_keyless}/v1"), None); + let (_, ok) = keyless.run_model(&base_request(&row.upstream), &row); + assert!(matches!(ok, TransportOutcome::Completed { .. })); + { + let seen_keyless = seen_keyless.lock().unwrap(); + assert_eq!(seen_keyless[0].path, "/v1/chat/completions"); + assert_eq!(seen_keyless[0].header("authorization"), None); + } + + // 3. 302 redirect fails Unavailable without contacting redirect target. + let target = TcpListener::bind("127.0.0.1:0").unwrap(); + target.set_nonblocking(true).unwrap(); + let target_url = format!("http://{}/stolen", target.local_addr().unwrap()); + let redir_listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let redir_url = format!("http://{}", redir_listener.local_addr().unwrap()); + let location = target_url.clone(); + thread::spawn(move || { + let (mut stream, _) = redir_listener.accept().unwrap(); + let _ = read_http_request(&mut stream); + let _ = write!( + stream, + "HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\n\r\n" + ); + }); + let (_, redir_outcome) = + backend(redir_url, Some(KEY)).run_model(&base_request(&row.upstream), &row); + let (kind, msg, _) = failure_of(&redir_outcome); + assert_eq!(kind, FailureKind::Unavailable); + assert!(!msg.contains(KEY)); + assert!( + matches!(target.accept(), Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock), + "redirect target must never be contacted" + ); + + // 4. .proxy(None) ignores HTTP_PROXY / HTTPS_PROXY when OpenAiChatBackend sends. + { + let _guard = crate::http::PROXY_ENV_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let old_http = std::env::var_os("HTTP_PROXY"); + let old_https = std::env::var_os("HTTPS_PROXY"); + + let proxy_listener = TcpListener::bind("127.0.0.1:0").unwrap(); + proxy_listener.set_nonblocking(true).unwrap(); + let proxy_url = format!("http://{}", proxy_listener.local_addr().unwrap()); + + let (direct_url, direct_seen) = mock(vec![(200, ok_reply)]); + // SAFETY: guarded by PROXY_ENV_LOCK. + unsafe { + std::env::set_var("HTTP_PROXY", &proxy_url); + std::env::set_var("HTTPS_PROXY", &proxy_url); + } + let (_, direct_outcome) = + backend(direct_url, Some(KEY)).run_model(&base_request(&row.upstream), &row); + // SAFETY: guarded by PROXY_ENV_LOCK. + unsafe { + match old_http { + Some(v) => std::env::set_var("HTTP_PROXY", v), + None => std::env::remove_var("HTTP_PROXY"), + } + match old_https { + Some(v) => std::env::set_var("HTTPS_PROXY", v), + None => std::env::remove_var("HTTPS_PROXY"), + } + } + assert!(matches!(direct_outcome, TransportOutcome::Completed { .. })); + assert_eq!(direct_seen.lock().unwrap().len(), 1); + assert!( + matches!(proxy_listener.accept(), Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock), + "HTTP_PROXY/HTTPS_PROXY must be ignored" + ); + } + + // 5. Missing credential fails Authentication before sending. + let missing = backend("http://127.0.0.1:9".to_string(), None); + let missing_with_source = OpenAiChatBackend::with_parts( + OpenAiChatConfig { + provider_id: PROVIDER.to_string(), + base_url: "http://127.0.0.1:9".to_string(), + key_credential: Some("missing".to_string()), + strict_unsupported: Vec::new(), + deadline: Duration::from_secs(5), + max_response_bytes: 1 << 20, + }, + Some(Box::new(Fixed(None))), + ); + assert_eq!(missing.ready(), Ok(())); + assert_eq!(missing_with_source.ready(), Err("token_credential")); + let (_, missing_outcome) = missing_with_source.run_model(&base_request(&row.upstream), &row); + assert_eq!(failure_of(&missing_outcome).0, FailureKind::Authentication); + + // 6. Oversized response fails Provider. + let big = chat_ok( + "big", + json!({"role": "assistant", "content": "x".repeat(4096)}), + "stop", + json!({"prompt_tokens": 1, "completion_tokens": 1}), + ); + let (big_url, _) = mock(vec![(200, big)]); + let small_cap = OpenAiChatBackend::with_parts( + OpenAiChatConfig { + provider_id: PROVIDER.to_string(), + base_url: big_url, + key_credential: None, + strict_unsupported: Vec::new(), + deadline: Duration::from_secs(5), + max_response_bytes: 512, + }, + None, + ); + let (_, big_outcome) = small_cap.run_model(&base_request(&row.upstream), &row); + assert_eq!(failure_of(&big_outcome).0, FailureKind::Provider); + + // 7. Dead endpoint fails Unavailable; silent endpoint fails Timeout. + let dead = TcpListener::bind("127.0.0.1:0").unwrap(); + let dead_url = format!("http://{}", dead.local_addr().unwrap()); + drop(dead); + let (_, dead_outcome) = backend(dead_url, None).run_model(&base_request(&row.upstream), &row); + assert_eq!(failure_of(&dead_outcome).0, FailureKind::Unavailable); + + let silent = TcpListener::bind("127.0.0.1:0").unwrap(); + let silent_url = format!("http://{}", silent.local_addr().unwrap()); + let slow = OpenAiChatBackend::with_parts( + OpenAiChatConfig { + provider_id: PROVIDER.to_string(), + base_url: silent_url, + key_credential: None, + strict_unsupported: Vec::new(), + deadline: Duration::from_millis(200), + max_response_bytes: 1 << 20, + }, + None, + ); + let (_, slow_outcome) = slow.run_model(&base_request(&row.upstream), &row); + assert_eq!(failure_of(&slow_outcome).0, FailureKind::Timeout); + drop(silent); +} diff --git a/crates/claude-connector/src/process.rs b/crates/claude-connector/src/process.rs index 2421e0e..b4936ea 100644 --- a/crates/claude-connector/src/process.rs +++ b/crates/claude-connector/src/process.rs @@ -46,6 +46,8 @@ pub trait RunningChild: Send { #[cfg(unix)] pub use unix::StdProcessPort; +#[cfg(unix)] +pub(crate) use unix::place_fd; #[cfg(unix)] mod unix { @@ -77,7 +79,7 @@ mod unix { /// Makes `source` also descriptor `target`, open across exec. Runs between /// fork and exec in the child, so it calls nothing but `dup2` and `fcntl`. - fn place_fd(source: RawFd, target: RawFd) -> io::Result<()> { + pub(crate) fn place_fd(source: RawFd, target: RawFd) -> io::Result<()> { // SAFETY: dup2 and fcntl take integers only and are async-signal-safe. unsafe { if source == target { diff --git a/crates/claude-connector/src/quota.rs b/crates/claude-connector/src/quota.rs index fe71383..3af2d7a 100644 --- a/crates/claude-connector/src/quota.rs +++ b/crates/claude-connector/src/quota.rs @@ -25,9 +25,8 @@ const FIRST_READ_POLL: Duration = Duration::from_millis(50); /// own observation: an event that names one window says nothing about the /// others. /// -/// It also keeps who is asking: a lease request is the swarm's only sign of -/// life the connector sees, and the meter reads the plan only while someone -/// asks. +/// It also keeps who is asking: a lease request is the connector's sign that a +/// holder is active, and the meter reads the plan only while someone asks. #[derive(Default)] pub struct QuotaCell { windows: Mutex>, @@ -155,7 +154,7 @@ impl QuotaCell { /// The windows as of `now`. One whose reset time has passed is reported /// `expired` with no utilization: the reading described a window that no /// longer exists. - fn snapshot_at(&self, now: u64) -> PlanQuotaSnapshot { + pub(crate) fn snapshot_at(&self, now: u64) -> PlanQuotaSnapshot { let held = self.windows.lock().unwrap_or_else(|e| e.into_inner()); PlanQuotaSnapshot { windows: held diff --git a/crates/claude-connector/src/router.rs b/crates/claude-connector/src/router.rs new file mode 100644 index 0000000..0af8f61 --- /dev/null +++ b/crates/claude-connector/src/router.rs @@ -0,0 +1,764 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use model_connector::{ + FailureKind, PlanQuotaSnapshot, ProviderBackend, ProviderCall, TransportOutcome, + TransportResult, +}; + +use crate::backend::ClaudeCodeBackend; +#[cfg(unix)] +use crate::backend::StderrSink; +use crate::config::ModelRow; +#[cfg(unix)] +use crate::config::ProviderWire; +use crate::daemon::ConfigError; +#[cfg(unix)] +use crate::daemon::{ + ClaudeConnectorConfig, backend_config_for, messages_config_for, openai_chat_config_for, +}; +use crate::messages::MessagesBackend; +use crate::openai_chat::OpenAiChatBackend; + +enum RouteBackend { + Messages(MessagesBackend), + OpenAiChat(OpenAiChatBackend), + Cli(Arc), +} + +/// The connector's sole [`ProviderBackend`]: dispatches each call by +/// [`ModelRow`], rewrites `wire_request.model` to `row.upstream` on the wire, +/// and leaves caller-facing `model` and `entry.id` on receipts. +pub struct RouterBackend { + providers: BTreeMap, + models: BTreeMap, + cli: Option>, +} + +impl RouterBackend { + #[cfg(unix)] + pub(crate) fn from_config( + config: &ClaudeConnectorConfig, + cli_sink: Box, + ) -> Result { + config.validate()?; + let mut cli_sink = Some(cli_sink); + let mut messages = Vec::new(); + let mut openai_chats = Vec::new(); + let mut cli = None; + for entry in &config.providers { + match &entry.wire { + ProviderWire::AnthropicMessages { .. } => { + let cfg = + messages_config_for(entry).ok_or(ConfigError::Unusable("providers"))?; + let backend = MessagesBackend::new(cfg); + if backend.provider_id() != entry.id { + return Err(ConfigError::Invalid("providers")); + } + messages.push(backend); + } + ProviderWire::ClaudeCodeCli { .. } => { + let sink = cli_sink.take().ok_or(ConfigError::Invalid("providers"))?; + let cfg = backend_config_for(entry, &config.models) + .ok_or(ConfigError::Unusable("providers"))?; + let backend = Arc::new(ClaudeCodeBackend::new(cfg, sink)); + if backend.provider_id() != entry.id { + return Err(ConfigError::Invalid("providers")); + } + cli = Some(backend); + } + ProviderWire::OpenAiChat { .. } => { + let cfg = + openai_chat_config_for(entry).ok_or(ConfigError::Unusable("providers"))?; + let backend = OpenAiChatBackend::new(cfg); + if backend.provider_id() != entry.id { + return Err(ConfigError::Invalid("providers")); + } + openai_chats.push(backend); + } + } + } + Self::from_backends(messages, openai_chats, cli, config.models.clone()) + } + + pub fn from_backends( + messages: impl IntoIterator, + openai_chats: impl IntoIterator, + cli: Option>, + models: Vec, + ) -> Result { + let mut providers = BTreeMap::new(); + for backend in messages { + let id = backend.provider_id(); + if id.is_empty() + || id.trim() != id + || providers + .insert(id.to_string(), RouteBackend::Messages(backend)) + .is_some() + { + return Err(ConfigError::Invalid("providers")); + } + } + for backend in openai_chats { + let id = backend.provider_id(); + if id.is_empty() + || id.trim() != id + || providers + .insert(id.to_string(), RouteBackend::OpenAiChat(backend)) + .is_some() + { + return Err(ConfigError::Invalid("providers")); + } + } + if let Some(cli_backend) = &cli { + let id = cli_backend.provider_id(); + if id.is_empty() + || id.trim() != id + || providers + .insert(id.to_string(), RouteBackend::Cli(cli_backend.clone())) + .is_some() + { + return Err(ConfigError::Invalid("providers")); + } + } + if models.is_empty() { + return Err(ConfigError::Invalid("models")); + } + let mut model_map = BTreeMap::new(); + for row in models { + if !providers.contains_key(&row.provider) { + return Err(ConfigError::Invalid("model_provider")); + } + if model_map.insert(row.id.clone(), row).is_some() { + return Err(ConfigError::Invalid("models")); + } + } + Ok(Self { + providers, + models: model_map, + cli, + }) + } + + pub fn cli_backend(&self) -> Option<&Arc> { + self.cli.as_ref() + } +} + +impl ProviderBackend for RouterBackend { + fn ready(&self) -> Result<(), &'static str> { + for backend in self.providers.values() { + match backend { + RouteBackend::Messages(messages) => messages.ready()?, + RouteBackend::OpenAiChat(openai) => openai.ready()?, + RouteBackend::Cli(cli) => cli.ready()?, + } + } + Ok(()) + } + + fn plan_quota(&self) -> Option<(&str, PlanQuotaSnapshot)> { + self.cli.as_deref().map(ClaudeCodeBackend::plan_quota) + } + + fn execute(&self, call: &ProviderCall) -> TransportResult { + let caller_request = call.request(); + let Some(row) = self.models.get(&caller_request.model) else { + return call.transported( + Vec::new(), + TransportOutcome::Failed { + kind: FailureKind::InvalidRequest, + message: "router: unknown model".to_string(), + usage: None, + }, + ); + }; + let Some(backend) = self.providers.get(&row.provider) else { + return call.transported( + Vec::new(), + TransportOutcome::Failed { + kind: FailureKind::Provider, + message: "router: missing provider".to_string(), + usage: None, + }, + ); + }; + let mut wire_request = caller_request.clone(); + wire_request.model = row.upstream.clone(); + let (events, outcome) = match backend { + RouteBackend::Messages(messages) => messages.run_model(&wire_request, row), + RouteBackend::OpenAiChat(openai) => openai.run_model(&wire_request, row), + RouteBackend::Cli(cli) => cli.run_model(&wire_request, call.caller_runtime_id(), row), + }; + call.transported(events, outcome) + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use model_connector::{ + CallerAdmission, ProviderBackend, ProviderRequest, ProviderRoutes, TransportAdmission, + TransportDisposition, TransportInvocation, TransportKey, TransportService, decrypt_result, + encrypt_invocation, + }; + use zeroize::Zeroizing; + + use super::*; + use crate::config::{EffortMap, ForcedToolChoice, OutputSchemaSupport}; + use crate::credential::TokenSource; + use crate::messages::MessagesConfig; + use crate::openai_chat::OpenAiChatConfig; + + struct FixedKey(&'static str); + impl TokenSource for FixedKey { + fn read(&self) -> Option> { + Some(Zeroizing::new(self.0.to_string())) + } + } + + struct MissingKey; + impl TokenSource for MissingKey { + fn read(&self) -> Option> { + None + } + } + + fn msg_backend(id: &str, url: &str, key: Option>) -> MessagesBackend { + MessagesBackend::with_parts( + MessagesConfig { + provider_id: id.to_string(), + base_url: url.to_string(), + key_credential: key.as_ref().map(|_| format!("{id}-cred")), + deadline: Duration::from_secs(5), + max_response_bytes: 1 << 20, + }, + key, + ) + } + + fn oai_backend(id: &str, url: &str, key: Option>) -> OpenAiChatBackend { + OpenAiChatBackend::with_parts( + OpenAiChatConfig { + provider_id: id.to_string(), + base_url: url.to_string(), + key_credential: key.as_ref().map(|_| format!("{id}-cred")), + strict_unsupported: Vec::new(), + deadline: Duration::from_secs(5), + max_response_bytes: 1 << 20, + }, + key, + ) + } + + fn row(id: &str, provider: &str, upstream: &str) -> ModelRow { + ModelRow { + id: id.to_string(), + provider: provider.to_string(), + upstream: upstream.to_string(), + efforts: EffortMap::default(), + unset_effort: None, + forced_tool_choice: ForcedToolChoice::Never, + output_schema: OutputSchemaSupport::Native, + strict_tools: false, + } + } + + #[test] + fn from_backends_validates_providers_models_and_readiness() { + let ok = msg_backend("entry-a", "http://127.0.0.1:9", None); + assert!(matches!( + RouterBackend::from_backends([ok], [], None, vec![]), + Err(ConfigError::Invalid("models")) + )); + + let dup_a = msg_backend("entry-a", "http://127.0.0.1:9", None); + let dup_b = msg_backend("entry-a", "http://127.0.0.1:10", None); + assert!(matches!( + RouterBackend::from_backends( + [dup_a, dup_b], + [], + None, + vec![row("m1", "entry-a", "u1")] + ), + Err(ConfigError::Invalid("providers")) + )); + + let untrimmed_msg = msg_backend(" entry-a", "http://127.0.0.1:9", None); + assert!(matches!( + RouterBackend::from_backends( + [untrimmed_msg], + [], + None, + vec![row("m1", "entry-a", "u1")] + ), + Err(ConfigError::Invalid("providers")) + )); + + let untrimmed_oai = oai_backend("entry-oai ", "http://127.0.0.1:9", None); + assert!(matches!( + RouterBackend::from_backends( + [], + [untrimmed_oai], + None, + vec![row("m1", "entry-oai", "u1")] + ), + Err(ConfigError::Invalid("providers")) + )); + + let dup_cross_msg = msg_backend("shared-id", "http://127.0.0.1:9", None); + let dup_cross_oai = oai_backend("shared-id", "http://127.0.0.1:10", None); + assert!(matches!( + RouterBackend::from_backends( + [dup_cross_msg], + [dup_cross_oai], + None, + vec![row("m1", "shared-id", "u1")] + ), + Err(ConfigError::Invalid("providers")) + )); + + let ok = msg_backend("entry-a", "http://127.0.0.1:9", None); + assert!(matches!( + RouterBackend::from_backends([ok], [], None, vec![row("m1", "unknown-entry", "u1")]), + Err(ConfigError::Invalid("model_provider")) + )); + + let ok = msg_backend("entry-a", "http://127.0.0.1:9", None); + assert!(matches!( + RouterBackend::from_backends( + [ok], + [], + None, + vec![row("m1", "entry-a", "u1"), row("m1", "entry-a", "u2")] + ), + Err(ConfigError::Invalid("models")) + )); + + let failing = msg_backend( + "entry-b", + "https://example.test", + Some(Box::new(MissingKey)), + ); + let ready = msg_backend( + "entry-a", + "https://example.test", + Some(Box::new(FixedKey("k"))), + ); + let oai_ready = oai_backend( + "entry-oai", + "https://oai.example.test/v1", + Some(Box::new(FixedKey("k2"))), + ); + let router = RouterBackend::from_backends( + [ready, failing], + [oai_ready], + None, + vec![ + row("m1", "entry-a", "u1"), + row("m2", "entry-b", "u2"), + row("m3", "entry-oai", "u3"), + ], + ) + .unwrap(); + assert_eq!(router.ready(), Err("token_credential")); + assert!(router.plan_quota().is_none()); + assert!(router.cli_backend().is_none()); + + let oai_failing = oai_backend( + "entry-oai-missing", + "https://oai.example.test/v1", + Some(Box::new(MissingKey)), + ); + let oai_router = RouterBackend::from_backends( + [], + [oai_failing], + None, + vec![row("m1", "entry-oai-missing", "u1")], + ) + .unwrap(); + assert_eq!(oai_router.ready(), Err("token_credential")); + } + + #[test] + fn execute_rewrites_upstream_and_keeps_caller_model_and_entry_id_on_receipt() { + use std::io::{Read, Write}; + use std::net::TcpListener; + use std::sync::Mutex; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let seen_body = Arc::new(Mutex::new(None::)); + let seen_clone = seen_body.clone(); + std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + let mut header_end = None; + let mut content_len = 0usize; + loop { + let n = stream.read(&mut chunk).unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + if header_end.is_none() + && let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") + { + let end = pos + 4; + header_end = Some(end); + let headers = String::from_utf8_lossy(&buf[..pos]); + for line in headers.lines().skip(1) { + if let Some((k, v)) = line.split_once(':') + && k.eq_ignore_ascii_case("content-length") + { + content_len = v.trim().parse().unwrap_or(0); + } + } + } + if let Some(end) = header_end + && buf.len() >= end + content_len + { + break; + } + } + let end = header_end.unwrap_or(buf.len()); + *seen_clone.lock().unwrap() = + Some(serde_json::from_slice(&buf[end..end + content_len]).unwrap()); + let resp = serde_json::json!({ + "id": "msg_router_1", + "content": [{"type": "text", "text": "ok"}], + "stop_reason": "end_turn", + "usage": {"input_tokens": 2, "output_tokens": 1} + }) + .to_string(); + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}", + resp.len(), + resp + ) + .unwrap(); + }); + + let backend = msg_backend( + "custom-entry", + &format!("http://{addr}"), + Some(Box::new(FixedKey("secret-k"))), + ); + let router = RouterBackend::from_backends( + [backend], + [], + None, + vec![row("caller-alias", "custom-entry", "wire-upstream-name")], + ) + .unwrap(); + + let dir = std::env::temp_dir().join(format!("router-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let admission = CallerAdmission::new( + "caller-1", + "caller-1-secret-0123456789abcdef0123456789", + 1, + ["caller-alias".to_string()], + 2, + 1 << 20, + 4_096, + ) + .unwrap(); + let routes = + ProviderRoutes::new([("caller-alias".to_string(), "custom-entry".to_string())]) + .unwrap(); + let mut service = + TransportService::open(&dir.join("replay.cc"), routes, [admission], 5_000).unwrap(); + let key = + TransportKey::from_connection_secret("caller-1-secret-0123456789abcdef0123456789") + .unwrap(); + let mut req = ProviderRequest::new("r1", "c1", "caller-alias", "Be brief.", 128); + req.input = vec![model_connector::InputItem::UserText { + text: "hi".to_string(), + }]; + let inv = TransportInvocation::new("caller-1", 2_000, [9; 32], req).unwrap(); + let env = encrypt_invocation(&inv, &key).unwrap(); + let TransportAdmission::Execute(claim) = service.begin(&env, 1_000, None, 1 << 20).unwrap() + else { + panic!("expected execute"); + }; + let result = router.execute(claim.call()); + let sealed = service.complete(*claim, result, 1 << 20).unwrap(); + let opened = decrypt_result(&sealed, &key, &inv).unwrap(); + let TransportDisposition::Transported { receipt, .. } = opened.disposition else { + panic!("expected transported"); + }; + assert_eq!(receipt.provider, "custom-entry"); + assert_eq!(receipt.model, "caller-alias"); + assert_eq!( + seen_body.lock().unwrap().as_ref().unwrap()["model"], + "wire-upstream-name" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + #[test] + fn from_config_accepts_and_routes_openai_chat_through_service() { + use std::io::{Read, Write}; + use std::net::TcpListener; + use std::sync::Mutex; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let seen = Arc::new(Mutex::new(Vec::<(String, serde_json::Value)>::new())); + let seen_clone = seen.clone(); + let responses = vec![ + serde_json::json!({ + "id": "oai_resp_1", + "choices": [{ + "index": 0, + "message": { + "role": "assistant", + "content": null, + "reasoning_content": "thought line", + "tool_calls": [{ + "id": "call_r1", + "type": "function", + "function": {"name": "ping", "arguments": "{\"x\":1}"}, + "extra_content": {"google": {"thought_signature": "sig-router"}} + }] + }, + "finish_reason": "tool_calls" + }], + "usage": {"prompt_tokens": 10, "completion_tokens": 5} + }), + serde_json::json!({ + "id": "oai_resp_2", + "choices": [{ + "index": 0, + "message": {"role": "assistant", "content": "done"}, + "finish_reason": "stop" + }], + "usage": {"prompt_tokens": 20, "completion_tokens": 3} + }), + ]; + std::thread::spawn(move || { + for resp in responses { + let (mut stream, _) = listener.accept().unwrap(); + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + let mut header_end = None; + let mut content_len = 0usize; + loop { + let n = stream.read(&mut chunk).unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + if header_end.is_none() + && let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") + { + let end = pos + 4; + header_end = Some(end); + let headers = String::from_utf8_lossy(&buf[..pos]); + for line in headers.lines().skip(1) { + if let Some((k, v)) = line.split_once(':') + && k.eq_ignore_ascii_case("content-length") + { + content_len = v.trim().parse().unwrap_or(0); + } + } + } + if let Some(end) = header_end + && buf.len() >= end + content_len + { + break; + } + } + let end = header_end.unwrap_or(buf.len()); + let path = String::from_utf8_lossy(&buf[..end]) + .lines() + .next() + .and_then(|l| l.split_whitespace().nth(1)) + .unwrap_or("") + .to_string(); + let body: serde_json::Value = + serde_json::from_slice(&buf[end..end + content_len]).unwrap(); + seen_clone.lock().unwrap().push((path, body)); + let payload = resp.to_string(); + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}", + payload.len(), + payload + ) + .unwrap(); + } + }); + + let dir = std::env::temp_dir().join(format!("router-oai-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let caller_key_file = dir.join("c1.key"); + let caller_secret = "caller-1-secret-0123456789abcdef0123456789"; + std::fs::write(&caller_key_file, caller_secret).unwrap(); + + let cfg = ClaudeConnectorConfig { + listen: "127.0.0.1:4110".to_string(), + replay_store: dir.join("replay.cc"), + max_frame_bytes: 2 << 20, + max_connections: 8, + socket_timeout_ms: 10_000, + max_expiry_skew_ms: 300_000, + providers: vec![crate::ProviderEntry { + id: "oai-entry".to_string(), + credential: None, + wire: ProviderWire::OpenAiChat { + base_url: format!("http://{addr}/v1"), + strict_unsupported: vec![], + deadline_ms: 10_000, + max_response_bytes: 1 << 20, + }, + }], + models: vec![row("ds-flash", "oai-entry", "deepseek-chat")], + callers: vec![model_connector::CallerConfig { + caller_runtime_id: "c1".to_string(), + connection_key_file: caller_key_file, + connection_key_epoch: 1, + allowed_models: vec!["ds-flash".to_string()], + max_concurrent_requests: 2, + max_payload_bytes: 1 << 20, + max_output_tokens: 4_096, + }], + lease_socket: None, + lease_holders: vec![], + lease_max_ms: 60_000, + }; + let router = RouterBackend::from_config(&cfg, Box::new(NoSink)).unwrap(); + + let admission = CallerAdmission::new( + "c1", + caller_secret, + 1, + ["ds-flash".to_string()], + 2, + 1 << 20, + 4_096, + ) + .unwrap(); + let routes = + ProviderRoutes::new([("ds-flash".to_string(), "oai-entry".to_string())]).unwrap(); + let mut service = + TransportService::open(&cfg.replay_store, routes, [admission], 5_000).unwrap(); + let key = TransportKey::from_connection_secret(caller_secret).unwrap(); + + let mut req1 = ProviderRequest::new("r1", "c1", "ds-flash", "Be brief.", 128); + req1.input = vec![model_connector::InputItem::UserText { + text: "ping".to_string(), + }]; + req1.tools = vec![model_connector::ToolDefinition { + name: "ping".to_string(), + description: "ping".to_string(), + parameters_json: r#"{"type":"object","properties":{"x":{"type":"integer"}}}"# + .to_string(), + }]; + let inv1 = TransportInvocation::new("c1", 2_000, [1; 32], req1.clone()).unwrap(); + let env1 = encrypt_invocation(&inv1, &key).unwrap(); + let TransportAdmission::Execute(claim1) = + service.begin(&env1, 1_000, None, 1 << 20).unwrap() + else { + panic!("expected execute"); + }; + let res1 = router.execute(claim1.call()); + let sealed1 = service.complete(*claim1, res1, 1 << 20).unwrap(); + let opened1 = decrypt_result(&sealed1, &key, &inv1).unwrap(); + let TransportDisposition::Transported { + receipt: ref receipt1, + .. + } = opened1.disposition + else { + panic!("expected transported"); + }; + assert_eq!(receipt1.provider, "oai-entry"); + assert_eq!(receipt1.model, "ds-flash"); + + let mut req2 = req1; + req2.request_id = "r2".to_string(); + req2.input.extend(opened1.transcript_items()); + req2.input.push(model_connector::InputItem::ToolResult { + call_id: "call_r1".to_string(), + output: "pong".to_string(), + }); + let inv2 = TransportInvocation::new("c1", 2_000, [2; 32], req2).unwrap(); + let env2 = encrypt_invocation(&inv2, &key).unwrap(); + let TransportAdmission::Execute(claim2) = + service.begin(&env2, 1_000, None, 1 << 20).unwrap() + else { + panic!("expected execute"); + }; + let res2 = router.execute(claim2.call()); + let sealed2 = service.complete(*claim2, res2, 1 << 20).unwrap(); + let opened2 = decrypt_result(&sealed2, &key, &inv2).unwrap(); + assert!(matches!( + opened2.disposition, + TransportDisposition::Transported { .. } + )); + + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 2); + assert_eq!(seen[0].0, "/v1/chat/completions"); + assert_eq!(seen[0].1["model"], "deepseek-chat"); + assert_eq!(seen[1].1["model"], "deepseek-chat"); + assert_eq!( + seen[1].1["messages"][2]["reasoning_content"], + "thought line" + ); + assert_eq!( + seen[1].1["messages"][2]["tool_calls"][0]["extra_content"], + serde_json::json!({"google": {"thought_signature": "sig-router"}}) + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + #[test] + fn from_backends_rejects_untrimmed_cli_provider_id() { + let cli = ClaudeCodeBackend::new( + crate::config::ClaudeCodeConfig { + provider_id: " cli-space".to_string(), + claude_binary: std::path::PathBuf::from("/usr/bin/false"), + claude_binary_sha256: [0xaa; 32], + work_dir: std::path::PathBuf::from("/tmp"), + config_dir: std::path::PathBuf::from("/tmp"), + prompt_dir: std::path::PathBuf::from("/tmp"), + token_credential: "tok".to_string(), + handle_secret_credential: "sec".to_string(), + instance: "inst".to_string(), + meter_model: None, + limits: crate::config::ClaudeCodeLimits { + deadline: Duration::from_secs(5), + max_line_bytes: 1024, + max_total_bytes: 4096, + stderr_tail_bytes: 256, + }, + }, + Box::new(NoSink), + ); + assert!(matches!( + RouterBackend::from_backends( + [], + [], + Some(Arc::new(cli)), + vec![row("m1", "cli-space", "u1")] + ), + Err(ConfigError::Invalid("providers")) + )); + } + + #[cfg(unix)] + struct NoSink; + #[cfg(unix)] + impl StderrSink for NoSink { + fn stderr_tail(&self, _: &[u8]) {} + } +} diff --git a/crates/claude-connector/src/stream.rs b/crates/claude-connector/src/stream.rs index 039ff75..333c865 100644 --- a/crates/claude-connector/src/stream.rs +++ b/crates/claude-connector/src/stream.rs @@ -121,7 +121,7 @@ pub(crate) struct StreamState<'a> { /// Whether that schema's top type admits an object (absent counts): the /// structured output must be an object, never a bare scalar or array. schema_top_is_object: bool, - quota: &'a QuotaCell, + quota: Option<&'a QuotaCell>, session_id: Option, texts: Vec, message_id: Option, @@ -130,7 +130,7 @@ pub(crate) struct StreamState<'a> { impl<'a> StreamState<'a> { /// `schema` is the request's output schema text, when it carried one. - pub(crate) fn new(model: &'a str, schema: Option<&str>, quota: &'a QuotaCell) -> Self { + pub(crate) fn new(model: &'a str, schema: Option<&str>, quota: Option<&'a QuotaCell>) -> Self { let top = schema .and_then(|text| serde_json::from_str::(text).ok()) .and_then(|schema| schema.get("type").cloned()); @@ -176,7 +176,9 @@ impl<'a> StreamState<'a> { if let Some(info) = &line.rate_limit_info { self.plan_rejected |= info.get("status").and_then(Value::as_str) == Some("rejected"); - self.quota.observe(plan_windows(info)); + if let Some(quota) = self.quota { + quota.observe(plan_windows(info)); + } } Step::More } diff --git a/crates/claude-connector/src/unit.rs b/crates/claude-connector/src/unit.rs index 1ab8dc9..f435064 100644 --- a/crates/claude-connector/src/unit.rs +++ b/crates/claude-connector/src/unit.rs @@ -141,17 +141,16 @@ mod tests { #[test] fn a_service_unit_is_the_last_cgroup_component() { - let service = "0::/system.slice/system-mind\\x2dself.slice/mind-self@huginn.service\n"; + let service = "0::/system.slice/system-agent\\x2dpool.slice/agent@alice.service\n"; assert_eq!( unit_of_cgroup(service).as_deref(), - Some("mind-self@huginn.service") + Some("agent@alice.service") ); // Several hierarchies listed: the unified one decides. - let hybrid = "12:cpu:/foo\n0::/system.slice/mind-self@a.service\n"; - assert_eq!( - unit_of_cgroup(hybrid).as_deref(), - Some("mind-self@a.service") - ); + let hybrid = "12:cpu:/foo\n0::/system.slice/agent@a.service\n"; + assert_eq!(unit_of_cgroup(hybrid).as_deref(), Some("agent@a.service")); + let plain = "0::/system.slice/other.service\n"; + assert_eq!(unit_of_cgroup(plain).as_deref(), Some("other.service")); } #[test] @@ -160,7 +159,7 @@ mod tests { "0::/\n", "0::/user.slice/user-1000.slice/session-3.scope\n", "0::/user.slice/user-1000.slice/user@1000.service/app.slice/x.service/child\n", - "0::/system.slice/mind-self@huginn.service/sub\n", + "0::/system.slice/agent@alice.service/sub\n", "0::/system.slice/.service\n", "1:name=systemd:/system.slice/a.service\n", "", @@ -188,7 +187,7 @@ mod tests { } const ID: &str = "0123456789abcdef0123456789abcdef"; - const UNIT: &str = "mind-self@eureka.service"; + const UNIT: &str = "worker@node.service"; /// A fake `/proc` with one process in `cgroup`, and a fake `systemctl` /// that records its arguments, runs `side_effect`, and exits `status` diff --git a/crates/claude-connector/tests/ask.rs b/crates/claude-connector/tests/ask.rs new file mode 100644 index 0000000..87ae67c --- /dev/null +++ b/crates/claude-connector/tests/ask.rs @@ -0,0 +1,796 @@ +//! `claude-connector ask` against a real serve loop on loopback with a scripted +//! backend: the consumer side of the no-tools completion. + +use std::net::{SocketAddr, TcpListener}; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use claude_connector::ask::{AskArgs, AskError, ask, build_invocation}; +use model_connector::*; + +const CALLER: &str = "ask-caller"; +const KEY: &str = "ask-test-key-0123456789-abcdefghijklmnop"; +const MODEL: &str = "claude-haiku-5-5"; +const FRAME: usize = 4 << 20; + +/// What the scripted backend does with each call. +#[derive(Clone)] +enum Script { + Text(&'static str), + Empty, + Failed(&'static str), + Sleep(Duration), + ToolCall, + Stop(StopReason), +} + +struct Backend { + script: Script, + seen: Mutex>, +} + +impl ProviderBackend for Backend { + fn ready(&self) -> Result<(), &'static str> { + Ok(()) + } + fn execute(&self, call: &ProviderCall) -> TransportResult { + self.seen.lock().unwrap().push(call.request().clone()); + let usage = Usage { + input_tokens: 1, + cache_read_tokens: 0, + cache_write_tokens: 0, + output_tokens: 1, + reasoning_tokens: None, + }; + let text = |t: &str| { + vec![TransportEvent { + sequence: 0, + payload: TransportEventPayload::TextDelta { text: t.into() }, + }] + }; + let stop = match &self.script { + Script::Stop(reason) => *reason, + _ => StopReason::EndTurn, + }; + let completed = TransportOutcome::Completed { + provider_response_id: None, + stop_reason: stop, + usage: usage.clone(), + }; + match &self.script { + Script::Text(t) => call.transported(text(t), completed), + Script::Empty => call.transported(Vec::new(), completed), + Script::Failed(message) => call.transported( + Vec::new(), + TransportOutcome::Failed { + kind: FailureKind::Provider, + message: message.to_string(), + usage: None, + }, + ), + Script::Stop(_) => call.transported(text("cut off"), completed), + Script::ToolCall => call.transported( + vec![TransportEvent { + sequence: 0, + payload: TransportEventPayload::ToolCall { + call_id: "c".into(), + name: "n".into(), + arguments: "{}".into(), + }, + }], + completed, + ), + Script::Sleep(d) => { + thread::sleep(*d); + call.transported(text("late"), completed) + } + } + } +} + +fn write_key(path: &std::path::Path, bytes: &[u8], mode: u32) { + use std::os::unix::fs::PermissionsExt; + std::fs::write(path, bytes).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap(); +} + +struct Rig { + endpoint: SocketAddr, + dir: PathBuf, + key_file: PathBuf, + backend: Arc, +} + +fn rig(script: Script) -> Rig { + static SEQ: AtomicUsize = AtomicUsize::new(0); + let dir = std::env::temp_dir().join(format!( + "claude-connector-ask-{}-{}", + std::process::id(), + SEQ.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).unwrap(); + let key_file = dir.join("caller.key"); + write_key(&key_file, format!("{KEY}\n").as_bytes(), 0o600); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let endpoint = listener.local_addr().unwrap(); + let admission = + CallerAdmission::new(CALLER, KEY, 1, [MODEL.to_string()], 4, 1 << 20, 4_096).unwrap(); + let limits = ServeLimits { + max_frame_bytes: FRAME, + max_connections: 8, + socket_timeout_ms: 5_000, + max_expiry_skew_ms: 300_000, + }; + let backend = Arc::new(Backend { + script, + seen: Mutex::new(Vec::new()), + }); + let served = backend.clone(); + let store = dir.join("replay.cc"); + let routes = ProviderRoutes::new([(MODEL.to_string(), "claude-code".to_string())]).unwrap(); + thread::spawn(move || serve(listener, limits, vec![admission], &store, routes, served)); + Rig { + endpoint, + dir, + key_file, + backend, + } +} + +impl Rig { + fn args(&self) -> AskArgs { + AskArgs { + endpoint: self.endpoint, + caller_id: CALLER.into(), + key_file: self.key_file.clone(), + model: MODEL.into(), + instructions: "Answer briefly.".into(), + effort: Some(ReasoningEffort::Low), + max_output_tokens: 1_024, + timeout: Duration::from_secs(5), + prompt: "SECRET-PROMPT-TEXT".into(), + } + } + fn seen(&self) -> Vec { + self.backend.seen.lock().unwrap().clone() + } +} + +fn message(error: &AskError) -> String { + error.to_string() +} + +#[test] +fn success_returns_the_answer_text_and_the_backend_saw_a_toolless_request() { + let rig = rig(Script::Text("four")); + assert_eq!(ask(&rig.args()).unwrap(), "four"); + let seen = rig.seen(); + assert_eq!(seen.len(), 1); + assert!(seen[0].tools.is_empty()); + assert_eq!(seen[0].model, MODEL); + assert_eq!(seen[0].instructions, "Answer briefly."); + assert_eq!(seen[0].reasoning_effort, Some(ReasoningEffort::Low)); + assert_eq!(seen[0].max_output_tokens, 1_024); + assert_eq!( + seen[0].input, + vec![InputItem::UserText { + text: "SECRET-PROMPT-TEXT".into() + }] + ); +} + +#[test] +fn each_run_uses_a_fresh_request_id_so_replay_never_answers_a_new_question() { + let rig = rig(Script::Text("again")); + ask(&rig.args()).unwrap(); + ask(&rig.args()).unwrap(); + let seen = rig.seen(); + assert_eq!(seen.len(), 2, "the provider ran once per run"); + assert_ne!(seen[0].request_id, seen[1].request_id); +} + +#[test] +fn the_cli_cannot_construct_a_request_with_tools() { + let rig = rig(Script::Text("x")); + let invocation = build_invocation(&rig.args()).unwrap(); + assert!(invocation.request.tools.is_empty()); + assert_eq!(invocation.request.tool_choice, ToolChoice::Auto); + assert!( + invocation + .request + .input + .iter() + .all(|item| matches!(item, InputItem::UserText { .. })) + ); +} + +#[test] +fn a_model_outside_allowed_models_is_refused_loudly() { + let rig = rig(Script::Text("x")); + let mut args = rig.args(); + args.model = "claude-opus-5".into(); + let error = ask(&args).unwrap_err(); + assert!( + matches!(error, AskError::Refused(Refusal::ModelNotAllowed)), + "{error}" + ); + assert!(rig.seen().is_empty()); +} + +#[test] +fn an_output_bound_over_the_callers_cap_is_refused() { + let rig = rig(Script::Text("x")); + let mut args = rig.args(); + args.max_output_tokens = 4_097; + assert!(matches!( + ask(&args).unwrap_err(), + AskError::Refused(Refusal::OutputBound) + )); + assert!(rig.seen().is_empty()); +} + +#[test] +fn a_wrong_key_or_caller_is_an_error_and_never_reaches_the_provider() { + let rig = rig(Script::Text("x")); + let mut wrong_key = rig.args(); + let other = rig.dir.join("other.key"); + write_key(&other, b"some-other-connection-key-0123456789", 0o600); + wrong_key.key_file = other; + let error = ask(&wrong_key).unwrap_err(); + assert!(!message(&error).contains("some-other"), "{error}"); + let mut wrong_caller = rig.args(); + wrong_caller.caller_id = "someone-else".into(); + ask(&wrong_caller).unwrap_err(); + assert!(rig.seen().is_empty()); +} + +#[test] +fn an_unusable_key_file_errors_without_echoing_its_contents() { + let rig = rig(Script::Text("x")); + let cases: Vec<(&str, Vec)> = vec![ + ("empty", b"\n".to_vec()), + ("long", vec![b'k'; 2_000]), + ("binary", vec![0xff, 0xfe, 0xfd, 0x41]), + ("padded", b" spaced-secret-value-padded ".to_vec()), + ]; + for (name, bytes) in cases { + let path = rig.dir.join(format!("{name}.key")); + write_key(&path, &bytes, 0o600); + let mut args = rig.args(); + args.key_file = path; + let text = message(&ask(&args).unwrap_err()); + assert!(!text.contains("spaced-secret"), "{name}: {text}"); + assert!(!text.contains("kkkk"), "{name}: {text}"); + } + let mut missing = rig.args(); + missing.key_file = rig.dir.join("absent.key"); + assert!(matches!( + ask(&missing).unwrap_err(), + AskError::KeyUnreadable + )); + let mut directory = rig.args(); + directory.key_file = rig.dir.clone(); + assert!(matches!( + ask(&directory).unwrap_err(), + AskError::KeyNotRegular + )); + assert!(rig.seen().is_empty()); +} + +#[test] +fn an_empty_answer_is_an_error() { + for script in [Script::Empty, Script::Text(" \n")] { + let rig = rig(script); + assert!(matches!( + ask(&rig.args()).unwrap_err(), + AskError::EmptyAnswer + )); + } +} + +#[test] +fn an_empty_prompt_is_an_error_before_any_connection() { + let rig = rig(Script::Text("x")); + let mut args = rig.args(); + args.prompt = " \n\t".into(); + assert!(matches!(ask(&args).unwrap_err(), AskError::EmptyPrompt)); + assert!(rig.seen().is_empty()); +} + +#[test] +fn a_provider_failure_names_its_kind_and_not_its_message() { + let rig = rig(Script::Failed("stderr tail with SECRET-PROMPT-TEXT")); + let error = ask(&rig.args()).unwrap_err(); + assert!(matches!(error, AskError::Failed(FailureKind::Provider))); + assert!(!message(&error).contains("SECRET")); +} + +#[test] +fn a_connector_that_does_not_answer_in_time_is_a_timeout() { + let rig = rig(Script::Sleep(Duration::from_secs(3))); + let mut args = rig.args(); + args.timeout = Duration::from_millis(300); + assert!(matches!(ask(&args).unwrap_err(), AskError::Timeout)); +} + +#[test] +fn a_dead_endpoint_is_a_connection_error() { + let rig = rig(Script::Text("x")); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let mut args = rig.args(); + args.endpoint = listener.local_addr().unwrap(); + drop(listener); + assert!(matches!(ask(&args).unwrap_err(), AskError::NotListening)); +} + +fn run_binary(rig: &Rig, stdin: &str, extra: &[&str]) -> std::process::Output { + run_binary_with_key(rig, &rig.key_file, stdin, extra) +} + +fn run_binary_with_key( + rig: &Rig, + key_file: &std::path::Path, + stdin: &str, + extra: &[&str], +) -> std::process::Output { + let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args(["ask", "--endpoint", &rig.endpoint.to_string()]) + .args([ + "--caller-id", + CALLER, + "--model", + MODEL, + "--system", + "Be brief.", + ]) + .args(["--connection-key-file", key_file.to_str().unwrap()]) + .args(extra) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + { + use std::io::Write; + let _ = child.stdin.take().unwrap().write_all(stdin.as_bytes()); + } + child.wait_with_output().unwrap() +} + +#[test] +fn a_toolcall_in_the_answer_is_an_error() { + let rig = rig(Script::ToolCall); + assert!(matches!(ask(&rig.args()).unwrap_err(), AskError::ToolCall)); +} + +/// The rule: only a turn that ended (end of turn or a stop sequence) is an +/// answer; a truncated, refused or context-limited turn is an error even when +/// it carries text. +#[test] +fn a_turn_that_did_not_end_is_an_error() { + for reason in [ + StopReason::MaxOutputTokens, + StopReason::Refusal, + StopReason::ContextWindow, + StopReason::ToolUse, + ] { + let rig = rig(Script::Stop(reason)); + assert!( + matches!(ask(&rig.args()).unwrap_err(), AskError::NotCompleted(r) if r == reason), + "{reason:?}" + ); + } + let rig = rig(Script::Stop(StopReason::StopSequence)); + assert_eq!(ask(&rig.args()).unwrap(), "cut off"); +} + +#[test] +fn a_fifo_key_file_errors_promptly_instead_of_hanging() { + let rig = rig(Script::Text("x")); + let fifo = rig.dir.join("fifo.key"); + let path = std::ffi::CString::new(fifo.to_str().unwrap()).unwrap(); + assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0); + let mut args = rig.args(); + args.key_file = fifo; + let (tx, rx) = std::sync::mpsc::channel(); + thread::spawn(move || tx.send(ask(&args)).unwrap()); + let error = rx + .recv_timeout(Duration::from_secs(3)) + .expect("reading a FIFO key file must not hang") + .unwrap_err(); + assert!(matches!(error, AskError::KeyNotRegular), "{error}"); +} + +#[test] +fn a_key_file_readable_by_group_or_world_is_refused_and_a_private_one_accepted() { + let rig = rig(Script::Text("fine")); + for mode in [0o644, 0o640, 0o604] { + let path = rig.dir.join(format!("mode-{mode:o}.key")); + write_key(&path, KEY.as_bytes(), mode); + let mut args = rig.args(); + args.key_file = path; + let error = ask(&args).unwrap_err(); + assert!(matches!(error, AskError::KeyExposed), "{mode:o}: {error}"); + assert!(!message(&error).contains(KEY)); + } + assert!(rig.seen().is_empty()); + assert_eq!(ask(&rig.args()).unwrap(), "fine"); +} + +#[test] +fn a_symlinked_key_is_judged_by_its_target() { + let rig = rig(Script::Text("linked")); + let link = rig.dir.join("link.key"); + std::os::unix::fs::symlink(&rig.key_file, &link).unwrap(); + let mut args = rig.args(); + args.key_file = link; + assert_eq!(ask(&args).unwrap(), "linked"); + let dir_link = rig.dir.join("dir.key"); + std::os::unix::fs::symlink(&rig.dir, &dir_link).unwrap(); + args.key_file = dir_link; + assert!(matches!(ask(&args).unwrap_err(), AskError::KeyNotRegular)); +} + +#[test] +fn the_key_read_is_bounded_at_1024_bytes() { + let rig = rig(Script::Text("x")); + let path = rig.dir.join("big.key"); + write_key(&path, &vec![b'k'; 1_025], 0o600); + assert!(matches!( + claude_connector::ask::read_key(&path).unwrap_err(), + AskError::KeyLength + )); + write_key(&path, &vec![b'k'; 1_024], 0o600); + assert!(claude_connector::ask::read_key(&path).is_ok()); +} + +#[test] +fn the_instructions_file_is_capped_and_must_be_a_regular_file() { + use claude_connector::ask::{MAX_SYSTEM_BYTES, read_system_file}; + let rig = rig(Script::Text("x")); + let path = rig.dir.join("system.txt"); + std::fs::write(&path, vec![b's'; MAX_SYSTEM_BYTES]).unwrap(); + assert_eq!(read_system_file(&path).unwrap().len(), MAX_SYSTEM_BYTES); + std::fs::write(&path, vec![b's'; MAX_SYSTEM_BYTES + 1]).unwrap(); + assert!(matches!( + read_system_file(&path).unwrap_err(), + AskError::SystemTooLarge + )); + assert!(matches!( + read_system_file(&rig.dir).unwrap_err(), + AskError::SystemUnreadable + )); +} + +#[test] +fn the_binary_never_prints_key_bytes_for_a_bad_key_file() { + let rig = rig(Script::Text("x")); + let cases: [(&str, &[u8], u32); 3] = [ + ("exposed", b"exposed-key-bytes-0123456789", 0o644), + ("padded", b" padded-key-bytes-0123456789 ", 0o600), + ("wrong", b"wrong-but-wellformed-key-0123456789", 0o600), + ]; + for (name, bytes, mode) in cases { + let path = rig.dir.join(format!("bin-{name}.key")); + write_key(&path, bytes, mode); + let out = run_binary_with_key(&rig, &path, "q", &[]); + assert!(!out.status.success(), "{name}"); + let shown = [out.stdout.clone(), out.stderr.clone()].concat(); + let shown = String::from_utf8_lossy(&shown); + assert!( + !shown.contains("key-bytes") && !shown.contains("wellformed"), + "{name}: {shown}" + ); + assert!(out.stdout.is_empty()); + } + let out = run_binary(&rig, "q", &["--system-file", "/nonexistent"]); + assert!(!out.status.success()); +} + +#[test] +fn stdin_and_stdout_failures_have_their_own_wording() { + let rig = rig(Script::Text("x")); + let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args(["ask", "--endpoint", &rig.endpoint.to_string()]) + .args(["--caller-id", CALLER, "--model", MODEL, "--system", "s"]) + .args(["--connection-key-file", rig.key_file.to_str().unwrap()]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + { + use std::io::Write; + child + .stdin + .take() + .unwrap() + .write_all(&[0xff, 0xfe]) + .unwrap(); + } + let out = child.wait_with_output().unwrap(); + let err = String::from_utf8(out.stderr).unwrap(); + assert!(err.contains("not UTF-8"), "{err}"); + assert!(!err.contains("flag"), "{err}"); +} + +/// What the wire returns for a tools-bearing request that gets past the CLI's +/// own construction (here forced by hand) when the real claude backend sits +/// behind the real serve loop: the service admits it, the backend's planner +/// refuses it, the caller receives a transported `Failed(InvalidRequest)` +/// result, and the claude child is never started. +#[test] +fn t_c0_oauth_still_cli_a_tools_request_is_refused_and_no_child_starts() { + use claude_connector::{ + ChildEnv, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, EffortMap, + ForcedToolChoice, ModelRow, OutputSchemaSupport, ProcessPort, RouterBackend, RunningChild, + SessionStore, StderrSink, TokenSource, + }; + use sha2::{Digest, Sha256}; + use zeroize::Zeroizing; + + struct CountingPort(Arc); + impl ProcessPort for CountingPort { + fn spawn( + &self, + _: &[String], + _: &ChildEnv, + _: &std::path::Path, + _: Vec, + _: &str, + ) -> std::io::Result> { + self.0.fetch_add(1, Ordering::SeqCst); + Err(std::io::Error::other("no child in this test")) + } + } + struct Fixed(&'static str); + impl TokenSource for Fixed { + fn read(&self) -> Option> { + Some(Zeroizing::new(self.0.to_string())) + } + } + struct NoSessions; + impl SessionStore for NoSessions { + fn exists(&self, _: &str) -> bool { + false + } + } + struct Quiet; + impl StderrSink for Quiet { + fn stderr_tail(&self, _: &[u8]) {} + } + + let dir = + std::env::temp_dir().join(format!("claude-connector-ask-tools-{}", std::process::id())); + for sub in ["work", "config", "prompt"] { + std::fs::create_dir_all(dir.join(sub)).unwrap(); + } + let binary = dir.join("claude"); + std::fs::write(&binary, b"pretend claude").unwrap(); + let spawns = Arc::new(AtomicUsize::new(0)); + let backend = ClaudeCodeBackend::with_ports( + ClaudeCodeConfig { + provider_id: "claude-code".into(), + claude_binary: binary, + claude_binary_sha256: Sha256::digest(b"pretend claude").into(), + work_dir: dir.join("work"), + config_dir: dir.join("config"), + prompt_dir: dir.join("prompt"), + token_credential: "t".into(), + handle_secret_credential: "h".into(), + instance: "i".into(), + meter_model: Some(MODEL.into()), + limits: ClaudeCodeLimits { + deadline: Duration::from_secs(5), + max_line_bytes: 1 << 16, + max_total_bytes: 1 << 20, + stderr_tail_bytes: 64, + }, + }, + Box::new(CountingPort(spawns.clone())), + Box::new(NoSessions), + Box::new(Quiet), + Box::new(Fixed("token")), + Box::new(Fixed( + "handle-secret-0000000000000000000000000000000000000000", + )), + ); + let router = RouterBackend::from_backends( + [], + [], + Some(Arc::new(backend)), + vec![ModelRow { + id: MODEL.into(), + provider: "claude-code".into(), + upstream: MODEL.into(), + efforts: EffortMap::default(), + unset_effort: None, + forced_tool_choice: ForcedToolChoice::Never, + output_schema: OutputSchemaSupport::Native, + strict_tools: false, + }], + ) + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let endpoint = listener.local_addr().unwrap(); + let admission = + CallerAdmission::new(CALLER, KEY, 1, [MODEL.to_string()], 4, 1 << 20, 4_096).unwrap(); + let limits = ServeLimits { + max_frame_bytes: FRAME, + max_connections: 8, + socket_timeout_ms: 5_000, + max_expiry_skew_ms: 300_000, + }; + let store = dir.join("replay.cc"); + let routes = ProviderRoutes::new([(MODEL.to_string(), "claude-code".to_string())]).unwrap(); + thread::spawn(move || { + serve( + listener, + limits, + vec![admission], + &store, + routes, + Arc::new(router), + ) + }); + + let mut args = AskArgs { + endpoint, + caller_id: CALLER.into(), + key_file: dir.join("unused"), + model: MODEL.into(), + instructions: "i".into(), + effort: None, + max_output_tokens: 64, + timeout: Duration::from_secs(5), + prompt: "p".into(), + }; + let mut forced = build_invocation(&args).unwrap().request; + forced.tools.push(ToolDefinition { + name: "lookup".into(), + description: "d".into(), + parameters_json: "{}".into(), + }); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as u64; + let invocation = TransportInvocation::new( + CALLER, + now + 60_000, + provider_request_sha256(&forced).unwrap(), + forced, + ) + .unwrap(); + let client = ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap(); + let result = client.execute(&invocation).unwrap(); + let TransportDisposition::Transported { receipt, .. } = &result.disposition else { + panic!( + "expected the planner's failed result, got {:?}", + result.disposition + ); + }; + assert!(matches!( + receipt.outcome, + TransportOutcome::Failed { + kind: FailureKind::InvalidRequest, + .. + } + )); + assert_eq!( + spawns.load(Ordering::SeqCst), + 0, + "the claude child must never start" + ); + // The same CLI path with no tools would have reached the spawn. + args.key_file = dir.join("unused"); + let clean = client.execute(&build_invocation(&args).unwrap()).unwrap(); + assert!(matches!( + clean.disposition, + TransportDisposition::Transported { .. } + )); + assert_eq!(spawns.load(Ordering::SeqCst), 1); +} + +#[test] +fn the_binary_prints_the_answer_on_success() { + let rig = rig(Script::Text("pong")); + let out = run_binary( + &rig, + "ping", + &["--effort", "low", "--max-output-tokens", "1024"], + ); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(String::from_utf8(out.stdout).unwrap(), "pong"); + assert!(out.stderr.is_empty()); +} + +#[test] +fn the_binary_fails_loudly_with_one_stderr_line_and_empty_stdout() { + let rig = rig(Script::Text("x")); + let out = run_binary(&rig, "", &[]); + assert!(!out.status.success()); + assert!(out.stdout.is_empty()); + let err = String::from_utf8(out.stderr).unwrap(); + assert_eq!(err.trim_end().lines().count(), 1, "{err}"); + assert!(err.starts_with("claude-connector: ")); + assert!(!err.contains(KEY)); + // Tools, a working directory and a second endpoint are not flags. + for flag in ["--tools", "--cwd", "--work-dir"] { + let out = run_binary(&rig, "q", &[flag, "x"]); + assert!(!out.status.success()); + assert!(out.stdout.is_empty()); + } + assert!(rig.seen().is_empty()); +} + +/// Runs the binary with `--system-file` instead of `--system`, killing it if it +/// has not exited within five seconds (a hang is a failure, not a stuck suite). +fn run_with_system_file(rig: &Rig, file: &std::path::Path) -> std::process::Output { + use std::io::Write; + let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args(["ask", "--endpoint", &rig.endpoint.to_string()]) + .args(["--caller-id", CALLER, "--model", MODEL]) + .args(["--max-output-tokens", "1024"]) + .args(["--connection-key-file", rig.key_file.to_str().unwrap()]) + .args(["--system-file", file.to_str().unwrap()]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let _ = child.stdin.take().unwrap().write_all(b"question"); + let started = std::time::Instant::now(); + while child.try_wait().unwrap().is_none() { + if started.elapsed() > Duration::from_secs(5) { + child.kill().unwrap(); + let _ = child.wait(); + panic!("the binary hung on its --system-file"); + } + thread::sleep(Duration::from_millis(20)); + } + child.wait_with_output().unwrap() +} + +#[test] +fn the_binary_bounds_and_guards_its_system_file() { + use claude_connector::ask::MAX_SYSTEM_BYTES; + let rig = rig(Script::Text("accepted")); + + let fifo = rig.dir.join("system.fifo"); + let path = std::ffi::CString::new(fifo.to_str().unwrap()).unwrap(); + assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0); + let out = run_with_system_file(&rig, &fifo); + assert!(!out.status.success()); + assert!(out.stdout.is_empty()); + + let zero = run_with_system_file(&rig, std::path::Path::new("/dev/zero")); + assert!(!zero.status.success()); + assert!(zero.stdout.is_empty()); + + let file = rig.dir.join("system.txt"); + std::fs::write(&file, vec![b's'; MAX_SYSTEM_BYTES + 1]).unwrap(); + let over = run_with_system_file(&rig, &file); + assert!(!over.status.success()); + assert!(over.stdout.is_empty()); + assert!(String::from_utf8_lossy(&over.stderr).contains("larger than")); + assert!(rig.seen().is_empty()); + + std::fs::write(&file, vec![b's'; MAX_SYSTEM_BYTES]).unwrap(); + let exact = run_with_system_file(&rig, &file); + assert!( + exact.status.success(), + "{}", + String::from_utf8_lossy(&exact.stderr) + ); + assert_eq!(String::from_utf8(exact.stdout).unwrap(), "accepted"); + assert_eq!(rig.seen()[0].instructions.len(), MAX_SYSTEM_BYTES); +} diff --git a/crates/claude-connector/tests/config_document.rs b/crates/claude-connector/tests/config_document.rs index 65c7b5d..f36dc1c 100644 --- a/crates/claude-connector/tests/config_document.rs +++ b/crates/claude-connector/tests/config_document.rs @@ -1,6 +1,5 @@ //! The claude-connector's configuration document and binary: what the -//! document accepts, what it refuses, and that a document of the dollar era -//! fails closed. +//! document accepts, what it refuses, and that older documents fail closed. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -8,10 +7,11 @@ use std::process::{Command, Output}; use std::sync::atomic::{AtomicUsize, Ordering}; use claude_connector::{ - ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, load_config, write_config, + ClaudeConnectorConfig, ConfigError, EffortMap, ForcedToolChoice, LeaseHolderConfig, ModelRow, + OutputSchemaSupport, ProviderEntry, ProviderWire, load_config, write_config, }; use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore}; -use model_connector::{CallerConfig, LeaseTurn}; +use model_connector::{CallerConfig, LeaseScope, MAX_IDENTITY_BYTES, ReasoningEffort}; const OPUS: &str = "claude-opus-5-1"; const HAIKU: &str = "claude-haiku-5-5"; @@ -30,6 +30,7 @@ impl Scratch { std::fs::create_dir_all(&dir).unwrap(); Self(dir) } + fn path(&self, name: &str) -> PathBuf { self.0.join(name) } @@ -41,26 +42,70 @@ impl Drop for Scratch { } } +fn cli_provider(id: &str) -> ProviderEntry { + ProviderEntry { + id: id.to_string(), + credential: Some("claude-token".to_string()), + wire: ProviderWire::ClaudeCodeCli { + binary: "/opt/claude/bin/claude".into(), + binary_sha256: [7; 32], + work_dir: "/var/lib/claude-connector/work".into(), + config_dir: "/var/lib/claude-connector/home".into(), + prompt_dir: "/var/lib/claude-connector/prompts".into(), + handle_secret_credential: "claude-handle-secret".to_string(), + instance: "persona-a".to_string(), + deadline_ms: 600_000, + max_line_bytes: 4 << 20, + max_total_bytes: 64 << 20, + stderr_tail_bytes: 8192, + meter_model: None, + }, + } +} + +fn http_provider(id: &str, base_url: &str, credential: Option<&str>) -> ProviderEntry { + ProviderEntry { + id: id.to_string(), + credential: credential.map(String::from), + wire: ProviderWire::AnthropicMessages { + base_url: base_url.to_string(), + deadline_ms: 600_000, + max_response_bytes: 64 << 20, + }, + } +} + +fn model_row(id: &str, provider: &str) -> ModelRow { + ModelRow { + id: id.to_string(), + provider: provider.to_string(), + upstream: id.to_string(), + efforts: EffortMap { + low: Some("low".to_string()), + medium: Some("medium".to_string()), + high: Some("high".to_string()), + max: Some("max".to_string()), + }, + unset_effort: None, + forced_tool_choice: ForcedToolChoice::Never, + output_schema: OutputSchemaSupport::Native, + strict_tools: false, + } +} + fn valid() -> ClaudeConnectorConfig { ClaudeConnectorConfig { listen: "127.0.0.1:7443".to_string(), replay_store: "/var/lib/claude-connector/replay.cc".into(), - claude_binary: "/opt/claude/bin/claude".into(), - claude_binary_sha256: [7; 32], - work_dir: "/var/lib/claude-connector/work".into(), - config_dir: "/var/lib/claude-connector/home".into(), - prompt_dir: "/var/lib/claude-connector/prompts".into(), - instance: "persona-a".to_string(), - token_credential: "claude-token".to_string(), - handle_secret_credential: "claude-handle-secret".to_string(), - deadline_ms: 600_000, - max_line_bytes: 4 << 20, - max_total_bytes: 64 << 20, - stderr_tail_bytes: 8192, max_frame_bytes: 2 << 20, max_connections: 8, socket_timeout_ms: 10_000, max_expiry_skew_ms: 300_000, + providers: vec![cli_provider("claude-code")], + models: vec![ + model_row(HAIKU, "claude-code"), + model_row(OPUS, "claude-code"), + ], callers: vec![CallerConfig { caller_runtime_id: "persona-a-caller".to_string(), connection_key_file: "/etc/claude-connector/caller.key".into(), @@ -71,11 +116,12 @@ fn valid() -> ClaudeConnectorConfig { max_output_tokens: 32_768, }], lease_socket: Some("/run/claude-connector/lease.sock".into()), - lease_callers: vec![LeaseCallerConfig { - unix_user: "mind-eureka-self".to_string(), + lease_holders: vec![LeaseHolderConfig { + unix_user: "agent-alice".to_string(), caller_id: "persona-a-caller".to_string(), - turn: LeaseTurn::SelfRun, - unit_instance: "eureka".to_string(), + provider: "claude-code".to_string(), + unit: "agent@alice.service".to_string(), + scope: LeaseScope::PerCaller, }], lease_max_ms: 3_600_000, } @@ -135,26 +181,49 @@ fn a_dollar_era_config_is_refused_at_load() { assert!(matches!(load_config(&path), Err(ConfigError::Store))); } +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "gamecult.model_connector.claude_connector_config.v2")] +struct V2Config { + #[cultcache(key = 0)] + listen: String, +} + #[test] -fn the_known_models_are_the_allowed_models_by_form_alone() { +fn v2_config_is_refused_at_load() { + let scratch = Scratch::new(); + let path = scratch.path("v2.cc"); + { + let mut cache = CultCache::new(); + cache.register_entry_type::().unwrap(); + cache + .add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)) + .unwrap(); + cache + .put( + "runtime".to_string(), + &V2Config { + listen: "127.0.0.1:7443".to_string(), + }, + ) + .unwrap(); + } + assert!(matches!(load_config(&path), Err(ConfigError::Store))); +} + +#[test] +fn allowed_models_must_be_subset_of_configured_models() { for good in [ - "claude-opus-5-1", - "claude-haiku-5-5", - "claude-opus-5", - "claude-opus-5-1-20260101", + "deepseek-flash", + "gpt-5", + "custom/model-1", + "claude-sonnet-5-5", ] { let mut config = valid(); + config.models.push(model_row(good, "claude-code")); config.callers[0].allowed_models = vec![good.to_string()]; assert!(config.validate().is_ok(), "{good}"); } - for bad in [ - "sonnet", - "claude-", - "claude-sonnet-latest", - "claude-Opus-5-1", - "claude-opus-5-1-2026", - "claude-opus-5-1-20260101-x", - ] { + for bad in ["unconfigured-model", "deepseek-v4-pro", ""] { let mut config = valid(); config.callers[0].allowed_models = vec![bad.to_string()]; assert_eq!(refused(&config), "allowed_models", "{bad}"); @@ -162,11 +231,333 @@ fn the_known_models_are_the_allowed_models_by_form_alone() { let mut twice = valid(); twice.callers[0].allowed_models = vec![OPUS.to_string(), OPUS.to_string()]; assert_eq!(refused(&twice), "allowed_models"); + let mut none = valid(); none.callers[0].allowed_models.clear(); assert_eq!(refused(&none), "allowed_models"); } +#[test] +fn v3_validation_refuses_invalid_providers_models_and_urls() { + // Valid HTTPS and loopback HTTP URLs (with and without credential). + for (url, cred) in [ + ("https://api.example.com", Some("k1")), + ("https://api.example.com/v1beta/openai", Some("k1")), + ("http://127.0.0.1:8080", None), + ("http://127.0.0.1:8080/v1", Some("k1")), + ("http://[::1]:8080", None), + ("http://[::1]:8080/v1", Some("k1")), + ] { + let mut config = valid(); + config.providers.push(http_provider("http-p", url, cred)); + config.models.push(model_row("m-http", "http-p")); + assert!(config.validate().is_ok(), "{url} cred={cred:?}"); + } + + // Invalid base_urls. + for bad_url in [ + "http://api.example.com", + "http://localhost:8080", + "http://192.168.1.10:8080", + "http://[fe80::1]:8080", + "ftp://api.example.com", + "https://user:pass@api.example.com", + "https://a@b.example.com/v1", + "https://api.example.com?foo=bar", + "https://api.example.com#frag", + "https://api.example.com ", + " https://api.example.com", + "https://api.example.com/", + "https://api.example.com//v1", + "https://", + "", + "https://api.example.com:+80", + "http://127.0.0.1:+8080", + "https://[::1]:+80", + "https://api.example.com:0", + "http://127.0.0.1:0", + "https://[::1]:0", + "https://api.example.com:", + "https://api.example.com:99999", + "https://api.example.com/v1 x", + "https://api.example.com/v1\x00", + "https://api.example.com/v1?x=1", + "https://api.example.com/v1#frag", + "https://api.example.com/v1\\x", + "https://.a.test", + "https://a.test.", + "https://a..b.test", + "https://a_b.test", + "https://[::1", + ] { + let mut config = valid(); + config + .providers + .push(http_provider("http-p", bad_url, Some("k1"))); + assert_eq!(refused(&config), "base_url", "{bad_url:?}"); + } + + // Keyless non-loopback refused. + let mut keyless_remote = valid(); + keyless_remote + .providers + .push(http_provider("remote", "https://api.example.com", None)); + assert_eq!(refused(&keyless_remote), "credential"); + + // Duplicate credential names across entries refused. + let mut dup_cred = valid(); + dup_cred.providers.push(http_provider( + "remote", + "https://api.example.com", + Some("claude-token"), + )); + assert_eq!(refused(&dup_cred), "credential"); + + // Provider credential colliding with CLI handle_secret_credential refused. + let mut collide_handle = valid(); + collide_handle.providers.push(http_provider( + "remote", + "https://api.example.com", + Some("claude-handle-secret"), + )); + assert_eq!(refused(&collide_handle), "credential"); + + // Model naming unknown provider refused. + let mut unknown_provider = valid(); + unknown_provider + .models + .push(model_row("m-unknown", "nobody")); + assert_eq!(refused(&unknown_provider), "model_provider"); + + // Second ClaudeCodeCli entry refused. + let mut two_cli = valid(); + two_cli.providers.push(ProviderEntry { + id: "cli-two".to_string(), + credential: Some("claude-token-two".to_string()), + wire: ProviderWire::ClaudeCodeCli { + binary: "/opt/claude/bin/claude".into(), + binary_sha256: [7; 32], + work_dir: "/var/lib/claude-connector/work2".into(), + config_dir: "/var/lib/claude-connector/home2".into(), + prompt_dir: "/var/lib/claude-connector/prompts2".into(), + handle_secret_credential: "claude-handle-secret-2".to_string(), + instance: "persona-b".to_string(), + deadline_ms: 600_000, + max_line_bytes: 4 << 20, + max_total_bytes: 64 << 20, + stderr_tail_bytes: 8192, + meter_model: None, + }, + }); + assert_eq!(refused(&two_cli), "providers"); + + // Valid keyed HTTPS and keyless loopback OpenAiChat entries pass validate(). + let mut oai_https = valid(); + oai_https.providers.push(ProviderEntry { + id: "deepseek".to_string(), + credential: Some("ds-key".to_string()), + wire: ProviderWire::OpenAiChat { + base_url: "https://api.deepseek.com".to_string(), + strict_unsupported: vec!["minLength".to_string(), "maxItems".to_string()], + deadline_ms: 600_000, + max_response_bytes: 64 << 20, + }, + }); + assert!(oai_https.validate().is_ok()); + + let mut oai_loopback = valid(); + oai_loopback.providers.push(ProviderEntry { + id: "local-oai".to_string(), + credential: None, + wire: ProviderWire::OpenAiChat { + base_url: "http://127.0.0.1:8080/v1".to_string(), + strict_unsupported: Vec::new(), + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }); + assert!(oai_loopback.validate().is_ok()); + + // OpenAiChat validation refuses bad base_url, keyless non-loopback, zero HTTP limits, and empty/untrimmed strict_unsupported. + let mut oai_bad_url = valid(); + oai_bad_url.providers.push(ProviderEntry { + id: "deepseek".to_string(), + credential: Some("ds-key".to_string()), + wire: ProviderWire::OpenAiChat { + base_url: "http://api.deepseek.com".to_string(), + strict_unsupported: Vec::new(), + deadline_ms: 600_000, + max_response_bytes: 64 << 20, + }, + }); + assert_eq!(refused(&oai_bad_url), "base_url"); + + let mut oai_keyless_remote = valid(); + oai_keyless_remote.providers.push(ProviderEntry { + id: "deepseek".to_string(), + credential: None, + wire: ProviderWire::OpenAiChat { + base_url: "https://api.deepseek.com".to_string(), + strict_unsupported: Vec::new(), + deadline_ms: 600_000, + max_response_bytes: 64 << 20, + }, + }); + assert_eq!(refused(&oai_keyless_remote), "credential"); + + let mut oai_zero_limit = valid(); + oai_zero_limit.providers.push(ProviderEntry { + id: "deepseek".to_string(), + credential: Some("ds-key".to_string()), + wire: ProviderWire::OpenAiChat { + base_url: "https://api.deepseek.com".to_string(), + strict_unsupported: Vec::new(), + deadline_ms: 0, + max_response_bytes: 64 << 20, + }, + }); + assert_eq!(refused(&oai_zero_limit), "http limits"); + + for bad_kw in ["", " ", " minLength", "minLength "] { + let mut oai_bad_kw = valid(); + oai_bad_kw.providers.push(ProviderEntry { + id: "deepseek".to_string(), + credential: Some("ds-key".to_string()), + wire: ProviderWire::OpenAiChat { + base_url: "https://api.deepseek.com".to_string(), + strict_unsupported: vec![bad_kw.to_string()], + deadline_ms: 600_000, + max_response_bytes: 64 << 20, + }, + }); + assert_eq!(refused(&oai_bad_kw), "strict_unsupported"); + } + + // Reserved stand-in provider id and oversized ids refused. + let mut stand_in = valid(); + stand_in.providers = vec![http_provider( + "model-connector", + "https://api.example.com", + Some("k1"), + )]; + assert_eq!(refused(&stand_in), "provider_id"); + + let mut oversized_provider = valid(); + oversized_provider.providers.push(http_provider( + &"p".repeat(MAX_IDENTITY_BYTES + 1), + "https://api.example.com", + Some("k1"), + )); + assert_eq!(refused(&oversized_provider), "provider_id"); + + let mut oversized_model = valid(); + oversized_model.models.push(model_row( + &"m".repeat(MAX_IDENTITY_BYTES + 1), + "claude-code", + )); + assert_eq!(refused(&oversized_model), "model_id"); + + // Empty providers, empty models, duplicate ids, empty/whitespace ids, untrimmed upstream/efforts/unset_effort, meter_model, and zero HTTP limits refused. + let mut empty_providers = valid(); + empty_providers.providers.clear(); + assert_eq!(refused(&empty_providers), "providers"); + + let mut empty_models = valid(); + empty_models.models.clear(); + assert_eq!(refused(&empty_models), "models"); + + let mut dup_provider = valid(); + dup_provider.providers.push(http_provider( + "claude-code", + "https://api.example.com", + Some("k-dup-provider"), + )); + assert_eq!(refused(&dup_provider), "providers"); + + let mut dup_model = valid(); + dup_model.models.push(model_row(HAIKU, "claude-code")); + assert_eq!(refused(&dup_model), "models"); + + for bad_id in ["", " ", " p", "p "] { + let mut bad_provider = valid(); + bad_provider.providers.push(http_provider( + bad_id, + "https://api.example.com", + Some("k-bad-provider"), + )); + assert_eq!(refused(&bad_provider), "provider_id", "{bad_id:?}"); + + let mut bad_model = valid(); + bad_model.models.push(model_row(bad_id, "claude-code")); + assert_eq!(refused(&bad_model), "model_id", "{bad_id:?}"); + } + + for bad_upstream in ["", " ", " u", "u "] { + let mut bad = valid(); + bad.models[0].upstream = bad_upstream.to_string(); + assert_eq!(refused(&bad), "upstream", "{bad_upstream:?}"); + } + + for bad_unset in ["", " ", " none", "none "] { + let mut bad = valid(); + bad.models[0].unset_effort = Some(bad_unset.to_string()); + assert_eq!(refused(&bad), "unset_effort", "{bad_unset:?}"); + } + let mut valid_unset = valid(); + valid_unset.models[0].unset_effort = Some("none".to_string()); + assert!(valid_unset.validate().is_ok()); + + for edit in [ + |m: &mut ModelRow| m.efforts.low = Some(" low".to_string()), + |m: &mut ModelRow| m.efforts.medium = Some(" medium".to_string()), + |m: &mut ModelRow| m.efforts.high = Some("high ".to_string()), + |m: &mut ModelRow| m.efforts.max = Some("".to_string()), + ] { + let mut untrimmed_effort = valid(); + edit(&mut untrimmed_effort.models[0]); + assert_eq!(refused(&untrimmed_effort), "efforts"); + } + + let mut with_meter_model = valid(); + with_meter_model.providers.push(http_provider( + "remote", + "https://api.example.com", + Some("k-remote"), + )); + with_meter_model.models = vec![model_row(HAIKU, "remote"), model_row(OPUS, "remote")]; + if let ProviderWire::ClaudeCodeCli { meter_model, .. } = &mut with_meter_model.providers[0].wire + { + *meter_model = Some(HAIKU.to_string()); + } + assert!(with_meter_model.validate().is_ok()); + + for bad_meter in ["", " ", " m", "m "] { + let mut bad = valid(); + if let ProviderWire::ClaudeCodeCli { meter_model, .. } = &mut bad.providers[0].wire { + *meter_model = Some(bad_meter.to_string()); + } + assert_eq!(refused(&bad), "meter_model", "{bad_meter:?}"); + } + + for (deadline_ms, max_response_bytes) in [(0, 64 << 20), (600_000, 0)] { + let mut bad = valid(); + bad.providers.push(ProviderEntry { + id: "http-zero".to_string(), + credential: Some("k-http-zero".to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: "https://api.example.com".to_string(), + deadline_ms, + max_response_bytes, + }, + }); + assert_eq!( + refused(&bad), + "http limits", + "deadline_ms={deadline_ms} max_response_bytes={max_response_bytes}" + ); + } +} + #[test] fn caller_bounds_are_required_nonzero() { let edits: [fn(&mut ClaudeConnectorConfig); 3] = [ @@ -182,41 +573,165 @@ fn caller_bounds_are_required_nonzero() { } #[test] -fn a_lease_caller_names_a_configured_caller_and_a_socket_exists_exactly_when_it_leases() { - let mut stranger = valid(); - stranger.lease_callers[0].caller_id = "nobody".to_string(); - assert_eq!(refused(&stranger), "lease_callers"); +fn cli_child_limits_are_bounded() { + let bad_edits: [fn(&mut ProviderWire); 4] = [ + |w| { + if let ProviderWire::ClaudeCodeCli { deadline_ms, .. } = w { + *deadline_ms = 0; + } + }, + |w| { + if let ProviderWire::ClaudeCodeCli { max_line_bytes, .. } = w { + *max_line_bytes = 0; + } + }, + |w| { + if let ProviderWire::ClaudeCodeCli { + max_line_bytes, + max_total_bytes, + .. + } = w + { + *max_line_bytes = 1024; + *max_total_bytes = 1023; + } + }, + |w| { + if let ProviderWire::ClaudeCodeCli { + stderr_tail_bytes, .. + } = w + { + *stderr_tail_bytes = 0; + } + }, + ]; + for edit in bad_edits { + let mut config = valid(); + edit(&mut config.providers[0].wire); + assert_eq!(refused(&config), "child limits"); + } - let mut no_callers = valid(); - no_callers.lease_callers.clear(); - assert_eq!(refused(&no_callers), "lease_callers"); + let mut equal_total = valid(); + if let ProviderWire::ClaudeCodeCli { + max_line_bytes, + max_total_bytes, + .. + } = &mut equal_total.providers[0].wire + { + *max_line_bytes = 1024; + *max_total_bytes = 1024; + } + assert!(equal_total.validate().is_ok()); +} + +#[test] +fn effort_map_get_returns_configured_wire_values() { + let populated = EffortMap { + low: Some("l".to_string()), + medium: Some("m".to_string()), + high: Some("h".to_string()), + max: Some("x".to_string()), + }; + assert_eq!(populated.get(ReasoningEffort::Low), Some("l")); + assert_eq!(populated.get(ReasoningEffort::Medium), Some("m")); + assert_eq!(populated.get(ReasoningEffort::High), Some("h")); + assert_eq!(populated.get(ReasoningEffort::Max), Some("x")); + + let empty = EffortMap::default(); + assert_eq!(empty.get(ReasoningEffort::Low), None); + assert_eq!(empty.get(ReasoningEffort::Medium), None); + assert_eq!(empty.get(ReasoningEffort::High), None); + assert_eq!(empty.get(ReasoningEffort::Max), None); +} + +#[test] +fn a_lease_holder_names_a_configured_caller_and_valid_unit_and_provider() { + let mut stranger = valid(); + stranger.lease_holders[0].caller_id = "nobody".to_string(); + assert_eq!(refused(&stranger), "lease_holders"); + + let mut no_holders = valid(); + no_holders.lease_holders.clear(); + assert_eq!(refused(&no_holders), "lease_holders"); let mut no_socket = valid(); no_socket.lease_socket = None; - assert_eq!(refused(&no_socket), "lease_callers"); - no_socket.lease_callers.clear(); + assert_eq!(refused(&no_socket), "lease_holders"); + no_socket.lease_holders.clear(); assert!(no_socket.validate().is_ok()); let mut twice = valid(); - twice.lease_callers.push(twice.lease_callers[0].clone()); - assert_eq!(refused(&twice), "lease_callers"); + twice.lease_holders.push(twice.lease_holders[0].clone()); + assert_eq!(refused(&twice), "lease_holders"); + + let mut plain_unit = valid(); + plain_unit.lease_holders[0].unit = "worker.service".to_string(); + assert!(plain_unit.validate().is_ok()); + + let mut instanced_unit = valid(); + instanced_unit.lease_holders[0].unit = "agent@alice.service".to_string(); + instanced_unit.lease_holders[0].scope = LeaseScope::PerInvocation; + assert!(instanced_unit.validate().is_ok()); + + // Custom CLI provider entry id binds lease_holders.provider. + let mut custom_cli = valid(); + custom_cli.providers = vec![cli_provider("sub-cli")]; + for model in &mut custom_cli.models { + model.provider = "sub-cli".to_string(); + } + custom_cli.lease_holders[0].provider = "sub-cli".to_string(); + assert!(custom_cli.validate().is_ok()); + + for bad_unit in [ + "agent@.service", + "@a.service", + "a@b@c.service", + ".service", + "agent", + "a/b.service", + "a..b.service", + "a b.service", + ] { + let mut bad = valid(); + bad.lease_holders[0].unit = bad_unit.to_string(); + assert_eq!(refused(&bad), "lease_holders", "{bad_unit:?}"); + } + + let mut bad_provider = valid(); + bad_provider.lease_holders[0].provider = "deepseek".to_string(); + assert_eq!(refused(&bad_provider), "lease_holders"); + + // Lease with CLI provider lacking both meter_model and any CLI ModelRow is refused. + let mut no_cli_model = valid(); + no_cli_model.providers.push(http_provider( + "remote", + "https://api.example.com", + Some("k"), + )); + no_cli_model.models = vec![model_row(HAIKU, "remote"), model_row(OPUS, "remote")]; + assert_eq!(refused(&no_cli_model), "meter_model"); } fn run(args: &[&str]) -> Output { Command::new(env!("CARGO_BIN_EXE_claude-connector")) .args(args) - .env_clear() .output() .unwrap() } -fn init_flags(scratch: &Scratch, extra: &[&str]) -> Vec { +fn cli_init_flags(scratch: &Scratch, extra: &[&str]) -> Vec { let path = |name: &str| scratch.path(name).to_string_lossy().into_owned(); let mut flags: Vec = [ "--listen", "127.0.0.1:0", "--replay-store", &path("replay.cc"), + "--provider", + "claude-code", + "--wire", + "claude-code-cli", + "--credential", + "claude-token", "--claude-binary", &path("claude"), "--claude-sha256", @@ -229,12 +744,62 @@ fn init_flags(scratch: &Scratch, extra: &[&str]) -> Vec { &path("prompts"), "--instance", "persona-a", - "--token-credential", - "claude-token", "--handle-secret-credential", "claude-handle-secret", "--handle-secret-file", &path("handle.secret"), + "--model", + HAIKU, + "--upstream", + HAIKU, + "--forced-tool-choice", + "never", + "--output-schema", + "native", + "--strict-tools", + "false", + "--caller-id", + "persona-a-caller", + "--connection-key-file", + &path("caller.key"), + "--connection-key-epoch", + "1", + "--allowed-model", + HAIKU, + ] + .map(String::from) + .to_vec(); + flags.extend(extra.iter().map(|flag| flag.to_string())); + flags +} + +fn http_init_flags(scratch: &Scratch, extra: &[&str]) -> Vec { + let path = |name: &str| scratch.path(name).to_string_lossy().into_owned(); + let mut flags: Vec = [ + "--listen", + "127.0.0.1:0", + "--replay-store", + &path("replay.cc"), + "--provider", + "anthropic-a", + "--wire", + "anthropic-messages", + "--base-url", + "https://api.example.test", + "--credential", + "cred-one", + "--model", + HAIKU, + "--upstream", + "claude-haiku-upstream", + "--effort-low", + "low", + "--forced-tool-choice", + "always", + "--output-schema", + "native", + "--strict-tools", + "false", "--caller-id", "persona-a-caller", "--connection-key-file", @@ -260,12 +825,347 @@ fn init(scratch: &Scratch, flags: &[String]) -> Output { #[test] fn config_init_writes_the_flags_into_the_document() { let scratch = Scratch::new(); - let made = init(&scratch, &init_flags(&scratch, &[])); + let made = init(&scratch, &cli_init_flags(&scratch, &[])); assert!(made.status.success(), "{:?}", made); let config = load_config(&scratch.path("connector.cc")).unwrap(); + assert_eq!(config.providers.len(), 1); + assert_eq!(config.providers[0].id, "claude-code"); + assert_eq!(config.models.len(), 1); + assert_eq!(config.models[0].id, HAIKU); + assert_eq!(config.models[0].forced_tool_choice, ForcedToolChoice::Never); + assert_eq!(config.models[0].output_schema, OutputSchemaSupport::Native); + assert!(!config.models[0].strict_tools); assert_eq!(config.callers[0].allowed_models, [HAIKU]); - assert_eq!(config.claude_binary_sha256, [0xab; 32]); - assert!(config.lease_callers.is_empty()); + assert!(matches!( + config.providers[0].wire, + ProviderWire::ClaudeCodeCli { + binary_sha256, + .. + } if binary_sha256 == [0xab; 32] + )); + assert!(config.lease_holders.is_empty()); +} + +#[test] +fn config_init_without_provider_fails_naming_the_flag() { + let scratch = Scratch::new(); + let config = scratch.path("connector.cc"); + let p = config.to_str().unwrap(); + + // Bare `config init` without `--provider`. + let bare = run(&["config", "init", p]); + assert!(!bare.status.success(), "{bare:?}"); + let bare_err = String::from_utf8_lossy(&bare.stderr); + assert!(bare_err.contains("--provider"), "{bare_err}"); + assert!(!config.exists()); + + // Full flags except `--provider` omitted. + let all = http_init_flags(&scratch, &[]); + let mut without_provider = Vec::new(); + let mut iter = all.iter(); + while let Some(flag) = iter.next() { + if flag == "--provider" { + let _ = iter.next(); + continue; + } + without_provider.push(flag.clone()); + } + let out = init(&scratch, &without_provider); + assert!(!out.status.success(), "{out:?}"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("--provider"), "{stderr}"); + assert!(!config.exists()); +} + +#[test] +fn config_init_rejects_v2_auth_and_conflicting_wire_flags() { + for bad in [ + vec!["--auth", "oauth-token"], + vec!["--token-credential", "claude-token"], + ] { + let scratch = Scratch::new(); + let made = init(&scratch, &cli_init_flags(&scratch, &bad)); + assert!(!made.status.success(), "{bad:?}"); + assert!(!scratch.path("connector.cc").exists()); + } + + let scratch = Scratch::new(); + let secret = scratch.path("handle.secret").to_string_lossy().into_owned(); + let http_with_cli_flag = init( + &scratch, + &http_init_flags(&scratch, &["--handle-secret-file", &secret]), + ); + assert!(!http_with_cli_flag.status.success()); + assert!( + String::from_utf8_lossy(&http_with_cli_flag.stderr).contains("--handle-secret-file"), + "{}", + String::from_utf8_lossy(&http_with_cli_flag.stderr) + ); + assert!(!scratch.path("connector.cc").exists()); + + let scratch = Scratch::new(); + let cli_with_http_flag = init( + &scratch, + &cli_init_flags(&scratch, &["--base-url", "https://api.example.test"]), + ); + assert!(!cli_with_http_flag.status.success()); + assert!( + String::from_utf8_lossy(&cli_with_http_flag.stderr).contains("--base-url"), + "{}", + String::from_utf8_lossy(&cli_with_http_flag.stderr) + ); + assert!(!scratch.path("connector.cc").exists()); +} + +#[test] +fn config_add_provider_and_add_model_append_and_validate() { + let scratch = Scratch::new(); + let made = init(&scratch, &http_init_flags(&scratch, &[])); + assert!(made.status.success(), "{made:?}"); + let config_path = scratch.path("connector.cc"); + let p = config_path.to_str().unwrap(); + + let added_provider = run(&[ + "config", + "add-provider", + p, + "--provider", + "local-stub", + "--wire", + "anthropic-messages", + "--base-url", + "http://127.0.0.1:8080", + ]); + assert!(added_provider.status.success(), "{added_provider:?}"); + + let added_model = run(&[ + "config", + "add-model", + p, + "--model", + "deepseek-flash", + "--provider", + "local-stub", + "--upstream", + "deepseek-chat", + "--effort-low", + "low", + "--effort-high", + "high", + "--unset-effort", + "none", + "--forced-tool-choice", + "without-thinking", + "--output-schema", + "none", + "--strict-tools", + "true", + ]); + assert!(added_model.status.success(), "{added_model:?}"); + + let loaded = load_config(&config_path).unwrap(); + assert_eq!(loaded.providers.len(), 2); + assert_eq!(loaded.providers[1].id, "local-stub"); + assert_eq!(loaded.providers[1].credential, None); + assert_eq!(loaded.models.len(), 2); + assert!(!loaded.models[0].strict_tools); + assert_eq!(loaded.models[1].id, "deepseek-flash"); + assert_eq!(loaded.models[1].provider, "local-stub"); + assert_eq!(loaded.models[1].upstream, "deepseek-chat"); + assert_eq!(loaded.models[1].unset_effort.as_deref(), Some("none")); + assert_eq!( + loaded.models[1].forced_tool_choice, + ForcedToolChoice::WithoutThinking + ); + assert_eq!(loaded.models[1].output_schema, OutputSchemaSupport::None); + assert!(loaded.models[1].strict_tools); + + let added_oai = run(&[ + "config", + "add-provider", + p, + "--provider", + "ds", + "--wire", + "openai-chat", + "--base-url", + "https://api.deepseek.com", + "--credential", + "ds-cred", + "--strict-unsupported", + "minLength", + "--strict-unsupported", + "maxItems", + ]); + assert!(added_oai.status.success(), "{added_oai:?}"); + + let added_oai_model = run(&[ + "config", + "add-model", + p, + "--model", + "ds-chat", + "--provider", + "ds", + "--upstream", + "deepseek-chat", + "--unset-effort", + "none", + "--forced-tool-choice", + "without-thinking", + "--output-schema", + "none", + "--strict-tools", + "true", + ]); + assert!(added_oai_model.status.success(), "{added_oai_model:?}"); + + let loaded_oai = load_config(&config_path).unwrap(); + assert_eq!(loaded_oai.providers.len(), 3); + assert_eq!( + loaded_oai.providers[2], + ProviderEntry { + id: "ds".to_string(), + credential: Some("ds-cred".to_string()), + wire: ProviderWire::OpenAiChat { + base_url: "https://api.deepseek.com".to_string(), + strict_unsupported: vec!["minLength".to_string(), "maxItems".to_string()], + deadline_ms: 600_000, + max_response_bytes: 64 << 20, + }, + } + ); + + std::fs::write(scratch.path("caller.key"), "k".repeat(48)).unwrap(); + let creds = scratch.path("creds"); + std::fs::create_dir_all(&creds).unwrap(); + std::fs::write(creds.join("cred-one"), "k1").unwrap(); + std::fs::write(creds.join("ds-cred"), "k2").unwrap(); + let check_ok = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args(["config", "check", p]) + .env("CREDENTIALS_DIRECTORY", &creds) + .output() + .unwrap(); + assert!(check_ok.status.success(), "{check_ok:?}"); + + let before_invalid = std::fs::read(&config_path).unwrap(); + for bad_args in [ + // Duplicate credential refused. + vec![ + "config", + "add-provider", + p, + "--provider", + "dup", + "--wire", + "anthropic-messages", + "--base-url", + "https://two.example.test", + "--credential", + "cred-one", + ], + // Unknown provider on model refused. + vec![ + "config", + "add-model", + p, + "--model", + "m-bad", + "--provider", + "nobody", + "--upstream", + "u", + "--forced-tool-choice", + "never", + "--output-schema", + "native", + "--strict-tools", + "false", + ], + // Invalid bool flag refused. + vec![ + "config", + "add-model", + p, + "--model", + "m-bad-bool", + "--provider", + "local-stub", + "--upstream", + "u", + "--forced-tool-choice", + "never", + "--output-schema", + "native", + "--strict-tools", + "maybe", + ], + ] { + let out = run(&bad_args); + assert!(!out.status.success(), "{bad_args:?} unexpectedly succeeded"); + assert_eq!( + std::fs::read(&config_path).unwrap(), + before_invalid, + "{bad_args:?} modified config" + ); + } +} + +#[test] +fn readiness_names_failing_entry_id_and_never_leaks_secret() { + const SECRET_1: &str = "canary-secret-value-one-73a9"; + const SECRET_2: &str = "canary-secret-value-two-88f1"; + + let scratch = Scratch::new(); + std::fs::write(scratch.path("caller.key"), "k".repeat(48)).unwrap(); + let creds = scratch.path("creds"); + std::fs::create_dir_all(&creds).unwrap(); + std::fs::write(creds.join("cred-one"), SECRET_1).unwrap(); + std::fs::write(creds.join("cred-two"), SECRET_2).unwrap(); + + let made = init(&scratch, &http_init_flags(&scratch, &[])); + assert!(made.status.success(), "{made:?}"); + let config_path = scratch.path("connector.cc"); + let p = config_path.to_str().unwrap(); + + let added = run(&[ + "config", + "add-provider", + p, + "--provider", + "anthropic-b", + "--wire", + "anthropic-messages", + "--base-url", + "https://b.example.test", + "--credential", + "cred-two", + ]); + assert!(added.status.success(), "{added:?}"); + + let ok = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args(["config", "check", p]) + .env("CREDENTIALS_DIRECTORY", &creds) + .output() + .unwrap(); + assert!(ok.status.success(), "{ok:?}"); + let stdout = String::from_utf8_lossy(&ok.stdout); + assert!(stdout.contains("providers: 2"), "{stdout}"); + assert!(stdout.contains("models: 1"), "{stdout}"); + + // Remove the second entry's credential -> must fail naming `anthropic-b`, never the secret. + std::fs::remove_file(creds.join("cred-two")).unwrap(); + let fail = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args(["config", "check", p]) + .env("CREDENTIALS_DIRECTORY", &creds) + .output() + .unwrap(); + assert!(!fail.status.success(), "{fail:?}"); + let stderr = String::from_utf8_lossy(&fail.stderr); + assert!(stderr.contains("anthropic-b"), "{stderr}"); + for secret in [SECRET_1, SECRET_2, "cred-one", "cred-two"] { + assert!(!stderr.contains(secret), "leaked {secret}: {stderr}"); + } } #[test] @@ -278,7 +1178,7 @@ fn the_dollar_flags_are_not_flags() { ]; for extra in dollar_flags { let scratch = Scratch::new(); - let made = init(&scratch, &init_flags(&scratch, extra)); + let made = init(&scratch, &cli_init_flags(&scratch, extra)); assert!(!made.status.success(), "{extra:?} was accepted"); assert!( !Path::new(&scratch.path("connector.cc")).exists(), @@ -295,3 +1195,157 @@ fn serve_refuses_a_document_that_is_not_there() { assert!(!served.status.success(), "{served:?}"); assert!(!String::from_utf8_lossy(&served.stderr).is_empty()); } + +#[test] +fn add_lease_holder_and_unit_validation() { + let scratch = Scratch::new(); + let config_path = scratch.path("connector.cc"); + let made = init( + &scratch, + &cli_init_flags( + &scratch, + &[ + "--lease-socket", + "/run/claude-connector/lease.sock", + "--lease-user", + "agent-a", + "--unit", + "worker.service", + "--scope", + "per-caller", + ], + ), + ); + assert!(made.status.success(), "{made:?}"); + let p = config_path.to_str().unwrap(); + + let added = run(&[ + "config", + "add-lease-holder", + p, + "--lease-user", + "agent-b", + "--caller-id", + "persona-a-caller", + "--provider", + "claude-code", + "--unit", + "agent@b.service", + "--scope", + "per-invocation", + ]); + assert!(added.status.success(), "{added:?}"); + let config = load_config(&config_path).unwrap(); + assert_eq!(config.lease_holders.len(), 2); + assert_eq!(config.lease_holders[0].unit, "worker.service"); + assert_eq!(config.lease_holders[0].scope, LeaseScope::PerCaller); + assert_eq!(config.lease_holders[1].unit, "agent@b.service"); + assert_eq!(config.lease_holders[1].scope, LeaseScope::PerInvocation); + + for bad_args in [ + vec![ + "config", + "add-lease-holder", + p, + "--lease-user", + "agent-c", + "--caller-id", + "persona-a-caller", + "--provider", + "claude-code", + "--unit", + "agent@.service", + "--scope", + "per-caller", + ], + vec![ + "config", + "add-lease-holder", + p, + "--lease-user", + "agent-c", + "--caller-id", + "persona-a-caller", + "--provider", + "other", + "--unit", + "agent@c.service", + "--scope", + "per-caller", + ], + vec![ + "config", + "add-lease-holder", + p, + "--lease-user", + "agent-c", + "--caller-id", + "persona-a-caller", + "--provider", + "claude-code", + "--unit", + "agent@c.service", + "--scope", + "invalid", + ], + vec![ + "config", + concat!("add-lease-", "caller"), + p, + "--lease-user", + "agent-c", + "--caller-id", + "persona-a-caller", + "--turn", + "self", + "--lease-unit-instance", + "c", + ], + ] { + let out = run(&bad_args); + assert!(!out.status.success(), "{bad_args:?} unexpectedly succeeded"); + } + assert_eq!(load_config(&config_path).unwrap().lease_holders.len(), 2); +} + +#[test] +fn serve_and_check_refuse_a_lease_without_cli_provider() { + let scratch = Scratch::new(); + let path = scratch.path("handmade.cc"); + let bad = ClaudeConnectorConfig { + providers: vec![http_provider( + "anthropic-messages", + "https://api.example.test", + Some("api-key"), + )], + models: vec![model_row(HAIKU, "anthropic-messages")], + callers: vec![CallerConfig { + allowed_models: vec![HAIKU.to_string()], + ..valid().callers.into_iter().next().unwrap() + }], + lease_holders: vec![LeaseHolderConfig { + provider: "anthropic-messages".to_string(), + ..valid().lease_holders.into_iter().next().unwrap() + }], + ..valid() + }; + assert!(write_config(&path, &bad).is_err()); + { + // Written around write_config, which would refuse it. + let mut cache = CultCache::new(); + cache + .register_entry_type::() + .unwrap(); + cache + .add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)) + .unwrap(); + cache.put("runtime".to_string(), &bad).unwrap(); + } + let p = path.to_str().unwrap(); + for args in [vec!["serve", "--config", p], vec!["config", "check", p]] { + let out = run(&args); + assert!(!out.status.success(), "{args:?}: {out:?}"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("lease_socket"), "{args:?}: {stderr}"); + } +} diff --git a/crates/claude-connector/tests/lease.rs b/crates/claude-connector/tests/lease.rs index 9c6f27d..0b33e07 100644 --- a/crates/claude-connector/tests/lease.rs +++ b/crates/claude-connector/tests/lease.rs @@ -1,4 +1,4 @@ -//! The Self-run credential lease over a real unix socket: who may lease, where +//! The credential lease over a real unix socket: who may lease, where //! the token goes, what ends a lease, and the one usage-derived refusal, the //! provider's own. Nothing is reserved and nothing is billed. The unit a peer //! runs in is the `PeerUnits` port, answered here by a fake. @@ -14,18 +14,19 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use claude_connector::{ - LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused, + LeaseGranted, LeaseHolder, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused, LeaseRequest, LeaseUsageReadoutRequest, PeerUnit, PeerUnits, QuotaCell, TokenSource, decode_frame, encode_frame, serve_leases, }; -use model_connector::{CallerAdmission, LeaseTurn, PlanQuota, TransportService, UsageReadout}; +use model_connector::{ + CallerAdmission, LeaseScope, PlanQuota, ProviderRoutes, TransportService, UsageReadout, +}; use zeroize::Zeroizing; const CALLER: &str = "eureka"; const MODEL: &str = "claude-opus-5-1"; const TOKEN: &str = "sk-canary-lease-4c1f9a"; -const INSTANCE: &str = "eureka"; -const UNIT: &str = "mind-self@eureka.service"; +const UNIT: &str = "agent@alice.service"; static SEQUENCE: AtomicUsize = AtomicUsize::new(0); @@ -102,7 +103,7 @@ struct Harness { } impl Harness { - /// The peers connect from invocation `n` of the Self unit. + /// The peers connect from invocation `n` of the configured unit. fn enter(&self, n: u64) { self.run_in(UNIT, n); } @@ -224,7 +225,8 @@ fn contains(haystack: &[u8], needle: &str) -> bool { /// What a harness is built from. struct Setup { uid: u32, - turn: LeaseTurn, + scope: LeaseScope, + unit: &'static str, token: Option<&'static str>, max_connections: usize, } @@ -232,14 +234,15 @@ struct Setup { fn setup() -> Setup { Setup { uid: own_uid(), - turn: LeaseTurn::SelfRun, + scope: LeaseScope::PerCaller, + unit: UNIT, token: Some(TOKEN), max_connections: 8, } } /// A listener serving `uid` as the caller `eureka`. Peers start in invocation -/// 1 of the Self unit. +/// 1 of the configured unit. fn start(setup: Setup) -> Harness { let units = Arc::new(FakeUnits { peer: Mutex::new(None), @@ -255,7 +258,7 @@ fn start(setup: Setup) -> Harness { let service = Arc::new(Mutex::new( TransportService::open( &dir.join("replay.cc"), - "claude-code", + ProviderRoutes::new([(MODEL.to_string(), "claude-code".to_string())]).unwrap(), [CallerAdmission::new( CALLER, "lease-test-connection-key", @@ -283,16 +286,17 @@ fn start(setup: Setup) -> Harness { tokens.clone(), units.clone(), ); - let caller = LeaseCaller { + let holder = LeaseHolder { uid: setup.uid, caller_id: CALLER.to_string(), - turn: setup.turn, - unit_instance: INSTANCE.to_string(), + provider: "claude-code".to_string(), + unit: setup.unit.to_string(), + scope: setup.scope, }; std::thread::spawn(move || { let _ = serve_leases( &listener, - vec![caller], + vec![holder], LeaseLimits { socket_timeout: Duration::from_secs(2), max_lease_ms: 3_600_000, @@ -449,7 +453,7 @@ fn high_utilization_refuses_nothing() { } #[test] -fn a_peer_uid_outside_the_lease_callers_is_refused_and_nothing_is_read() { +fn a_peer_uid_outside_the_lease_holders_is_refused_and_nothing_is_read() { let harness = start(Setup { uid: own_uid().wrapping_add(1), ..setup() @@ -460,9 +464,9 @@ fn a_peer_uid_outside_the_lease_callers_is_refused_and_nothing_is_read() { } #[test] -fn the_configured_uid_outside_the_self_unit_is_refused_and_nothing_is_read() { +fn the_configured_uid_outside_the_configured_unit_is_refused_and_nothing_is_read() { let harness = start(setup()); - harness.run_in("mind-persona@eureka.service", 1); + harness.run_in("other.service", 1); let answer = ask(&harness, 60_000); assert_eq!(refusal_of(&answer), Some(LeaseRefusalKind::UnknownCaller)); assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0); @@ -699,7 +703,7 @@ fn a_readout_answers_the_cells_windows_and_lends_nothing() { } #[test] -fn a_peer_outside_the_lease_callers_still_reads_usage() { +fn a_peer_outside_the_lease_holders_still_reads_usage() { let harness = start(Setup { uid: own_uid().wrapping_add(1), ..setup() @@ -726,3 +730,58 @@ fn a_readout_beside_a_held_lease_leaves_it_held() { assert_eq!(refusal_of(&second), Some(LeaseRefusalKind::Busy)); assert!(granted_ok(&held)); } + +#[test] +fn per_invocation_holder_in_configured_unit_leases_and_other_unit_is_refused() { + let harness = start(Setup { + scope: LeaseScope::PerInvocation, + unit: "agent@alice.service", + ..setup() + }); + harness.run_in("agent@alice.service", 1); + let answer = ask(&harness, 60_000); + assert!(granted_ok(&answer)); + assert_eq!( + granted(&answer).lease_id, + format!("lease:{}:invocation", invocation(1)) + ); + + harness.run_in("other.service", 2); + let refused = ask(&harness, 60_000); + assert_eq!(refusal_of(&refused), Some(LeaseRefusalKind::UnknownCaller)); +} + +#[test] +fn per_caller_and_per_invocation_busy_rules() { + let per_caller = start(Setup { + scope: LeaseScope::PerCaller, + ..setup() + }); + let first = ask(&per_caller, 60_000); + assert!(granted_ok(&first)); + assert_eq!(granted(&first).lease_id, format!("lease:{}", invocation(1))); + per_caller.enter(2); + assert_eq!( + refusal_of(&ask(&per_caller, 60_000)), + Some(LeaseRefusalKind::Busy) + ); + drop(first); + + let per_invocation = start(Setup { + scope: LeaseScope::PerInvocation, + ..setup() + }); + let inv1 = ask(&per_invocation, 60_000); + assert!(granted_ok(&inv1)); + assert_eq!( + refusal_of(&ask(&per_invocation, 60_000)), + Some(LeaseRefusalKind::Busy) + ); + per_invocation.enter(2); + let inv2 = ask(&per_invocation, 60_000); + assert!(granted_ok(&inv2)); + assert_eq!( + granted(&inv2).lease_id, + format!("lease:{}:invocation", invocation(2)) + ); +} diff --git a/crates/claude-connector/tests/lease_run.rs b/crates/claude-connector/tests/lease_run.rs new file mode 100644 index 0000000..f425c0f --- /dev/null +++ b/crates/claude-connector/tests/lease_run.rs @@ -0,0 +1,316 @@ +//! Integration tests for `claude-connector lease run`. +#![cfg(target_os = "linux")] + +use std::io::{self, Read, Write}; +use std::mem::{size_of, zeroed}; +use std::os::fd::{AsRawFd, RawFd}; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::PathBuf; +use std::process::Command; +use std::ptr; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +use claude_connector::{ + LeaseGranted, LeaseMessage, LeaseRefusalKind, LeaseRefused, MAX_LEASE_FRAME_BYTES, + decode_frame, encode_frame, +}; + +static SEQUENCE: AtomicUsize = AtomicUsize::new(0); + +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Self { + let dir = std::env::temp_dir().join(format!( + "claude-lease-run-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::SeqCst) + )); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn path(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn read_request_frame(stream: &mut UnixStream) -> LeaseMessage { + let mut len_buf = [0_u8; 4]; + stream.read_exact(&mut len_buf).unwrap(); + let len = u32::from_be_bytes(len_buf) as usize; + assert!(len > 0 && len <= MAX_LEASE_FRAME_BYTES); + let mut body = vec![0_u8; len]; + stream.read_exact(&mut body).unwrap(); + let mut whole = Vec::with_capacity(4 + len); + whole.extend_from_slice(&len_buf); + whole.extend_from_slice(&body); + decode_frame(&whole).unwrap() +} + +fn send_with_fd(stream: &UnixStream, frame: &[u8], fd: RawFd) -> io::Result<()> { + let fd_size = size_of::() as u32; + // SAFETY: `CMSG_SPACE` is a pure size computation. + let space = unsafe { libc::CMSG_SPACE(fd_size) } as usize; + let mut control = vec![0_u64; space.div_ceil(size_of::())]; + let mut vector = libc::iovec { + iov_base: frame.as_ptr().cast_mut().cast(), + iov_len: frame.len(), + }; + // SAFETY: buffers outlive `sendmsg` and `control` is sized for one fd. + let sent = unsafe { + let mut message: libc::msghdr = zeroed(); + message.msg_iov = &mut vector; + message.msg_iovlen = 1; + message.msg_control = control.as_mut_ptr().cast(); + message.msg_controllen = space as _; + let header = libc::CMSG_FIRSTHDR(&message); + (*header).cmsg_level = libc::SOL_SOCKET; + (*header).cmsg_type = libc::SCM_RIGHTS; + (*header).cmsg_len = libc::CMSG_LEN(fd_size) as _; + ptr::copy_nonoverlapping( + ptr::from_ref(&fd).cast::(), + libc::CMSG_DATA(header), + size_of::(), + ); + libc::sendmsg(stream.as_raw_fd(), &message, libc::MSG_NOSIGNAL) + }; + let Ok(sent) = usize::try_from(sent) else { + return Err(io::Error::last_os_error()); + }; + let mut stream = stream; + stream.write_all(&frame[sent..]) +} + +#[test] +fn fake_lender_fd3_status_and_socket_hold() { + const TOKEN: &str = "sk-canary-lease-run-88f1c"; + let scratch = Scratch::new(); + let socket = scratch.path("lease.sock"); + let listener = UnixListener::bind(&socket).unwrap(); + + let started_flag = scratch.path("child.started"); + let release_flag = scratch.path("lender.checked"); + let token_seen = scratch.path("child.token"); + let eof_seen = Arc::new(AtomicBool::new(false)); + let eof_seen_lender = eof_seen.clone(); + + let lender = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let req = read_request_frame(&mut stream); + assert!(matches!(req, LeaseMessage::ClaudeLeaseRequest(_))); + + let (read_end, mut write_end) = std::io::pipe().unwrap(); + write_end.write_all(TOKEN.as_bytes()).unwrap(); + drop(write_end); + + let frame = encode_frame(&LeaseMessage::ClaudeLeaseGrant(LeaseGranted { + lease_id: "lease:test-run".to_string(), + plan_quota: vec![], + })); + send_with_fd(&stream, &frame, read_end.as_raw_fd()).unwrap(); + drop(read_end); + + let mut buf = [0_u8; 16]; + loop { + match stream.read(&mut buf) { + Ok(0) | Err(_) => { + eof_seen_lender.store(true, Ordering::Release); + break; + } + Ok(_) => {} + } + } + }); + + // Child reads fd 3, checks env/cmdline do not hold the token, signals startup, + // waits for the test thread to assert the lender socket is still open, and exits 42. + let script = format!( + r#"set -eu +test "${{CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR:-}}" = "3" +tok=$(cat <&3) +printf '%s' "$tok" > "{token_seen}" +if env | grep -qF "{TOKEN}"; then exit 91; fi +if tr '\0' '\n' < /proc/self/cmdline | grep -qF "{TOKEN}"; then exit 92; fi +: > "{started_flag}" +i=0 +while [ ! -e "{release_flag}" ]; do + i=$((i + 1)) + if [ "$i" -gt 200 ]; then exit 93; fi + sleep 0.05 +done +exit 42 +"#, + token_seen = token_seen.display(), + started_flag = started_flag.display(), + release_flag = release_flag.display(), + ); + + let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args([ + "lease", + "run", + "--socket", + socket.to_str().unwrap(), + "--", + "/bin/sh", + "-c", + &script, + ]) + .env("KEEP_INHERITED", "yes") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let deadline = Instant::now() + Duration::from_secs(10); + while !started_flag.exists() { + if let Some(status) = child.try_wait().unwrap() { + let _ = UnixStream::connect(&socket); + panic!("leased child exited early before starting: {status:?}"); + } + assert!(Instant::now() < deadline, "leased child never started"); + std::thread::sleep(Duration::from_millis(20)); + } + assert!( + !eof_seen.load(Ordering::Acquire), + "lender saw EOF while leased child was still running" + ); + std::fs::write(&release_flag, b"ok").unwrap(); + + let output = child.wait_with_output().unwrap(); + assert_eq!(output.status.code(), Some(42), "{output:?}"); + assert_eq!(std::fs::read_to_string(&token_seen).unwrap(), TOKEN); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!stderr.contains(TOKEN), "{stderr}"); + + lender.join().unwrap(); + assert!( + eof_seen.load(Ordering::Acquire), + "lender did not see EOF after child exited" + ); +} + +#[test] +fn refused_busy_and_unknown_caller_do_not_spawn() { + const CANARY_DETAIL: &str = "CANARY-REFUSAL-DETAIL-7f3a"; + for kind in [LeaseRefusalKind::Busy, LeaseRefusalKind::UnknownCaller] { + let scratch = Scratch::new(); + let socket = scratch.path("lease.sock"); + let spawned_marker = scratch.path("should-not-exist"); + let listener = UnixListener::bind(&socket).unwrap(); + let handled = Arc::new(AtomicBool::new(false)); + let handled_lender = handled.clone(); + + let lender = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + if handled_lender.load(Ordering::Acquire) { + return; + } + let req = read_request_frame(&mut stream); + assert!(matches!(req, LeaseMessage::ClaudeLeaseRequest(_))); + let frame = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused { + kind, + detail: CANARY_DETAIL.to_string(), + })); + stream.write_all(&frame).unwrap(); + handled_lender.store(true, Ordering::Release); + }); + + let output = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args([ + "lease", + "run", + "--socket", + socket.to_str().unwrap(), + "--", + "/bin/sh", + "-c", + &format!("touch '{}'", spawned_marker.display()), + ]) + .output() + .unwrap(); + + if !handled.load(Ordering::Acquire) { + handled.store(true, Ordering::Release); + let _ = UnixStream::connect(&socket); + } + lender.join().unwrap(); + assert!(!output.status.success(), "{kind:?}: {output:?}"); + assert!( + !spawned_marker.exists(), + "{kind:?}: child spawned on refusal" + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!stderr.contains(CANARY_DETAIL), "{kind:?}: {stderr}"); + } +} + +#[test] +fn signal_exit_maps_to_128_plus_signal_and_bad_cli_args_fail() { + let scratch = Scratch::new(); + let socket = scratch.path("lease.sock"); + let listener = UnixListener::bind(&socket).unwrap(); + let lender = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let req = read_request_frame(&mut stream); + assert!(matches!(req, LeaseMessage::ClaudeLeaseRequest(_))); + let (read_end, mut write_end) = std::io::pipe().unwrap(); + write_end.write_all(b"sk-signal-test").unwrap(); + drop(write_end); + let frame = encode_frame(&LeaseMessage::ClaudeLeaseGrant(LeaseGranted { + lease_id: "lease:signal".to_string(), + plan_quota: vec![], + })); + send_with_fd(&stream, &frame, read_end.as_raw_fd()).unwrap(); + drop(read_end); + let mut buf = [0_u8; 16]; + while matches!(stream.read(&mut buf), Ok(n) if n > 0) {} + }); + + let output = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args([ + "lease", + "run", + "--socket", + socket.to_str().unwrap(), + "--", + "/bin/sh", + "-c", + "kill -KILL $$", + ]) + .output() + .unwrap(); + lender.join().unwrap(); + assert_eq!(output.status.code(), Some(128 + 9), "{output:?}"); + + let sock = socket.to_str().unwrap(); + for bad in [ + vec!["lease", "run", "--socket", sock], + vec!["lease", "run", "--socket", sock, "--"], + vec![ + "lease", + "run", + "--socket", + sock, + "--ttl-secs", + "0", + "--", + "/bin/true", + ], + ] { + let out = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args(&bad) + .output() + .unwrap(); + assert!(!out.status.success(), "{bad:?}: {out:?}"); + } +} diff --git a/crates/model-connector/src/fixtures.rs b/crates/model-connector/src/fixtures.rs index 19ab522..3474b95 100644 --- a/crates/model-connector/src/fixtures.rs +++ b/crates/model-connector/src/fixtures.rs @@ -171,11 +171,16 @@ pub(crate) fn caller( .unwrap() } +#[cfg(feature = "daemon")] +pub(crate) fn routes() -> crate::ProviderRoutes { + crate::ProviderRoutes::new([("gpt-5.4".to_string(), "fixture-sse".to_string())]).unwrap() +} + #[cfg(feature = "daemon")] pub(crate) fn open_service(store: &TestStore, max_concurrent_requests: usize) -> TransportService { TransportService::open( &store.path, - "fixture-sse", + routes(), [ caller( "epiphany-yggdrasil", diff --git a/crates/model-connector/src/serve.rs b/crates/model-connector/src/serve.rs index 2c2ac91..0dba9c2 100644 --- a/crates/model-connector/src/serve.rs +++ b/crates/model-connector/src/serve.rs @@ -18,26 +18,24 @@ use crate::envelope::{ }; use crate::readout::PlanQuotaSnapshot; use crate::service::{ - CallerAdmission, ProviderCall, TransportAdmission, TransportService, distinct_admissions, + CallerAdmission, ProviderCall, ProviderRoutes, TransportAdmission, TransportService, + distinct_admissions, }; -/// The only provider seam of the connector kit. A connector binary implements -/// it over one model provider; the kit names no provider. +/// The provider seam of the connector kit. A connector binary implements +/// it over one or more model routes; the kit derives the provider tag per +/// model from [`ProviderRoutes`]. pub trait ProviderBackend: Send + Sync { /// Whether the provider can take work; `Err` names the backend field that /// is not ready, never a value. `serve` consults it once, before it opens /// the replay store or accepts a connection; the request path does not /// consult it. fn ready(&self) -> Result<(), &'static str>; - /// The tag of the provider this backend fronts. The service owns it from - /// `serve` on: it names the provider on every receipt and decides which - /// reasoning state is foreign. - fn provider(&self) -> &str; - /// What the provider's own plan allows and has used, for the usage - /// readout and the provider's own refusals. A provider with no plan to report - /// keeps the default. - fn plan_quota(&self) -> PlanQuotaSnapshot { - PlanQuotaSnapshot::default() + /// What one provider's own plan allows and has used together with that + /// provider's tag, for the usage readout and that provider's own refusals. + /// A backend with no plan to report keeps `None`. + fn plan_quota(&self) -> Option<(&str, PlanQuotaSnapshot)> { + None } /// Executes one admitted call. The service has already bound it to its /// caller and recorded its replay claim. The call cannot show a foreign @@ -158,13 +156,14 @@ pub fn serve( limits: ServeLimits, admissions: Vec, replay_store: &Path, + routes: ProviderRoutes, backend: Arc, ) -> Result<(), ServeError> { limits.validate(&admissions)?; admit_listener(&listener, backend.as_ref())?; let service = Arc::new(Mutex::new(TransportService::open( replay_store, - backend.provider(), + routes, admissions, limits.max_expiry_skew_ms, )?)); @@ -172,7 +171,7 @@ pub fn serve( } /// `serve` over a service the caller opened and keeps a handle to, so another -/// front of the same service (the Self-run credential lease) shares its +/// front of the same service (the credential lease) shares its /// replay store and plan. The limits must already have been validated against the /// service's admissions. pub fn serve_service( @@ -261,7 +260,10 @@ fn answer_frame( let envelope = match decode_request_frame(request).map_err(|_| ServeError::FrameEncoding)? { RequestFrame::Invoke(envelope) => envelope, RequestFrame::UsageReadout(envelope) => { - let plan = backend.plan_quota(); + let plan = backend + .plan_quota() + .map(|(_, snapshot)| snapshot) + .unwrap_or_default(); let response = service .lock() .map_err(|_| ServeError::ServicePoisoned)? @@ -270,13 +272,15 @@ fn answer_frame( .map_err(|_| ServeError::FrameEncoding); } }; + let plan = backend.plan_quota(); let admission = service .lock() .map_err(|_| ServeError::ServicePoisoned)? .begin( &envelope, unix_ms()?, - &backend.plan_quota(), + plan.as_ref() + .map(|(provider, snapshot)| (*provider, snapshot)), limits.max_frame_bytes, )?; let response = match admission { @@ -382,7 +386,7 @@ mod tests { FailureKind, Refusal, TransportDisposition, TransportEvent, TransportEventPayload, TransportInvocation, TransportOutcome, TransportResult, }; - use crate::fixtures::{TestStore, caller, invocation_for, receipt, request}; + use crate::fixtures::{TestStore, caller, invocation_for, receipt, request, routes}; const CALLER: &str = "epiphany-yggdrasil"; const KEY: &str = "epiphany-distinct-test-key"; @@ -412,10 +416,6 @@ mod tests { self.ready.then_some(()).ok_or("fixture") } - fn provider(&self) -> &str { - "fixture-sse" - } - fn execute(&self, call: &ProviderCall) -> TransportResult { self.executions.fetch_add(1, Ordering::SeqCst); call.transported( @@ -458,7 +458,14 @@ mod tests { let (sender, receiver) = std::sync::mpsc::channel(); let path = path.to_path_buf(); thread::spawn(move || { - let _ = sender.send(serve(listener, limits, admissions, &path, backend)); + let _ = sender.send(serve( + listener, + limits, + admissions, + &path, + routes(), + backend, + )); }); receiver.recv_timeout(Duration::from_secs(2)).ok() } @@ -484,7 +491,7 @@ mod tests { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let endpoint = listener.local_addr().unwrap(); let path = store.path.clone(); - thread::spawn(move || serve(listener, limits(), admissions, &path, backend)); + thread::spawn(move || serve(listener, limits(), admissions, &path, routes(), backend)); let client = ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap(); (client, endpoint) @@ -509,6 +516,7 @@ mod tests { /// A counting backend that reports a plan, as a provider with one would. struct PlanBackend { inner: Arc, + provider: &'static str, plan: PlanQuotaSnapshot, } @@ -517,12 +525,8 @@ mod tests { self.inner.ready() } - fn provider(&self) -> &str { - self.inner.provider() - } - - fn plan_quota(&self) -> PlanQuotaSnapshot { - self.plan.clone() + fn plan_quota(&self) -> Option<(&str, PlanQuotaSnapshot)> { + Some((self.provider, self.plan.clone())) } fn execute(&self, call: &ProviderCall) -> TransportResult { @@ -545,6 +549,7 @@ mod tests { }; let backend = Arc::new(PlanBackend { inner: inner.clone(), + provider: "fixture-sse", plan: plan.clone(), }); let (client, endpoint) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]); @@ -572,6 +577,11 @@ mod tests { assert!(stranger.usage_readout(CALLER).is_err()); } + #[test] + fn plan_quota_defaults_to_none() { + assert_eq!(CountingBackend::new(true).plan_quota(), None); + } + #[test] fn a_backend_with_no_plan_reads_out_none() { let store = TestStore::new(); @@ -598,6 +608,7 @@ mod tests { let inner = CountingBackend::new(true); let backend = Arc::new(PlanBackend { inner: inner.clone(), + provider: "fixture-sse", plan: window_plan(1_000, "rejected", now_ms() + 3_600_000), }); let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]); @@ -609,12 +620,31 @@ mod tests { assert_eq!(inner.executions.load(Ordering::SeqCst), 0); } + #[test] + fn serve_rejecting_plan_only_refuses_owning_route() { + let store = TestStore::new(); + let inner = CountingBackend::new(true); + let backend = Arc::new(PlanBackend { + inner: inner.clone(), + provider: "other-provider", + plan: window_plan(1_000, "rejected", now_ms() + 3_600_000), + }); + let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]); + let admitted = client.execute(&fresh("request-other-plan")).unwrap(); + assert!(matches!( + admitted.disposition, + TransportDisposition::Transported { .. } + )); + assert_eq!(inner.executions.load(Ordering::SeqCst), 1); + } + #[test] fn serve_admits_a_full_window_the_provider_still_allows() { let store = TestStore::new(); let inner = CountingBackend::new(true); let backend = Arc::new(PlanBackend { inner: inner.clone(), + provider: "fixture-sse", plan: window_plan(999, "allowed", now_ms() + 3_600_000), }); let (client, _) = start_with(backend, &store, vec![caller(CALLER, KEY, 4)]); @@ -743,19 +773,14 @@ mod tests { // The wide completion goes straight through the service: serve holds // the replay store for as long as it runs, so a second serve cannot // open it while the first lives. - let mut service = TransportService::open( - &store.path, - "fixture-sse", - vec![caller(CALLER, KEY, 4)], - 300_000, - ) - .unwrap(); + let mut service = + TransportService::open(&store.path, routes(), vec![caller(CALLER, KEY, 4)], 300_000) + .unwrap(); let envelope = crate::envelope::encrypt_invocation(&invocation, &crate::fixtures::security(KEY)) .unwrap(); - let TransportAdmission::Execute(claim) = service - .begin(&envelope, now_ms(), &PlanQuotaSnapshot::default(), 1 << 20) - .unwrap() + let TransportAdmission::Execute(claim) = + service.begin(&envelope, now_ms(), None, 1 << 20).unwrap() else { panic!("a fresh request must execute"); }; @@ -779,6 +804,7 @@ mod tests { narrowed, vec![caller(CALLER, KEY, 4)], &path, + routes(), served, ) }); @@ -1077,7 +1103,7 @@ mod tests { ..limits() }; let admissions = vec![admission(CALLER, KEY, 4, bound)]; - thread::spawn(move || serve(listener, tight, admissions, &path, served)); + thread::spawn(move || serve(listener, tight, admissions, &path, routes(), served)); let client = ConnectorClient::new(endpoint, KEY, frame, Some(Duration::from_secs(5))).unwrap(); let reply = client.execute(&invocation).unwrap(); @@ -1129,10 +1155,6 @@ mod tests { Ok(()) } - fn provider(&self) -> &str { - "fixture-sse" - } - fn execute(&self, call: &ProviderCall) -> TransportResult { self.executions.fetch_add(1, Ordering::SeqCst); sized_result(call, self.text_len) @@ -1189,21 +1211,16 @@ mod tests { /// The encoded size of a result carrying no text, for this request id. fn empty_result_len(request_id: &str) -> usize { let store = TestStore::new(); - let mut service = TransportService::open( - &store.path, - "fixture-sse", - vec![caller(CALLER, KEY, 4)], - 300_000, - ) - .unwrap(); + let mut service = + TransportService::open(&store.path, routes(), vec![caller(CALLER, KEY, 4)], 300_000) + .unwrap(); let envelope = crate::envelope::encrypt_invocation( &fresh(request_id), &crate::fixtures::security(KEY), ) .unwrap(); - let TransportAdmission::Execute(claim) = service - .begin(&envelope, now_ms(), &PlanQuotaSnapshot::default(), 1 << 20) - .unwrap() + let TransportAdmission::Execute(claim) = + service.begin(&envelope, now_ms(), None, 1 << 20).unwrap() else { panic!("a fresh request must execute"); }; @@ -1294,7 +1311,7 @@ mod tests { let service = Arc::new(Mutex::new( TransportService::open( &store.path, - "fixture-sse", + routes(), vec![caller(CALLER, KEY, 4)], 300_000, ) @@ -1352,7 +1369,7 @@ mod tests { let backend = CountingBackend::new(true); let path = store.path.clone(); let served = backend.clone(); - thread::spawn(move || serve(listener, limits(), admissions, &path, served)); + thread::spawn(move || serve(listener, limits(), admissions, &path, routes(), served)); let client = ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap(); client.execute(&fresh("request-key")).unwrap(); diff --git a/crates/model-connector/src/service.rs b/crates/model-connector/src/service.rs index 5fe2db8..d065393 100644 --- a/crates/model-connector/src/service.rs +++ b/crates/model-connector/src/service.rs @@ -1,4 +1,4 @@ -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::Path; use cultcache_rs::{CacheBackingStore, CultCache, DatabaseEntry, OwnedRedbMessagePackBackingStore}; @@ -13,8 +13,8 @@ use crate::contract::{ }; use crate::envelope::{ EnvelopeKind, MAX_IDENTITY_BYTES, ServiceError, TransportEnvelope, decrypt_invocation, - decrypt_usage_readout_request, encode_result_frame, encode_usage_readout_response_frame, - encrypt_result, encrypt_usage_readout, validate_envelope, + decrypt_result, decrypt_usage_readout_request, encode_result_frame, + encode_usage_readout_response_frame, encrypt_result, encrypt_usage_readout, validate_envelope, }; use crate::readout::{PlanQuotaSnapshot, UsageReadout}; @@ -104,16 +104,26 @@ const REJECTED: &str = "rejected"; /// `rejected` and its own reset lies in the future. The one usage-derived /// refusal there is. It repeats the provider's word with the provider's /// expiry, and no utilization figure is ever compared to anything. -pub(crate) fn provider_rejects(plan: &PlanQuotaSnapshot, now_unix_ms: u64) -> bool { +pub(crate) fn plan_rejects(plan: &PlanQuotaSnapshot, now_unix_ms: u64) -> bool { plan.windows .iter() .any(|window| window.status == REJECTED && window.resets_at_unix_ms > now_unix_ms) } -/// A Self run's or Persona turn's credential lease while its holder keeps it. +/// Whether the invoked model's routed provider is refusing right now: `plan` +/// names that provider as its owner and reports an unexpired `rejected` window. +pub(crate) fn provider_rejects( + plan: Option<(&str, &PlanQuotaSnapshot)>, + provider: &str, + now_unix_ms: u64, +) -> bool { + matches!(plan, Some((owner, snapshot)) if owner == provider && plan_rejects(snapshot, now_unix_ms)) +} + +/// A credential lease while its holder keeps it. #[derive(Debug, Clone, Copy)] struct LiveLease { - turn: LeaseTurn, + scope: LeaseScope, expires_at_unix_ms: u64, } @@ -217,6 +227,45 @@ pub enum TransportAdmission { Reply(TransportEnvelope), } +/// Validated model-id to provider-tag table for [`TransportService`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProviderRoutes { + routes: BTreeMap, +} + +impl ProviderRoutes { + pub fn new(routes: impl IntoIterator) -> Result { + let mut validated = BTreeMap::new(); + for (model, provider) in routes { + if require_id(&model, "model").is_err() + || model.len() > MAX_IDENTITY_BYTES + || require_id(&provider, "provider").is_err() + || provider.len() > MAX_IDENTITY_BYTES + || provider == STAND_IN_PROVIDER + { + return Err(ServiceError::InvalidAdmission); + } + match validated.get(&model) { + Some(existing) if existing != &provider => { + return Err(ServiceError::InvalidAdmission); + } + Some(_) => {} + None => { + validated.insert(model, provider); + } + } + } + if validated.is_empty() { + return Err(ServiceError::InvalidAdmission); + } + Ok(Self { routes: validated }) + } + + pub fn provider_for(&self, model: &str) -> Option<&str> { + self.routes.get(model).map(String::as_str) + } +} + pub struct TransportService { callers: HashMap, /// The requests between claim and completion. @@ -227,22 +276,22 @@ pub struct TransportService { leases: HashMap, replay_store: CultCache, max_expiry_skew_ms: u64, - provider: String, + routes: ProviderRoutes, } impl TransportService { - /// `provider` is the tag of the backend this service fronts. The service - /// owns it from here on: it decides which reasoning state is foreign and + /// `routes` maps every served model id to the provider tag the service + /// owns from here on: it decides which reasoning state is foreign and /// what provider every receipt names. pub fn open( replay_store_path: &Path, - provider: &str, + routes: ProviderRoutes, admissions: impl IntoIterator, max_expiry_skew_ms: u64, ) -> Result { Self::with_store( OwnedRedbMessagePackBackingStore::new(replay_store_path).map_err(replay_store_error)?, - provider, + routes, admissions, max_expiry_skew_ms, ) @@ -251,14 +300,11 @@ impl TransportService { /// `open` over any backing store, so a test can inject one that fails. pub fn with_store( store: impl CacheBackingStore + 'static, - provider: &str, + routes: ProviderRoutes, admissions: impl IntoIterator, max_expiry_skew_ms: u64, ) -> Result { - if max_expiry_skew_ms == 0 - || require_id(provider, "provider").is_err() - || provider == STAND_IN_PROVIDER - { + if max_expiry_skew_ms == 0 { return Err(ServiceError::InvalidAdmission); } let admissions: Vec = admissions.into_iter().collect(); @@ -311,7 +357,7 @@ impl TransportService { leases: HashMap::new(), replay_store, max_expiry_skew_ms, - provider: provider.to_string(), + routes, }) } @@ -358,7 +404,7 @@ impl TransportService { &mut self, envelope: &TransportEnvelope, now_unix_ms: u64, - plan: &PlanQuotaSnapshot, + plan: Option<(&str, &PlanQuotaSnapshot)>, max_frame_bytes: usize, ) -> Result { validate_envelope(envelope, EnvelopeKind::Invocation)?; @@ -369,7 +415,10 @@ impl TransportService { let security = caller.security.clone(); let max_concurrent_requests = caller.max_concurrent_requests; let connection_key_epoch = caller.connection_key_epoch; + let max_payload_bytes = caller.max_payload_bytes; + let max_output_tokens = caller.max_output_tokens; let invocation = decrypt_invocation(envelope, &security)?; + let model_allowed = caller.allowed_models.contains(&invocation.request.model); if envelope.request_id.len() > MAX_IDENTITY_BYTES { let refusal = encrypt_result( &TransportResult::refused(&invocation, Refusal::Malformed), @@ -381,23 +430,12 @@ impl TransportService { Err(ServiceError::FrameBound) }; } - if envelope.ciphertext.len() > caller.max_payload_bytes { + if envelope.ciphertext.len() > max_payload_bytes { return self.reply_refusal(&invocation, Refusal::PayloadBound, &security); } if let Err(error) = invocation.validate(now_unix_ms, self.max_expiry_skew_ms) { return self.reply_refusal(&invocation, contract_refusal(&error), &security); } - if !caller.allowed_models.contains(&invocation.request.model) { - return self.reply_refusal(&invocation, Refusal::ModelNotAllowed, &security); - } - if invocation.request.max_output_tokens > caller.max_output_tokens { - return self.reply_refusal(&invocation, Refusal::OutputBound, &security); - } - let (request, foreign_reasoning_dropped) = - match partition_reasoning(&invocation.request, &self.provider) { - Ok(partition) => partition, - Err(refusal) => return self.reply_refusal(&invocation, refusal, &security), - }; let identity = RequestIdentity { caller_runtime_id: invocation.caller_runtime_id.clone(), request_id: invocation.request_id().to_string(), @@ -417,11 +455,21 @@ impl TransportService { if fits_frame(response, max_frame_bytes)? { return Ok(TransportAdmission::Reply(response.clone())); } - let stand_in = self.seal_stand_in( + let foreign_reasoning_dropped = + match decrypt_result(response, &security, &invocation)?.disposition { + TransportDisposition::Transported { receipt, .. } => { + receipt.foreign_reasoning_dropped + } + TransportDisposition::Refused(_) => { + return Err(ServiceError::InvalidReplayRecord); + } + }; + let stand_in = seal_stand_in( &invocation, &security, max_frame_bytes, FailureKind::ResultSize, + foreign_reasoning_dropped, )?; self.replay_store .put( @@ -446,9 +494,24 @@ impl TransportService { } }; } + let Some(provider) = model_allowed + .then(|| self.routes.provider_for(&invocation.request.model)) + .flatten() + .map(str::to_string) + else { + return self.reply_refusal(&invocation, Refusal::ModelNotAllowed, &security); + }; + if invocation.request.max_output_tokens > max_output_tokens { + return self.reply_refusal(&invocation, Refusal::OutputBound, &security); + } + let (request, foreign_reasoning_dropped) = + match partition_reasoning(&invocation.request, &provider) { + Ok(partition) => partition, + Err(refusal) => return self.reply_refusal(&invocation, refusal, &security), + }; // The provider's own refusal binds new work only: a request already // recorded is answered whatever the provider says now. - if provider_rejects(plan, now_unix_ms) { + if provider_rejects(plan, &provider, now_unix_ms) { return self.reply_refusal(&invocation, Refusal::ProviderRejected, &security); } if self @@ -484,7 +547,7 @@ impl TransportService { native_request_sha256: invocation.native_request_sha256, provider_request_sha256: invocation.provider_request_sha256, model: invocation.request.model.clone(), - provider: self.provider.clone(), + provider, foreign_reasoning_dropped, // Replaced by the backend's outcome in `transported`. outcome: TransportOutcome::Failed { @@ -535,6 +598,7 @@ impl TransportService { .ok_or(ServiceError::CallerNotAdmitted)?; let security = caller.security.clone(); let connection_key_epoch = caller.connection_key_epoch; + let foreign_reasoning_dropped = claim.call.receipt.foreign_reasoning_dropped; // A result the service refuses (not a transported result, not bound to // this invocation, or carrying a provider tag or drop count the call // did not derive) is answered like an oversized one: a typed failure @@ -550,22 +614,24 @@ impl TransportService { // Nothing is recorded when even the stand-in cannot be // carried, but the caller's slot is not held by a request // that can no longer finish. - self.seal_stand_in( + seal_stand_in( invocation, &security, max_frame_bytes, FailureKind::ResultSize, + foreign_reasoning_dropped, ) .inspect_err(|_| { self.live.remove(&identity); })? } } else { - self.seal_stand_in( + seal_stand_in( invocation, &security, max_frame_bytes, FailureKind::Provider, + foreign_reasoning_dropped, ) .inspect_err(|_| { self.live.remove(&identity); @@ -594,36 +660,6 @@ impl TransportService { Ok(response) } - /// The `result_size` failure sealed for `invocation`, if it fits the frame. - fn seal_stand_in( - &self, - invocation: &TransportInvocation, - security: &TransportKey, - max_frame_bytes: usize, - kind: FailureKind, - ) -> Result { - let (_, foreign_reasoning_dropped) = - partition_reasoning(&invocation.request, &self.provider) - .map_err(|_| ServiceError::InvalidCompletion)?; - let stand_in = encrypt_result( - &stand_in_failure( - &invocation.caller_runtime_id, - invocation.request_id(), - &invocation.request.model, - invocation.native_request_sha256, - invocation.provider_request_sha256, - foreign_reasoning_dropped, - kind, - ), - security, - )?; - if fits_frame(&stand_in, max_frame_bytes)? { - Ok(stand_in) - } else { - Err(ServiceError::FrameBound) - } - } - /// Whether `result` is the answer to this claim's call: transported, /// bound to the caller's invocation, and carrying the provider tag and /// drop count the service derived. @@ -631,8 +667,11 @@ impl TransportService { let TransportDisposition::Transported { receipt, .. } = &result.disposition else { return false; }; + let Some(provider) = self.routes.provider_for(&claim.invocation.request.model) else { + return false; + }; result.validate_against(&claim.invocation).is_ok() - && receipt.provider == self.provider + && receipt.provider == provider && receipt.foreign_reasoning_dropped == claim.call.receipt.foreign_reasoning_dropped } @@ -649,6 +688,35 @@ impl TransportService { } } +/// The `result_size` or `provider` stand-in failure sealed for `invocation`, if +/// it fits the frame, carrying the already-derived drop count without +/// re-consulting live routes. +fn seal_stand_in( + invocation: &TransportInvocation, + security: &TransportKey, + max_frame_bytes: usize, + kind: FailureKind, + foreign_reasoning_dropped: u32, +) -> Result { + let stand_in = encrypt_result( + &stand_in_failure( + &invocation.caller_runtime_id, + invocation.request_id(), + &invocation.request.model, + invocation.native_request_sha256, + invocation.provider_request_sha256, + foreign_reasoning_dropped, + kind, + ), + security, + )?; + if fits_frame(&stand_in, max_frame_bytes)? { + Ok(stand_in) + } else { + Err(ServiceError::FrameBound) + } +} + fn fits_frame(envelope: &TransportEnvelope, max_frame_bytes: usize) -> Result { encode_result_frame(envelope).map(|bytes| bytes.len() <= max_frame_bytes) } @@ -779,7 +847,7 @@ fn replay_store_error(error: impl std::fmt::Display) -> ServiceError { } mod lease; -pub use lease::{LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseTurn}; +pub use lease::{LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseScope}; fn contract_refusal(error: &ContractError) -> Refusal { match error { @@ -804,7 +872,7 @@ mod tests { assert!(matches!( TransportService::open( &store.path, - "fixture-sse", + routes(), [ caller("epiphany-yggdrasil", "shared-key", 1), caller("ghostlight-yggdrasil", "shared-key", 1), @@ -1007,7 +1075,7 @@ mod tests { assert!(matches!( TransportService::open( &store.path, - "fixture-sse", + routes(), [CallerAdmission::new( "epiphany-yggdrasil", "rotated-connection-key", @@ -1119,7 +1187,7 @@ mod tests { 32_768, ) .unwrap(); - TransportService::open(&store.path, "fixture-sse", [admission], 5_000) + TransportService::open(&store.path, routes(), [admission], 5_000) .unwrap() .begin_unplanned(&envelope, 1_000, FRAME) }; @@ -1191,7 +1259,7 @@ mod tests { assert!( TransportService::open( &control.path, - "fixture-sse", + routes(), [caller(CALLER, KEY, 1)], 5_000 ) @@ -1216,7 +1284,7 @@ mod tests { matches!( TransportService::open( &store.path, - "fixture-sse", + routes(), [caller(CALLER, KEY, 1)], 5_000 ), @@ -1749,19 +1817,45 @@ mod tests { #[test] fn open_refuses_a_blank_or_stand_in_provider_tag() { - let store = TestStore::new(); - for tag in ["", " ", STAND_IN_PROVIDER] { + assert!(matches!( + ProviderRoutes::new(Vec::<(String, String)>::new()), + Err(ServiceError::InvalidAdmission) + )); + let over = "x".repeat(MAX_IDENTITY_BYTES + 1); + for bad_model in ["", " ", " gpt-5.4", "gpt-5.4 ", over.as_str()] { assert!( matches!( - TransportService::open(&store.path, tag, [caller(CALLER, KEY, 1)], 5_000), + ProviderRoutes::new([(bad_model.to_string(), "fixture-sse".to_string())]), Err(ServiceError::InvalidAdmission) ), - "{tag:?}" + "bad model {bad_model:?}" ); } + for bad_tag in ["", " ", " p", "p ", STAND_IN_PROVIDER, over.as_str()] { + assert!( + matches!( + ProviderRoutes::new([("gpt-5.4".to_string(), bad_tag.to_string())]), + Err(ServiceError::InvalidAdmission) + ), + "bad provider {bad_tag:?}" + ); + } + assert!(matches!( + ProviderRoutes::new([ + ("gpt-5.4".to_string(), "p".to_string()), + ("gpt-5.4".to_string(), "q".to_string()), + ]), + Err(ServiceError::InvalidAdmission) + )); + let max = "x".repeat(MAX_IDENTITY_BYTES); + let deduped = + ProviderRoutes::new([(max.clone(), max.clone()), (max.clone(), max.clone())]).unwrap(); + assert_eq!(deduped.provider_for(&max), Some(max.as_str())); + assert_eq!(deduped.provider_for("missing"), None); + + let store = TestStore::new(); assert!( - TransportService::open(&store.path, "fixture-sse", [caller(CALLER, KEY, 1)], 5_000) - .is_ok() + TransportService::open(&store.path, routes(), [caller(CALLER, KEY, 1)], 5_000).is_ok() ); } @@ -1920,12 +2014,7 @@ mod tests { now_unix_ms: u64, max_frame_bytes: usize, ) -> Result { - self.begin( - envelope, - now_unix_ms, - &PlanQuotaSnapshot::default(), - max_frame_bytes, - ) + self.begin(envelope, now_unix_ms, None, max_frame_bytes) } } @@ -1945,7 +2034,7 @@ mod tests { service: &mut TransportService, request_id: &str, now: u64, - plan: &PlanQuotaSnapshot, + plan: Option<(&str, &PlanQuotaSnapshot)>, ) -> (TransportAdmission, TransportInvocation) { let mut request = invocation_for(CALLER, request_id).request; request.request_id = request_id.to_string(); @@ -1974,12 +2063,23 @@ mod tests { let store = TestStore::new(); let mut service = open_service(&store, 4); let rejected = plan_of(1_000, "rejected", 10_000); - let (refused, invocation) = begin_under(&mut service, "request-1", 9_999, &rejected); + let (refused, invocation) = begin_under( + &mut service, + "request-1", + 9_999, + Some(("fixture-sse", &rejected)), + ); assert_eq!(refusal_of(refused, &invocation), Refusal::ProviderRejected); // At the provider's own reset the refusal lifts, and it was never // recorded: the same id is admitted. assert!(matches!( - begin_under(&mut service, "request-1", 10_000, &rejected).0, + begin_under( + &mut service, + "request-1", + 10_000, + Some(("fixture-sse", &rejected)), + ) + .0, TransportAdmission::Execute(_) )); } @@ -1991,7 +2091,13 @@ mod tests { for (n, status) in ["allowed", "allowed_warning"].into_iter().enumerate() { let plan = plan_of(999, status, 1_000_000); assert!(matches!( - begin_under(&mut service, &format!("request-{n}"), 1_000, &plan).0, + begin_under( + &mut service, + &format!("request-{n}"), + 1_000, + Some(("fixture-sse", &plan)), + ) + .0, TransportAdmission::Execute(_) )); } @@ -2006,7 +2112,12 @@ mod tests { let answer = service.complete(*claim, result, FRAME).unwrap(); let rejected = plan_of(1_000, "rejected", 1_000_000); let again = service - .begin(&raw_envelope(&invocation), 1_000, &rejected, FRAME) + .begin( + &raw_envelope(&invocation), + 1_000, + Some(("fixture-sse", &rejected)), + FRAME, + ) .unwrap(); assert_eq!(again, TransportAdmission::Reply(answer)); } @@ -2045,7 +2156,7 @@ mod tests { .unwrap(); } assert!(matches!( - TransportService::open(&store.path, "fixture-sse", [caller(CALLER, KEY, 1)], 5_000), + TransportService::open(&store.path, routes(), [caller(CALLER, KEY, 1)], 5_000), Err(ServiceError::ReplayStore(_)) )); } @@ -2144,8 +2255,7 @@ mod tests { let store = FlakyStore::new(0); let allowance = store.allowance(); let mut service = - TransportService::with_store(store, "fixture-sse", [caller(CALLER, KEY, 1)], 5_000) - .unwrap(); + TransportService::with_store(store, routes(), [caller(CALLER, KEY, 1)], 5_000).unwrap(); let invocation = invocation_for(CALLER, "request-1"); assert!(matches!( service.begin_unplanned(&raw_envelope(&invocation), 1_000, FRAME), @@ -2163,8 +2273,7 @@ mod tests { let store = FlakyStore::new(1); let allowance = store.allowance(); let mut service = - TransportService::with_store(store, "fixture-sse", [caller(CALLER, KEY, 1)], 5_000) - .unwrap(); + TransportService::with_store(store, routes(), [caller(CALLER, KEY, 1)], 5_000).unwrap(); let (claim, invocation) = claim_for(&mut service, "request-1"); let result = text_result(claim.call(), "done"); assert!(matches!( @@ -2180,4 +2289,492 @@ mod tests { assert_eq!(refusal_of(again, &invocation), Refusal::Indeterminate); let _ = claim_for(&mut service, "request-2"); } + + fn two_route_service(store: &TestStore, max_concurrent_requests: usize) -> TransportService { + let routes = ProviderRoutes::new([ + ("model-a".to_string(), "p".to_string()), + ("model-b".to_string(), "q".to_string()), + ]) + .unwrap(); + let admission = CallerAdmission::new( + CALLER, + KEY, + 1, + ["model-a".to_string(), "model-b".to_string()], + max_concurrent_requests, + 64 * 1024, + 32_768, + ) + .unwrap(); + TransportService::open(&store.path, routes, [admission], 5_000).unwrap() + } + + fn invocation_for_model( + request_id: &str, + model: &str, + now_unix_ms: u64, + input: Vec, + ) -> TransportInvocation { + let mut request = invocation_for(CALLER, request_id).request; + request.model = model.to_string(); + request.input = input; + TransportInvocation::new(CALLER, now_unix_ms + 1_000, [7; 32], request).unwrap() + } + + #[test] + fn foreign_reasoning_across_routes_p_and_q() { + let store = TestStore::new(); + let mut service = two_route_service(&store, 1); + + let foreign_in_flight = invocation_for_model( + "in-flight-q-on-a", + "model-a", + 1_000, + vec![user("turn"), state("q", "model-b", 1)], + ); + let refused = service + .begin_unplanned(&raw_envelope(&foreign_in_flight), 1_000, FRAME) + .unwrap(); + assert_eq!( + refusal_of(refused, &foreign_in_flight), + Refusal::ForeignReasoningState + ); + + let completed_q = invocation_for_model( + "completed-q-on-a", + "model-a", + 1_000, + vec![state("q", "model-b", 1), user("next")], + ); + let TransportAdmission::Execute(claim) = service + .begin_unplanned(&raw_envelope(&completed_q), 1_000, FRAME) + .unwrap() + else { + panic!("completed foreign state must be dropped, not refused"); + }; + assert_eq!(claim.call().foreign_reasoning_dropped(), 1); + assert_eq!(claim.call().request().input, vec![user("next")]); + assert_eq!(claim.call().receipt.provider, "p"); + let result = text_result(claim.call(), "ok"); + let response = service.complete(*claim, result, FRAME).unwrap(); + let TransportDisposition::Transported { receipt, .. } = + decrypt_result(&response, &security(KEY), &completed_q) + .unwrap() + .disposition + else { + panic!("expected transported result"); + }; + assert_eq!(receipt.provider, "p"); + assert_eq!(receipt.foreign_reasoning_dropped, 1); + + let own_p = invocation_for_model( + "own-p-on-a", + "model-a", + 1_000, + vec![user("next"), state("p", "model-a", 2)], + ); + let TransportAdmission::Execute(claim) = service + .begin_unplanned(&raw_envelope(&own_p), 1_000, FRAME) + .unwrap() + else { + panic!("own p state on model-a must pass"); + }; + assert_eq!(claim.call().foreign_reasoning_dropped(), 0); + assert_eq!(claim.call().receipt.provider, "p"); + } + + #[test] + fn same_tag_reasoning_on_other_route_passes() { + let store = TestStore::new(); + let mut service = two_route_service(&store, 1); + let q_state = state("q", "model-b", 3); + let invocation = invocation_for_model( + "q-on-b", + "model-b", + 1_000, + vec![user("hi"), q_state.clone()], + ); + let TransportAdmission::Execute(claim) = service + .begin_unplanned(&raw_envelope(&invocation), 1_000, FRAME) + .unwrap() + else { + panic!("q state on q-routed model-b must pass"); + }; + assert_eq!(claim.call().foreign_reasoning_dropped(), 0); + assert_eq!(claim.call().request().input, vec![user("hi"), q_state]); + assert_eq!(claim.call().receipt.provider, "q"); + let result = text_result(claim.call(), "ok"); + let response = service.complete(*claim, result, FRAME).unwrap(); + let TransportDisposition::Transported { receipt, .. } = + decrypt_result(&response, &security(KEY), &invocation) + .unwrap() + .disposition + else { + panic!("expected transported result"); + }; + assert_eq!(receipt.provider, "q"); + assert_eq!(receipt.foreign_reasoning_dropped, 0); + } + + #[test] + fn receipt_tag_mismatch_returns_stand_in_failure() { + let store = TestStore::new(); + let mut service = two_route_service(&store, 1); + let invocation = invocation_for_model("mismatch", "model-a", 1_000, vec![user("hi")]); + let TransportAdmission::Execute(claim) = service + .begin_unplanned(&raw_envelope(&invocation), 1_000, FRAME) + .unwrap() + else { + panic!("expected execution claim"); + }; + let mut bad = text_result(claim.call(), "done"); + let TransportDisposition::Transported { receipt, .. } = &mut bad.disposition else { + unreachable!(); + }; + receipt.provider = "q".to_string(); + let response = service.complete(*claim, bad, FRAME).unwrap(); + let answer = decrypt_result(&response, &security(KEY), &invocation).unwrap(); + let TransportDisposition::Transported { events, receipt } = &answer.disposition else { + panic!("expected stand-in failure"); + }; + assert!(events.is_empty()); + assert_eq!(receipt.provider, STAND_IN_PROVIDER); + assert!(matches!( + receipt.outcome, + TransportOutcome::Failed { + kind: FailureKind::Provider, + .. + } + )); + + let TransportAdmission::Reply(replay) = service + .begin_unplanned(&raw_envelope(&invocation), 1_000, FRAME) + .unwrap() + else { + panic!("retry must replay stand-in failure"); + }; + assert_eq!(replay, response); + + let next = invocation_for_model("after-mismatch", "model-b", 1_000, vec![user("hi")]); + assert!(matches!( + service + .begin_unplanned(&raw_envelope(&next), 1_000, FRAME) + .unwrap(), + TransportAdmission::Execute(_) + )); + } + + #[test] + fn unrouted_model_is_refused_model_not_allowed() { + let store = TestStore::new(); + let admission = CallerAdmission::new( + CALLER, + KEY, + 1, + ["gpt-5.4".to_string(), "unrouted-model".to_string()], + 1, + 64 * 1024, + 32_768, + ) + .unwrap(); + let mut service = + TransportService::open(&store.path, routes(), [admission], 5_000).unwrap(); + let unrouted = invocation_for_model("unrouted", "unrouted-model", 1_000, vec![user("hi")]); + let refused = service + .begin_unplanned(&raw_envelope(&unrouted), 1_000, FRAME) + .unwrap(); + assert_eq!(refusal_of(refused, &unrouted), Refusal::ModelNotAllowed); + + let routed = invocation_for_model("routed", "gpt-5.4", 1_000, vec![user("hi")]); + assert!(matches!( + service + .begin_unplanned(&raw_envelope(&routed), 1_000, FRAME) + .unwrap(), + TransportAdmission::Execute(_) + )); + } + + #[test] + fn rejecting_plan_refuses_only_its_owner_route() { + let store = TestStore::new(); + let mut service = two_route_service(&store, 4); + let rejected = plan_of(1_000, "rejected", 10_000); + + let model_a = invocation_for_model("a-rejected", "model-a", 9_999, vec![user("hi")]); + let refused = service + .begin( + &raw_envelope(&model_a), + 9_999, + Some(("p", &rejected)), + FRAME, + ) + .unwrap(); + assert_eq!(refusal_of(refused, &model_a), Refusal::ProviderRejected); + + let model_b = invocation_for_model("b-admitted", "model-b", 9_999, vec![user("hi")]); + let TransportAdmission::Execute(claim_b) = service + .begin( + &raw_envelope(&model_b), + 9_999, + Some(("p", &rejected)), + FRAME, + ) + .unwrap() + else { + panic!("model-b routed to q must not be refused by p's plan"); + }; + assert_eq!(claim_b.call().receipt.provider, "q"); + + assert!(matches!( + service + .begin( + &raw_envelope(&model_a), + 10_000, + Some(("p", &rejected)), + FRAME, + ) + .unwrap(), + TransportAdmission::Execute(_) + )); + } + + #[test] + fn replay_succeeds_after_removing_model_from_routes_and_allowed_models() { + let store = TestStore::new(); + let mut service = two_route_service(&store, 4); + let invocation = invocation_for_model("b1-replay", "model-a", 1_000, vec![user("hi")]); + let TransportAdmission::Execute(claim) = service + .begin_unplanned(&raw_envelope(&invocation), 1_000, FRAME) + .unwrap() + else { + panic!("first invocation must execute"); + }; + assert_eq!(claim.call().receipt.provider, "p"); + let result = text_result(claim.call(), "done"); + let recorded = service.complete(*claim, result, FRAME).unwrap(); + drop(service); + + let routes_without_a = + ProviderRoutes::new([("model-b".to_string(), "q".to_string())]).unwrap(); + let admission_without_a = CallerAdmission::new( + CALLER, + KEY, + 1, + ["model-b".to_string()], + 4, + 64 * 1024, + 32_768, + ) + .unwrap(); + let mut reopened = + TransportService::open(&store.path, routes_without_a, [admission_without_a], 5_000) + .unwrap(); + + let TransportAdmission::Reply(replay) = reopened + .begin_unplanned(&raw_envelope(&invocation), 1_000, FRAME) + .unwrap() + else { + panic!("completed request must replay even after model removal"); + }; + assert_eq!(replay, recorded); + let TransportDisposition::Transported { receipt, .. } = + decrypt_result(&replay, &security(KEY), &invocation) + .unwrap() + .disposition + else { + panic!("expected transported result"); + }; + assert_eq!(receipt.provider, "p"); + + let conflict = invocation_for_model("b1-replay", "model-a", 1_000, vec![user("changed")]); + let conflict_reply = reopened + .begin_unplanned(&raw_envelope(&conflict), 1_000, FRAME) + .unwrap(); + assert_eq!( + refusal_of(conflict_reply, &conflict), + Refusal::ReplayConflict + ); + + let fresh_a = invocation_for_model("b1-fresh", "model-a", 1_000, vec![user("hi")]); + let fresh_reply = reopened + .begin_unplanned(&raw_envelope(&fresh_a), 1_000, FRAME) + .unwrap(); + assert_eq!(refusal_of(fresh_reply, &fresh_a), Refusal::ModelNotAllowed); + } + + #[test] + fn replay_succeeds_after_switching_route_with_inflight_reasoning_state() { + let store = TestStore::new(); + let mut service = two_route_service(&store, 4); + let invocation = invocation_for_model( + "b2-replay", + "model-a", + 1_000, + vec![user("turn"), state("p", "model-a", 1)], + ); + let TransportAdmission::Execute(claim) = service + .begin_unplanned(&raw_envelope(&invocation), 1_000, FRAME) + .unwrap() + else { + panic!("first invocation with p state on p-routed model-a must execute"); + }; + let result = text_result(claim.call(), "done"); + let recorded = service.complete(*claim, result, FRAME).unwrap(); + drop(service); + + let switched_routes = ProviderRoutes::new([ + ("model-a".to_string(), "q".to_string()), + ("model-b".to_string(), "q".to_string()), + ]) + .unwrap(); + let admission = CallerAdmission::new( + CALLER, + KEY, + 1, + ["model-a".to_string(), "model-b".to_string()], + 4, + 64 * 1024, + 32_768, + ) + .unwrap(); + let mut reopened = + TransportService::open(&store.path, switched_routes, [admission], 5_000).unwrap(); + + let TransportAdmission::Reply(replay) = reopened + .begin_unplanned(&raw_envelope(&invocation), 1_000, FRAME) + .unwrap() + else { + panic!("completed request must replay even after route switch p -> q"); + }; + assert_eq!(replay, recorded); + + let fresh_p_on_q = invocation_for_model( + "b2-fresh", + "model-a", + 1_000, + vec![user("turn"), state("p", "model-a", 1)], + ); + let refused = reopened + .begin_unplanned(&raw_envelope(&fresh_p_on_q), 1_000, FRAME) + .unwrap(); + assert_eq!( + refusal_of(refused, &fresh_p_on_q), + Refusal::ForeignReasoningState + ); + } + + #[test] + fn oversized_replay_at_narrowed_frame_keeps_original_drop_count_after_route_change_or_removal() + { + let store = TestStore::new(); + let mut service = two_route_service(&store, 4); + + // Case 1: originally 0 dropped on route p; route switches p -> q before narrowed replay. + let zero_dropped = invocation_for_model( + "b3-rerouted", + "model-a", + 1_000, + vec![state("p", "model-a", 1), user("turn")], + ); + let TransportAdmission::Execute(claim_zero) = service + .begin_unplanned(&raw_envelope(&zero_dropped), 1_000, FRAME) + .unwrap() + else { + panic!("expected execution claim"); + }; + assert_eq!(claim_zero.call().foreign_reasoning_dropped(), 0); + let big_zero = text_result(claim_zero.call(), &"y".repeat(4000)); + service.complete(*claim_zero, big_zero, FRAME).unwrap(); + + // Case 2: originally 1 dropped on route p; model-a is removed before narrowed replay. + let one_dropped = invocation_for_model( + "b3-removed", + "model-a", + 1_000, + vec![state("q", "model-b", 1), user("turn")], + ); + let TransportAdmission::Execute(claim_one) = service + .begin_unplanned(&raw_envelope(&one_dropped), 1_000, FRAME) + .unwrap() + else { + panic!("expected execution claim"); + }; + assert_eq!(claim_one.call().foreign_reasoning_dropped(), 1); + let big_one = text_result(claim_one.call(), &"y".repeat(4000)); + service.complete(*claim_one, big_one, FRAME).unwrap(); + drop(service); + + let switched_routes = ProviderRoutes::new([ + ("model-a".to_string(), "q".to_string()), + ("model-b".to_string(), "q".to_string()), + ]) + .unwrap(); + let admission_both = CallerAdmission::new( + CALLER, + KEY, + 1, + ["model-a".to_string(), "model-b".to_string()], + 4, + 64 * 1024, + 32_768, + ) + .unwrap(); + let mut rerouted = + TransportService::open(&store.path, switched_routes, [admission_both], 5_000).unwrap(); + let TransportAdmission::Reply(stand_in_zero) = rerouted + .begin_unplanned(&raw_envelope(&zero_dropped), 1_000, 2000) + .unwrap() + else { + panic!("expected stand-in replay for rerouted oversized record"); + }; + let TransportDisposition::Transported { receipt, .. } = + decrypt_result(&stand_in_zero, &security(KEY), &zero_dropped) + .unwrap() + .disposition + else { + panic!("expected transported stand-in"); + }; + assert_eq!(receipt.provider, STAND_IN_PROVIDER); + assert_eq!(receipt.foreign_reasoning_dropped, 0); + drop(rerouted); + + let routes_without_a = + ProviderRoutes::new([("model-b".to_string(), "q".to_string())]).unwrap(); + let admission_without_a = CallerAdmission::new( + CALLER, + KEY, + 1, + ["model-b".to_string()], + 4, + 64 * 1024, + 32_768, + ) + .unwrap(); + let mut removed = + TransportService::open(&store.path, routes_without_a, [admission_without_a], 5_000) + .unwrap(); + let TransportAdmission::Reply(stand_in_one) = removed + .begin_unplanned(&raw_envelope(&one_dropped), 1_000, 2000) + .unwrap() + else { + panic!("expected stand-in replay for unrouted oversized record"); + }; + let TransportDisposition::Transported { receipt, .. } = + decrypt_result(&stand_in_one, &security(KEY), &one_dropped) + .unwrap() + .disposition + else { + panic!("expected transported stand-in"); + }; + assert_eq!(receipt.provider, STAND_IN_PROVIDER); + assert_eq!(receipt.foreign_reasoning_dropped, 1); + + let TransportAdmission::Reply(replayed_stand_in) = removed + .begin_unplanned(&raw_envelope(&one_dropped), 1_000, FRAME) + .unwrap() + else { + panic!("expected persisted stand-in replay"); + }; + assert_eq!(replayed_stand_in, stand_in_one); + } } diff --git a/crates/model-connector/src/service/lease.rs b/crates/model-connector/src/service/lease.rs index 5d55bf3..178cdb7 100644 --- a/crates/model-connector/src/service/lease.rs +++ b/crates/model-connector/src/service/lease.rs @@ -1,27 +1,29 @@ -//! A credential lease: a Self run's or a Persona turn's hold on the token the -//! connector lends. The lease is memory bound to its holder's open connection, -//! not a record and not a charge: it decides `Busy` while it is held and -//! nothing else. It ends when its holder lets go (`end_lease`), when the unit -//! invocation it served ends, or when its expiry passes. Nothing is billed and -//! nothing is reserved. The only usage-derived refusal is the provider's own -//! (`ProviderRejected`), repeated with the provider's own expiry. +//! A credential lease: a holder's hold on the token the connector lends. +//! The lease is memory bound to its holder's open connection, not a record and +//! not a charge: it decides `Busy` while it is held and nothing else. It ends +//! when its holder lets go (`end_lease`), when the unit invocation it served +//! ends, or when its expiry passes. Nothing is billed and nothing is reserved. +//! The only usage-derived refusal is the provider's own (`ProviderRejected`), +//! repeated with the provider's own expiry. use super::*; /// The request-id namespace of leases. const LEASE_PREFIX: &str = "lease:"; -/// What a Persona turn's lease id adds to its invocation id, so a Persona -/// lease and a Self lease of one caller and one invocation never share an id. -const PERSONA_SUFFIX: &str = ":persona"; +/// What a per-invocation lease id adds to its invocation id, so a +/// per-invocation lease and a per-caller lease of one caller and one +/// invocation never share an id. +const INVOCATION_SUFFIX: &str = ":invocation"; -/// Which kind of turn a lease serves. It is a property of the lease caller's -/// configured row, never of a request. A caller holds one Self lease at a -/// time; a Persona turn holds one lease per live invocation, one at a time. +/// Exclusivity scope of a lease. It is a property of the lease holder's +/// configured row, never of a request. A `PerCaller` holder keeps one lease open +/// per caller at a time; a `PerInvocation` holder keeps one lease open per live +/// unit invocation at a time. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum LeaseTurn { - SelfRun, - PersonaTurn, +pub enum LeaseScope { + PerCaller, + PerInvocation, } /// What an admitted lease holds. @@ -34,8 +36,8 @@ pub struct LeaseGrant { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LeaseRefusal { UnknownCaller, - /// A Self run: the caller holds a Self lease now. A Persona turn: this - /// invocation holds a lease now. + /// `PerCaller`: the caller holds a per-caller lease now. `PerInvocation`: + /// this invocation holds a lease now. Busy, /// The provider is refusing right now and has said until when. ProviderRejected, @@ -49,16 +51,16 @@ pub enum LeaseAdmission { impl TransportService { /// Grants `caller_runtime_id` a lease for the unit invocation - /// `invocation_id` until `expires_at_unix_ms`. A Self run's lease is - /// `lease:` and one is open per caller; a Persona turn's is - /// `lease::persona`, one open per invocation; neither blocks - /// the other. A lease takes no request slot. `plan` is the backend's plan - /// quota as it stands: a provider that is refusing right now refuses the - /// lease. A lease past its expiry no longer holds anything. + /// `invocation_id` until `expires_at_unix_ms`. A `PerCaller` lease is + /// `lease:` and one is open per caller; a `PerInvocation` lease + /// is `lease::invocation`, one open per invocation; neither + /// blocks the other. A lease takes no request slot. `plan` is the backend's + /// plan quota as it stands: a provider that is refusing right now refuses + /// the lease. A lease past its expiry no longer holds anything. pub fn begin_lease( &mut self, caller_runtime_id: &str, - turn: LeaseTurn, + scope: LeaseScope, invocation_id: &str, expires_at_unix_ms: u64, now_unix_ms: u64, @@ -68,9 +70,9 @@ impl TransportService { return Ok(LeaseAdmission::Refused(LeaseRefusal::UnknownCaller)); } require_id(invocation_id, "invocation_id")?; - let suffix = match turn { - LeaseTurn::SelfRun => "", - LeaseTurn::PersonaTurn => PERSONA_SUFFIX, + let suffix = match scope { + LeaseScope::PerCaller => "", + LeaseScope::PerInvocation => INVOCATION_SUFFIX, }; let lease_id = format!("{LEASE_PREFIX}{invocation_id}{suffix}"); if lease_id.len() > MAX_IDENTITY_BYTES { @@ -82,22 +84,22 @@ impl TransportService { caller_runtime_id: caller_runtime_id.to_string(), request_id: lease_id.clone(), }; - let busy = match turn { - LeaseTurn::SelfRun => self.leases.iter().any(|(held, lease)| { - lease.turn == LeaseTurn::SelfRun && held.caller_runtime_id == caller_runtime_id + let busy = match scope { + LeaseScope::PerCaller => self.leases.iter().any(|(held, lease)| { + lease.scope == LeaseScope::PerCaller && held.caller_runtime_id == caller_runtime_id }), - LeaseTurn::PersonaTurn => self.leases.contains_key(&identity), + LeaseScope::PerInvocation => self.leases.contains_key(&identity), }; if busy { return Ok(LeaseAdmission::Refused(LeaseRefusal::Busy)); } - if provider_rejects(plan, now_unix_ms) { + if plan_rejects(plan, now_unix_ms) { return Ok(LeaseAdmission::Refused(LeaseRefusal::ProviderRejected)); } self.leases.insert( identity, LiveLease { - turn, + scope, expires_at_unix_ms, }, ); @@ -121,16 +123,28 @@ mod tests { use crate::readout::PlanQuota; const CALLER: &str = "eureka"; + const CALLER_TWO: &str = "caller-two"; const KEY: &str = "lease-distinct-test-key"; + const KEY_TWO: &str = "lease-distinct-test-key-two"; const NOW: u64 = 7_200_500; fn open(store: &TestStore) -> TransportService { TransportService::open( &store.path, - "fixture-sse", + crate::fixtures::routes(), [ CallerAdmission::new(CALLER, KEY, 1, ["gpt-5.4".to_string()], 1, 65_536, 32_768) .unwrap(), + CallerAdmission::new( + CALLER_TWO, + KEY_TWO, + 1, + ["gpt-5.4".to_string()], + 1, + 65_536, + 32_768, + ) + .unwrap(), ], 5_000, ) @@ -155,17 +169,17 @@ mod tests { fn lease_in( service: &mut TransportService, - turn: LeaseTurn, + scope: LeaseScope, run: &str, plan: &PlanQuotaSnapshot, ) -> LeaseAdmission { service - .begin_lease(CALLER, turn, run, NOW + 60_000, NOW, plan) + .begin_lease(CALLER, scope, run, NOW + 60_000, NOW, plan) .unwrap() } fn lease(service: &mut TransportService, run: &str) -> LeaseAdmission { - lease_in(service, LeaseTurn::SelfRun, run, &none()) + lease_in(service, LeaseScope::PerCaller, run, &none()) } fn granted(admission: LeaseAdmission) -> LeaseGrant { @@ -186,7 +200,7 @@ mod tests { } #[test] - fn a_caller_holds_one_self_lease_at_a_time() { + fn a_per_caller_holder_holds_one_lease_at_a_time() { let store = TestStore::new(); let mut service = open(&store); granted(lease(&mut service, "run-1")); @@ -198,6 +212,19 @@ mod tests { lease(&mut service, "run-1"), LeaseAdmission::Refused(LeaseRefusal::Busy) ); + // Distinct callers hold independent PerCaller leases. + granted( + service + .begin_lease( + CALLER_TWO, + LeaseScope::PerCaller, + "run-other", + NOW + 60_000, + NOW, + &none(), + ) + .unwrap(), + ); } #[test] @@ -223,14 +250,21 @@ mod tests { let mut service = open(&store); granted( service - .begin_lease(CALLER, LeaseTurn::SelfRun, "run-1", NOW + 10, NOW, &none()) + .begin_lease( + CALLER, + LeaseScope::PerCaller, + "run-1", + NOW + 10, + NOW, + &none(), + ) .unwrap(), ); assert_eq!( service .begin_lease( CALLER, - LeaseTurn::SelfRun, + LeaseScope::PerCaller, "run-2", NOW + 99, NOW + 9, @@ -244,7 +278,7 @@ mod tests { service .begin_lease( CALLER, - LeaseTurn::SelfRun, + LeaseScope::PerCaller, "run-2", NOW + 99, NOW + 10, @@ -262,7 +296,7 @@ mod tests { service .begin_lease( "stranger", - LeaseTurn::SelfRun, + LeaseScope::PerCaller, "run-1", NOW + 1, NOW, @@ -274,22 +308,22 @@ mod tests { } #[test] - fn a_persona_holds_one_lease_per_invocation_and_never_blocks_the_self_lease() { + fn a_per_invocation_holder_holds_one_lease_per_invocation_and_never_blocks_per_caller() { let store = TestStore::new(); let mut service = open(&store); - let persona = |service: &mut TransportService, run: &str| { - lease_in(service, LeaseTurn::PersonaTurn, run, &none()) + let per_invocation = |service: &mut TransportService, run: &str| { + lease_in(service, LeaseScope::PerInvocation, run, &none()) }; - let first = granted(persona(&mut service, "turn-1")); - assert_eq!(first.lease_id, "lease:turn-1:persona"); + let first = granted(per_invocation(&mut service, "turn-1")); + assert_eq!(first.lease_id, "lease:turn-1:invocation"); assert_eq!( - persona(&mut service, "turn-1"), + per_invocation(&mut service, "turn-1"), LeaseAdmission::Refused(LeaseRefusal::Busy) ); - granted(persona(&mut service, "turn-2")); + granted(per_invocation(&mut service, "turn-2")); granted(lease(&mut service, "turn-1")); service.end_lease(CALLER, &first.lease_id); - granted(persona(&mut service, "turn-1")); + granted(per_invocation(&mut service, "turn-1")); } #[test] @@ -298,7 +332,7 @@ mod tests { let mut service = open(&store); let rejected = window(1_000, "rejected", NOW + 5_000); assert_eq!( - lease_in(&mut service, LeaseTurn::SelfRun, "run-1", &rejected), + lease_in(&mut service, LeaseScope::PerCaller, "run-1", &rejected), LeaseAdmission::Refused(LeaseRefusal::ProviderRejected) ); let call = |service: &mut TransportService, now: u64, plan: &PlanQuotaSnapshot| { @@ -313,8 +347,9 @@ mod tests { &security(KEY), ) .unwrap(); - let TransportAdmission::Reply(reply) = - service.begin(&sealed, now, plan, 1 << 20).unwrap() + let TransportAdmission::Reply(reply) = service + .begin(&sealed, now, Some(("fixture-sse", plan)), 1 << 20) + .unwrap() else { return None; }; @@ -338,7 +373,7 @@ mod tests { service .begin_lease( CALLER, - LeaseTurn::SelfRun, + LeaseScope::PerCaller, "run-1", NOW + 9_000, NOW + 5_000, @@ -354,11 +389,16 @@ mod tests { let store = TestStore::new(); let mut service = open(&store); let full = window(999, "allowed", NOW + 5_000); - granted(lease_in(&mut service, LeaseTurn::SelfRun, "run-1", &full)); + granted(lease_in( + &mut service, + LeaseScope::PerCaller, + "run-1", + &full, + )); let warned = window(1_000, "allowed_warning", NOW + 5_000); granted(lease_in( &mut service, - LeaseTurn::PersonaTurn, + LeaseScope::PerInvocation, "turn-1", &warned, )); @@ -371,30 +411,37 @@ mod tests { let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len()); let grant = granted(lease(&mut service, &longest)); assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES); - assert!(lease_try(&mut service, LeaseTurn::SelfRun, &format!("{longest}r")).is_err()); + assert!(lease_try(&mut service, LeaseScope::PerCaller, &format!("{longest}r")).is_err()); } #[test] - fn a_persona_invocation_id_leaves_room_for_its_suffix() { + fn a_per_invocation_id_leaves_room_for_its_suffix() { let store = TestStore::new(); let mut service = open(&store); - let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len() - PERSONA_SUFFIX.len()); + let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len() - INVOCATION_SUFFIX.len()); let grant = granted(lease_in( &mut service, - LeaseTurn::PersonaTurn, + LeaseScope::PerInvocation, &longest, &none(), )); assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES); - assert!(lease_try(&mut service, LeaseTurn::PersonaTurn, &format!("{longest}r")).is_err()); + assert!( + lease_try( + &mut service, + LeaseScope::PerInvocation, + &format!("{longest}r") + ) + .is_err() + ); } fn lease_try( service: &mut TransportService, - turn: LeaseTurn, + scope: LeaseScope, run: &str, ) -> Result { - service.begin_lease(CALLER, turn, run, NOW + 60_000, NOW, &none()) + service.begin_lease(CALLER, scope, run, NOW + 60_000, NOW, &none()) } #[test] @@ -415,13 +462,13 @@ mod tests { ) .unwrap(); assert!(matches!( - service.begin(&sealed, NOW, &none(), 1 << 20).unwrap(), + service.begin(&sealed, NOW, None, 1 << 20).unwrap(), TransportAdmission::Execute(_) )); // And a call in flight does not make the caller busy for a lease. granted(lease_in( &mut service, - LeaseTurn::PersonaTurn, + LeaseScope::PerInvocation, "turn-1", &none(), )); diff --git a/crates/model-connector/tests/reasoning_state.rs b/crates/model-connector/tests/reasoning_state.rs index 170dd8e..6105c19 100644 --- a/crates/model-connector/tests/reasoning_state.rs +++ b/crates/model-connector/tests/reasoning_state.rs @@ -42,10 +42,6 @@ impl ProviderBackend for RecordingBackend { Ok(()) } - fn provider(&self) -> &str { - PROVIDER - } - fn execute(&self, call: &ProviderCall) -> TransportResult { self.executions.fetch_add(1, Ordering::SeqCst); self.seen.lock().unwrap().push(call.request().clone()); @@ -114,7 +110,9 @@ fn start_with(backend: Arc, max_concurrent: usize) -> Conne socket_timeout_ms: 5_000, max_expiry_skew_ms: 300_000, }; - thread::spawn(move || serve(listener, limits, vec![admission], &store, backend)); + let routes = + ProviderRoutes::new([("claude-opus-4-5".to_string(), PROVIDER.to_string())]).unwrap(); + thread::spawn(move || serve(listener, limits, vec![admission], &store, routes, backend)); ConnectorClient::new(endpoint, KEY, FRAME, Some(Duration::from_secs(5))).unwrap() } @@ -279,10 +277,6 @@ impl ProviderBackend for TamperingBackend { Ok(()) } - fn provider(&self) -> &str { - PROVIDER - } - fn execute(&self, call: &ProviderCall) -> TransportResult { let mut result = call.transported( vec![TransportEvent {