claude-connector: the ApiKey route leaves the CLI; MessagesBackend serves it over the Messages API
A connector whose document says auth is an API key now answers with one Messages API request per call: tools, tool_use and tool_result, thinking blocks replayed unchanged, cache breakpoints (5m or 1h) and cache usage map natively. The CLI keeps only the subscription token: ClaudeCodeConfig.auth, the API-key descriptor variable and its tests are deleted. Reasoning state of this backend is tagged anthropic-messages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
80c1fc6a69
commit
d50ece2a81
12 changed files with 1496 additions and 162 deletions
137
Cargo.lock
generated
137
Cargo.lock
generated
|
|
@ -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"
|
||||
|
|
@ -151,6 +163,7 @@ dependencies = [
|
|||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror",
|
||||
"ureq",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
|
|
@ -232,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",
|
||||
|
|
@ -437,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"
|
||||
|
|
@ -511,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",
|
||||
|
|
@ -556,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"
|
||||
|
|
@ -700,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"
|
||||
|
|
@ -739,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"
|
||||
|
|
@ -986,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"
|
||||
|
|
@ -1063,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"
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
@ -23,6 +23,7 @@ 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]
|
||||
|
|
|
|||
|
|
@ -278,7 +278,7 @@ pub fn ask(args: &AskArgs) -> Result<String, AskError> {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits};
|
||||
use crate::config::{ClaudeCodeConfig, ClaudeCodeLimits};
|
||||
use crate::handle::{SessionStore, plan};
|
||||
use model_connector::ToolDefinition;
|
||||
|
||||
|
|
@ -315,7 +315,6 @@ mod tests {
|
|||
prompt_dir: "/p".into(),
|
||||
token_credential: "t".into(),
|
||||
handle_secret_credential: "h".into(),
|
||||
auth: ClaudeAuth::OAuthToken,
|
||||
instance: "i".into(),
|
||||
limits: ClaudeCodeLimits {
|
||||
deadline: Duration::from_secs(1),
|
||||
|
|
|
|||
|
|
@ -261,7 +261,7 @@ impl ClaudeCodeBackend {
|
|||
deadline,
|
||||
&request.model,
|
||||
request.output_schema_json.as_deref(),
|
||||
self.config.auth.is_metered().then_some(&*self.quota),
|
||||
Some(&*self.quota),
|
||||
);
|
||||
child.kill();
|
||||
child.wait();
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ use model_connector::{
|
|||
};
|
||||
|
||||
use super::*;
|
||||
use crate::config::{ClaudeAuth, ClaudeCodeLimits};
|
||||
use crate::config::ClaudeCodeLimits;
|
||||
use crate::handle::{FsSessionStore, SessionStore};
|
||||
use crate::launch::ChildEnv;
|
||||
|
||||
|
|
@ -19,8 +19,6 @@ 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";
|
||||
const TOKEN_FD_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
|
||||
const KEY_FD_ENV: &str = "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR";
|
||||
const CANARY_KEY: &str = "canary-api-key-value";
|
||||
const MODEL: &str = "claude-haiku-5-5";
|
||||
const INSTANCE: &str = "persona-a";
|
||||
const SESSION: &str = "11111111-2222-3333-4444-555555555555";
|
||||
|
|
@ -335,7 +333,6 @@ fn config(dir: &Path, instance: &str, limits: ClaudeCodeLimits) -> ClaudeCodeCon
|
|||
config_dir: PathBuf::from("/cfg"),
|
||||
prompt_dir: dir.join("prompts"),
|
||||
token_credential: "claude-token".to_string(),
|
||||
auth: ClaudeAuth::OAuthToken,
|
||||
handle_secret_credential: "claude-handle-secret".to_string(),
|
||||
instance: instance.to_string(),
|
||||
limits,
|
||||
|
|
@ -677,90 +674,13 @@ fn child_env_is_cleared_and_names_the_token_descriptor_never_the_token() {
|
|||
assert!(!format!("{result:?}").contains(CANARY_TOKEN));
|
||||
}
|
||||
|
||||
// ---- API key authentication ----
|
||||
|
||||
/// A rig whose child authenticates with an API key.
|
||||
fn api_rig(scripts: Vec<Script>) -> Rig {
|
||||
let mut rig = rig(scripts);
|
||||
rig.backend.config.auth = ClaudeAuth::ApiKey;
|
||||
rig.backend.tokens = Box::new(FixedToken(Some(CANARY_KEY)));
|
||||
rig
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_key_mode_names_the_key_descriptor_and_never_the_key_or_the_oauth_variable() {
|
||||
let rig = api_rig(vec![structured_script()]);
|
||||
let result = rig.run(schema_request());
|
||||
let seen = rig.seen();
|
||||
let mut names: Vec<&str> = seen.env.iter().map(|(name, _)| name.as_str()).collect();
|
||||
names.sort();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
KEY_FD_ENV,
|
||||
"CLAUDE_CODE_MAX_OUTPUT_TOKENS",
|
||||
"CLAUDE_CONFIG_DIR",
|
||||
"HOME",
|
||||
"PATH"
|
||||
]
|
||||
);
|
||||
assert!(seen.env.contains(&(KEY_FD_ENV.to_string(), "3".to_string())));
|
||||
// The key travels beside the environment, to the port, alone.
|
||||
assert_eq!(seen.token, CANARY_KEY);
|
||||
let everything = format!(
|
||||
"{:?} {:?} {:?} {result:?}",
|
||||
seen.env, seen.argv, rig.backend.config
|
||||
);
|
||||
assert!(!everything.contains(CANARY_KEY));
|
||||
let sunk = String::from_utf8(rig.sink.0.lock().unwrap().clone()).unwrap();
|
||||
assert!(!sunk.contains(CANARY_KEY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_key_mode_reads_no_plan_and_the_cell_stays_empty() {
|
||||
let rig = api_rig(vec![structured_script()]);
|
||||
rig.run(schema_request());
|
||||
assert!(quota_of(&rig).windows.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_mode_still_feeds_the_cell_and_names_the_oauth_descriptor() {
|
||||
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));
|
||||
assert!(seen.env.iter().all(|(name, _)| name != KEY_FD_ENV));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_api_key_fails_before_spawn() {
|
||||
let mut rig = api_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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_api_key_is_not_ready() {
|
||||
let dir = sandbox();
|
||||
let (work, cfg) = (dir.path().join("work"), dir.path().join("cfg"));
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
std::fs::create_dir_all(&cfg).unwrap();
|
||||
let mut config = config(dir.path(), INSTANCE, limits());
|
||||
config.work_dir = work;
|
||||
config.config_dir = cfg;
|
||||
config.auth = ClaudeAuth::ApiKey;
|
||||
assert_eq!(
|
||||
readiness(&config, &FixedToken(None), &FixedSecret(Some(SECRET))),
|
||||
Err("token_credential")
|
||||
);
|
||||
assert_eq!(
|
||||
readiness(&config, &FixedToken(Some(CANARY_KEY)), &FixedSecret(Some(SECRET))),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -2567,31 +2487,6 @@ mod real {
|
|||
assert!(held.contains(&3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_key_reaches_the_child_on_its_pipe_and_nowhere_else() {
|
||||
let probe = TempDir::new();
|
||||
let body = format!(
|
||||
"fd=\"${KEY_FD_ENV}\"\neval \"cat <&$fd\" > '{d}/key'\nenv > '{d}/env'\nprintf '%s\n' \"$@\" > '{d}/argv'\nprintf '%s' \"${TOKEN_FD_ENV}\" > '{d}/oauth'\n{lines}",
|
||||
d = probe.path().display(),
|
||||
lines = printf_lines(&good_lines())
|
||||
);
|
||||
let mut fake = fake(&body, limits());
|
||||
fake.backend.config.auth = ClaudeAuth::ApiKey;
|
||||
fake.backend.tokens = Box::new(FixedToken(Some(CANARY_KEY)));
|
||||
let result = fake.run(request(vec![user("hello")]));
|
||||
assert!(matches!(
|
||||
outcome(&result),
|
||||
TransportOutcome::Completed { .. }
|
||||
));
|
||||
let read = |name: &str| std::fs::read_to_string(probe.path().join(name)).unwrap();
|
||||
assert_eq!(read("key"), CANARY_KEY, "the pipe holds the key");
|
||||
assert_eq!(read("oauth"), "", "the OAuth variable is not set");
|
||||
assert!(!read("env").contains(CANARY_KEY) && !read("argv").contains(CANARY_KEY));
|
||||
assert!(read("env").contains(&format!("{KEY_FD_ENV}=3")));
|
||||
let sunk = String::from_utf8(fake.sink.0.lock().unwrap().clone()).unwrap();
|
||||
assert!(!sunk.contains(CANARY_KEY) && !format!("{result:?}").contains(CANARY_KEY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_too_large_for_a_pipe_is_refused_at_its_bound_not_hung() {
|
||||
let fake = fake("exit 0", limits());
|
||||
|
|
|
|||
|
|
@ -3,37 +3,25 @@ use std::time::Duration;
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// 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
|
||||
/// of the CLI backend. It is distinct from the Messages backend's tag, so the
|
||||
/// kit treats each backend's state as foreign to the other.
|
||||
pub(crate) const PROVIDER: &str = "claude-code";
|
||||
|
||||
/// Which credential the child authenticates with. One choice for the whole
|
||||
/// connector; the credential itself is the systemd credential
|
||||
/// [`ClaudeCodeConfig::token_credential`] names, and it reaches the child on a
|
||||
/// pipe whichever this is.
|
||||
/// Which credential the connector authenticates with. One choice for the whole
|
||||
/// connector, held in the systemd credential the config document's
|
||||
/// `token_credential` names.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ClaudeAuth {
|
||||
/// The subscription's OAuth token. The plan's usage is metered.
|
||||
/// The subscription's OAuth token, given to the `claude` CLI child by
|
||||
/// [`ClaudeCodeBackend`](crate::ClaudeCodeBackend). The plan's usage is
|
||||
/// metered.
|
||||
OAuthToken,
|
||||
/// An Anthropic API key. Nothing is metered: a key has no subscription plan.
|
||||
/// An Anthropic API key, used by [`MessagesBackend`](crate::MessagesBackend)
|
||||
/// over HTTP; the CLI is never spawned. Nothing is metered: a key has no
|
||||
/// subscription plan.
|
||||
ApiKey,
|
||||
}
|
||||
|
||||
impl ClaudeAuth {
|
||||
/// The variable that tells the CLI which descriptor holds the credential.
|
||||
pub(crate) fn fd_var(self) -> &'static str {
|
||||
match self {
|
||||
Self::OAuthToken => "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
|
||||
Self::ApiKey => "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the credential has a subscription plan to meter.
|
||||
pub(crate) fn is_metered(self) -> bool {
|
||||
self == Self::OAuthToken
|
||||
}
|
||||
}
|
||||
|
||||
/// What the connector's binary hands the backend. Every path is absolute.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ClaudeCodeConfig {
|
||||
|
|
@ -50,11 +38,9 @@ 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 credential, under
|
||||
/// The name of the systemd credential that holds the child's subscription token, under
|
||||
/// `$CREDENTIALS_DIRECTORY`.
|
||||
pub token_credential: String,
|
||||
/// Which credential that is: the subscription token or an API key.
|
||||
pub auth: ClaudeAuth,
|
||||
/// The name of the systemd credential that holds the handle secret: the
|
||||
/// key every handle is authenticated with.
|
||||
pub handle_secret_credential: String,
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ use crate::unit::SystemdUnits;
|
|||
use crate::meter;
|
||||
use crate::{
|
||||
ClaudeAuth, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource,
|
||||
StderrSink,
|
||||
MessagesBackend, MessagesConfig, StderrSink,
|
||||
};
|
||||
|
||||
const CONFIG_KEY: &str = "runtime";
|
||||
|
|
@ -293,7 +293,6 @@ impl ClaudeConnectorConfig {
|
|||
config_dir: self.config_dir.clone(),
|
||||
prompt_dir: self.prompt_dir.clone(),
|
||||
token_credential: self.token_credential.clone(),
|
||||
auth: self.auth,
|
||||
handle_secret_credential: self.handle_secret_credential.clone(),
|
||||
instance: self.instance.clone(),
|
||||
limits: ClaudeCodeLimits {
|
||||
|
|
@ -305,6 +304,14 @@ impl ClaudeConnectorConfig {
|
|||
}
|
||||
}
|
||||
|
||||
fn messages_config(&self) -> MessagesConfig {
|
||||
MessagesConfig {
|
||||
key_credential: self.token_credential.clone(),
|
||||
deadline: Duration::from_millis(self.deadline_ms),
|
||||
max_response_bytes: self.max_total_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
fn serve_limits(&self) -> ServeLimits {
|
||||
ServeLimits {
|
||||
max_frame_bytes: self.max_frame_bytes,
|
||||
|
|
@ -450,18 +457,27 @@ impl<W: std::io::Write + Send> StderrSink for LogSink<W> {
|
|||
/// key and the frame and connection bounds. Returns the admitted callers.
|
||||
fn readiness_of(config: &ClaudeConnectorConfig) -> Result<Vec<CallerAdmission>, 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)?;
|
||||
match config.auth {
|
||||
// The CLI is never spawned on a key: its binary, directories and
|
||||
// handle secret are not this backend's, only the key is.
|
||||
ClaudeAuth::ApiKey => MessagesBackend::new(config.messages_config())
|
||||
.ready()
|
||||
.map_err(ConfigError::Unusable)?,
|
||||
ClaudeAuth::OAuthToken => {
|
||||
#[cfg(unix)]
|
||||
check_prompt_dir(&config.prompt_dir)?;
|
||||
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)?;
|
||||
}
|
||||
}
|
||||
if config.lease_socket.is_some() {
|
||||
lease_callers_of(config)?;
|
||||
}
|
||||
|
|
@ -564,10 +580,17 @@ fn serve_config_with(
|
|||
let config = load_config(path)?;
|
||||
let admissions = readiness_of(&config)?;
|
||||
let listen = config.validate()?;
|
||||
let backend = Arc::new(ClaudeCodeBackend::new(
|
||||
config.backend_config(),
|
||||
Box::new(LogSink(std::sync::Mutex::new(std::io::stderr()))),
|
||||
));
|
||||
// The CLI backend on a subscription token, the Messages backend on a key.
|
||||
let claude = (config.auth == ClaudeAuth::OAuthToken).then(|| {
|
||||
Arc::new(ClaudeCodeBackend::new(
|
||||
config.backend_config(),
|
||||
Box::new(LogSink(std::sync::Mutex::new(std::io::stderr()))),
|
||||
))
|
||||
});
|
||||
let backend: Arc<dyn ProviderBackend> = match &claude {
|
||||
Some(claude) => claude.clone(),
|
||||
None => Arc::new(MessagesBackend::new(config.messages_config())),
|
||||
};
|
||||
let listener = TcpListener::bind(listen).map_err(|_| ConfigError::Listen)?;
|
||||
let service = Arc::new(Mutex::new(
|
||||
TransportService::open(
|
||||
|
|
@ -581,9 +604,11 @@ fn serve_config_with(
|
|||
// The meter is running before the first lease can ask, so that lease can
|
||||
// wait for its first read. An API key has no subscription plan to read:
|
||||
// no meter runs, the cell stays empty, and no lease waits for it.
|
||||
let quota = backend.quota();
|
||||
if config.auth.is_metered() {
|
||||
meter::start(quota.clone(), Box::new(backend.clone()))
|
||||
let quota = claude
|
||||
.as_ref()
|
||||
.map_or_else(|| Arc::new(crate::QuotaCell::new()), |claude| claude.quota());
|
||||
if let Some(claude) = &claude {
|
||||
meter::start(quota.clone(), Box::new(claude.clone()))
|
||||
.map_err(|_| ConfigError::Serving("meter"))?;
|
||||
}
|
||||
started("a);
|
||||
|
|
|
|||
|
|
@ -13,11 +13,13 @@ use model_connector::{ProviderRequest, ReasoningEffort};
|
|||
use crate::config::ClaudeCodeConfig;
|
||||
use crate::handle::Plan;
|
||||
|
||||
/// The credential never enters the environment, whichever `ClaudeAuth` it is:
|
||||
/// 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.
|
||||
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.
|
||||
|
|
@ -48,7 +50,7 @@ pub(crate) fn child_env(config: &ClaudeCodeConfig, request: &ProviderRequest) ->
|
|||
"CLAUDE_CODE_MAX_OUTPUT_TOKENS",
|
||||
request.max_output_tokens.to_string(),
|
||||
),
|
||||
(config.auth.fd_var(), TOKEN_FD.to_string()),
|
||||
(TOKEN_FD_VAR, TOKEN_FD.to_string()),
|
||||
])
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ mod handle;
|
|||
mod launch;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod lease;
|
||||
mod messages;
|
||||
mod meter;
|
||||
mod process;
|
||||
mod quota;
|
||||
|
|
@ -25,6 +26,7 @@ pub use daemon::{
|
|||
};
|
||||
#[cfg(unix)]
|
||||
pub use daemon::{check_prompt_dir, serve_config};
|
||||
pub use messages::{MessagesBackend, MessagesConfig};
|
||||
pub use handle::{FsSessionStore, MIN_SECRET_BYTES, SessionStore};
|
||||
pub use launch::ChildEnv;
|
||||
#[cfg(target_os = "linux")]
|
||||
|
|
|
|||
530
crates/claude-connector/src/messages.rs
Normal file
530
crates/claude-connector/src/messages.rs
Normal file
|
|
@ -0,0 +1,530 @@
|
|||
//! The Messages API backend: one non-streaming `POST /v1/messages` per call,
|
||||
//! authenticated with an Anthropic API key. It is the backend of a connector
|
||||
//! whose document says `auth` is an API key; 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`):
|
||||
//! - `claude-sonnet-5-5` and `claude-opus-5-5` reject forced `tool_choice`
|
||||
//! (`any`, `tool`) with a 400, and reject `thinking.budget_tokens`. So
|
||||
//! [`ToolChoice::Required`] is `auto` plus a system sentence, thinking is
|
||||
//! `{"type":"adaptive"}` with `output_config.effort`, and a request's output
|
||||
//! schema is `output_config.format` (`json_schema`) instead of a forced
|
||||
//! tool.
|
||||
//! - A thinking block is replayed unchanged, in transcript order; the API
|
||||
//! drops one its model cannot read. Its `signature` is the provider's.
|
||||
//! - Usage reports `input_tokens` apart from `cache_read_input_tokens` and
|
||||
//! `cache_creation_input_tokens`.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use model_connector::{
|
||||
CacheRetention, FailureKind, InputItem, PlanQuotaSnapshot, ProviderBackend, ProviderCall,
|
||||
ProviderRequest, ReasoningEffort, StopReason, ToolChoice, TransportEvent,
|
||||
TransportEventPayload, TransportOutcome, TransportResult, Usage,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::backend::TokenSource;
|
||||
|
||||
/// The provider tag on every receipt and every reasoning block of this
|
||||
/// backend; distinct from the CLI backend's tag.
|
||||
pub(crate) const PROVIDER: &str = "anthropic-messages";
|
||||
const ENDPOINT: &str = "https://api.anthropic.com";
|
||||
const API_VERSION: &str = "2026-10-21";
|
||||
/// The longest provider message a receipt carries.
|
||||
const MESSAGE_BYTES: usize = 2048;
|
||||
/// What `Required` becomes where the API accepts no forced tool choice.
|
||||
const REQUIRED_TOOL_SENTENCE: &str = "Respond by calling one of the provided tools.";
|
||||
|
||||
/// What the connector's binary hands the backend.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MessagesConfig {
|
||||
/// The name of the systemd credential that holds the API key, under
|
||||
/// `$CREDENTIALS_DIRECTORY`.
|
||||
pub key_credential: String,
|
||||
/// 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 {
|
||||
agent: ureq::Agent,
|
||||
endpoint: String,
|
||||
keys: Box<dyn TokenSource>,
|
||||
max_response_bytes: u64,
|
||||
}
|
||||
|
||||
impl MessagesBackend {
|
||||
/// The backend over the real API, with the key read from the credential
|
||||
/// `config.key_credential` names.
|
||||
pub fn new(config: MessagesConfig) -> Self {
|
||||
let keys = Box::new(crate::backend::CredentialTokenSource::from_environment(
|
||||
config.key_credential.clone(),
|
||||
));
|
||||
Self::with_parts(config, keys, ENDPOINT.to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn with_parts(
|
||||
config: MessagesConfig,
|
||||
keys: Box<dyn TokenSource>,
|
||||
endpoint: String,
|
||||
) -> Self {
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(config.deadline))
|
||||
.http_status_as_error(false)
|
||||
.build()
|
||||
.into();
|
||||
Self {
|
||||
agent,
|
||||
endpoint,
|
||||
keys,
|
||||
max_response_bytes: config.max_response_bytes as u64,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, request: &ProviderRequest) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let Some(key) = self.keys.read() else {
|
||||
return failed(
|
||||
FailureKind::Authentication,
|
||||
"anthropic-messages: the connector has no API key".to_string(),
|
||||
Some(zero_usage()),
|
||||
);
|
||||
};
|
||||
let body = match render(request).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!("anthropic-messages: {message}"),
|
||||
Some(zero_usage()),
|
||||
);
|
||||
}
|
||||
};
|
||||
let sent = self
|
||||
.agent
|
||||
.post(format!("{}/v1/messages", self.endpoint))
|
||||
.header("x-api-key", key.as_str())
|
||||
.header("anthropic-version", API_VERSION)
|
||||
.header("content-type", "application/json")
|
||||
.send(&body[..]);
|
||||
let mut response = match sent {
|
||||
Ok(response) => response,
|
||||
Err(error) => return transport_failure(&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(&error),
|
||||
};
|
||||
if !(200..300).contains(&status) {
|
||||
return http_failure(status, &text);
|
||||
}
|
||||
match parse(&text) {
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ProviderBackend for MessagesBackend {
|
||||
fn ready(&self) -> Result<(), &'static str> {
|
||||
match self.keys.read() {
|
||||
Some(_) => Ok(()),
|
||||
None => Err(self.keys.missing()),
|
||||
}
|
||||
}
|
||||
|
||||
fn provider(&self) -> &str {
|
||||
PROVIDER
|
||||
}
|
||||
|
||||
fn plan_quota(&self) -> PlanQuotaSnapshot {
|
||||
PlanQuotaSnapshot::default()
|
||||
}
|
||||
|
||||
fn execute(&self, call: &ProviderCall) -> TransportResult {
|
||||
let (events, outcome) = self.run(call.request());
|
||||
call.transported(events, outcome)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- request ----
|
||||
|
||||
/// The request body, or what is wrong with the request.
|
||||
fn render(request: &ProviderRequest) -> Result<Value, String> {
|
||||
let mut body = Map::new();
|
||||
body.insert("model".into(), json!(request.model));
|
||||
body.insert("max_tokens".into(), json!(request.max_output_tokens));
|
||||
|
||||
let mut system = vec![json!({"type": "text", "text": request.instructions})];
|
||||
if request.tool_choice == ToolChoice::Required && !request.tools.is_empty() {
|
||||
system.push(json!({"type": "text", "text": REQUIRED_TOOL_SENTENCE}));
|
||||
}
|
||||
body.insert("system".into(), Value::Array(system));
|
||||
|
||||
let mut messages = messages_of(&request.input)?;
|
||||
if let Some(retention) = request.cache_retention {
|
||||
mark_cache_breakpoint(&mut messages, retention);
|
||||
}
|
||||
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,
|
||||
}));
|
||||
}
|
||||
body.insert("tools".into(), Value::Array(tools));
|
||||
if !request.parallel_tool_calls {
|
||||
body.insert(
|
||||
"tool_choice".into(),
|
||||
json!({"type": "auto", "disable_parallel_tool_use": true}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mut output = Map::new();
|
||||
if let Some(effort) = request.reasoning_effort {
|
||||
body.insert("thinking".into(), json!({"type": "adaptive"}));
|
||||
output.insert("effort".into(), json!(effort_name(effort)));
|
||||
}
|
||||
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())?;
|
||||
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))
|
||||
}
|
||||
|
||||
fn effort_name(effort: ReasoningEffort) -> &'static str {
|
||||
match effort {
|
||||
ReasoningEffort::Low => "low",
|
||||
ReasoningEffort::Medium => "medium",
|
||||
ReasoningEffort::High => "high",
|
||||
ReasoningEffort::Max => "max",
|
||||
}
|
||||
}
|
||||
|
||||
#[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]) -> Result<Vec<Value>, String> {
|
||||
let mut messages: Vec<Value> = Vec::new();
|
||||
let mut open: Option<(Role, Vec<Value>)> = None;
|
||||
for item in input {
|
||||
let (role, block) = block_of(item)?;
|
||||
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>)) -> 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) -> 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
|
||||
&& 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Puts the one breakpoint on the last block of the last message that can
|
||||
/// carry it (a thinking block cannot).
|
||||
fn mark_cache_breakpoint(messages: &mut [Value], retention: CacheRetention) {
|
||||
let mark = match retention {
|
||||
CacheRetention::Short => json!({"type": "ephemeral"}),
|
||||
CacheRetention::Long => json!({"type": "ephemeral", "ttl": "1h"}),
|
||||
};
|
||||
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<String>,
|
||||
payloads: Vec<TransportEventPayload>,
|
||||
stop_reason: StopReason,
|
||||
usage: Usage,
|
||||
}
|
||||
|
||||
struct Failure {
|
||||
kind: FailureKind,
|
||||
message: String,
|
||||
usage: Option<Usage>,
|
||||
}
|
||||
|
||||
fn parse(bytes: &[u8]) -> Result<Done, Failure> {
|
||||
let provider_failure = |message: &str, usage: Option<Usage>| 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(),
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
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> {
|
||||
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: None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ---- failures ----
|
||||
|
||||
fn kind_of_status(status: u16) -> FailureKind {
|
||||
match status {
|
||||
401 | 403 => FailureKind::Authentication,
|
||||
429 => FailureKind::RateLimited,
|
||||
503 | 529 => FailureKind::Unavailable,
|
||||
400 => FailureKind::InvalidRequest,
|
||||
_ => FailureKind::Provider,
|
||||
}
|
||||
}
|
||||
|
||||
/// A failure the provider answered: its own type and message, bounded.
|
||||
fn http_failure(status: u16, body: &[u8]) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let parsed: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
|
||||
let error = &parsed["error"];
|
||||
let mut message = format!("anthropic-messages: HTTP {status}");
|
||||
if let Some(kind) = error["type"].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);
|
||||
}
|
||||
failed(kind_of_status(status), bounded(message), None)
|
||||
}
|
||||
|
||||
/// A failure before an answer: the deadline, the size cap, the connection.
|
||||
fn transport_failure(error: &ureq::Error) -> (Vec<TransportEvent>, 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")
|
||||
}
|
||||
_ => (FailureKind::Provider, "the request could not be completed"),
|
||||
};
|
||||
failed(kind, format!("anthropic-messages: {what}"), None)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
fn zero_usage() -> Usage {
|
||||
Usage {
|
||||
input_tokens: 0,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: 0,
|
||||
reasoning_tokens: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(
|
||||
kind: FailureKind,
|
||||
message: String,
|
||||
usage: Option<Usage>,
|
||||
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
(
|
||||
Vec::new(),
|
||||
TransportOutcome::Failed {
|
||||
kind,
|
||||
message,
|
||||
usage,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
762
crates/claude-connector/src/messages/tests.rs
Normal file
762
crates/claude-connector/src/messages/tests.rs
Normal file
|
|
@ -0,0 +1,762 @@
|
|||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
|
||||
use model_connector::ToolDefinition;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::*;
|
||||
|
||||
const KEY: &str = "sk-ant-test-key-canary-0001";
|
||||
const MODEL: &str = "claude-sonnet-5-5";
|
||||
|
||||
struct Fixed(Option<&'static str>);
|
||||
|
||||
impl TokenSource for Fixed {
|
||||
fn read(&self) -> Option<Zeroizing<String>> {
|
||||
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<Mutex<Vec<Seen>>>) {
|
||||
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 {
|
||||
key_credential: "claude-key".to_string(),
|
||||
deadline: Duration::from_secs(10),
|
||||
max_response_bytes: 1 << 20,
|
||||
},
|
||||
Box::new(Fixed(key)),
|
||||
url,
|
||||
)
|
||||
}
|
||||
|
||||
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<Usage>) {
|
||||
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::<Value>(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<u8>> = 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), 1);
|
||||
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), 1);
|
||||
assert_eq!(
|
||||
body["messages"][2]["content"][1]["cache_control"],
|
||||
json!({"type": "ephemeral"})
|
||||
);
|
||||
}
|
||||
|
||||
#[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()).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());
|
||||
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::<Value>(schema).unwrap()}
|
||||
})
|
||||
);
|
||||
assert!(body.get("tools").is_none() && body.get("tool_choice").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_required_tool_choice_is_a_system_sentence_never_a_forced_choice() {
|
||||
let mut asked = request();
|
||||
asked.tools = vec![weather_tool()];
|
||||
asked.tool_choice = ToolChoice::Required;
|
||||
let body = render(&asked).unwrap();
|
||||
assert_eq!(
|
||||
body["system"][1],
|
||||
json!({"type": "text", "text": REQUIRED_TOOL_SENTENCE})
|
||||
);
|
||||
let text = body.to_string();
|
||||
assert!(!text.contains(r#""type":"any""#) && !text.contains(r#""type":"tool""#));
|
||||
}
|
||||
|
||||
#[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":"Your credit balance is too low to access the Anthropic API."}}"#,
|
||||
),
|
||||
(500, FailureKind::Provider, "<html>bad gateway</html>"),
|
||||
] {
|
||||
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_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::Provider);
|
||||
|
||||
let silent = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let url = format!("http://{}", silent.local_addr().unwrap());
|
||||
let slow = MessagesBackend::with_parts(
|
||||
MessagesConfig {
|
||||
key_credential: "claude-key".to_string(),
|
||||
deadline: Duration::from_millis(200),
|
||||
max_response_bytes: 1 << 20,
|
||||
},
|
||||
Box::new(Fixed(Some(KEY))),
|
||||
url,
|
||||
);
|
||||
let (_, outcome) = slow.run(&request());
|
||||
assert_eq!(failure_of(&outcome).0, FailureKind::Timeout);
|
||||
drop(silent);
|
||||
}
|
||||
|
||||
#[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 {
|
||||
key_credential: "claude-key".to_string(),
|
||||
deadline: Duration::from_secs(10),
|
||||
max_response_bytes: 1024,
|
||||
},
|
||||
Box::new(Fixed(Some(KEY))),
|
||||
url,
|
||||
);
|
||||
let (_, outcome) = small.run(&request());
|
||||
assert_eq!(failure_of(&outcome).0, FailureKind::Provider);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_key_means_no_request_and_no_readiness() {
|
||||
let (url, seen) = mock(vec![(200, answer(json!([]), "end_turn", plain_usage()))]);
|
||||
let keyless = backend(url, None);
|
||||
assert_eq!(keyless.ready(), Err("token_credential"));
|
||||
let (events, outcome) = keyless.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(()));
|
||||
}
|
||||
|
||||
#[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));
|
||||
assert_eq!(backend.provider(), "anthropic-messages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_through_the_serve_loop_reaches_the_caller_as_a_valid_result() {
|
||||
use model_connector::{
|
||||
CallerAdmission, ConnectorClient, 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 backend = Arc::new(backend(url, Some(KEY)));
|
||||
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;
|
||||
thread::spawn(move || serve(listener, limits, vec![admission], &store, backend));
|
||||
|
||||
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"));
|
||||
}
|
||||
|
|
@ -526,9 +526,9 @@ fn stdin_and_stdout_failures_have_their_own_wording() {
|
|||
/// refuses it, the caller receives a transported `Failed(InvalidRequest)`
|
||||
/// result, and the claude child is never started.
|
||||
#[test]
|
||||
fn a_forced_tools_request_reaches_the_planner_is_refused_and_no_child_starts() {
|
||||
fn t_c0_oauth_still_cli_a_tools_request_is_refused_and_no_child_starts() {
|
||||
use claude_connector::{
|
||||
ChildEnv, ClaudeAuth, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, ProcessPort, RunningChild,
|
||||
ChildEnv, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, ProcessPort, RunningChild,
|
||||
SessionStore, StderrSink, TokenSource,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
|
@ -582,7 +582,6 @@ fn a_forced_tools_request_reaches_the_planner_is_refused_and_no_child_starts() {
|
|||
prompt_dir: dir.join("prompt"),
|
||||
token_credential: "t".into(),
|
||||
handle_secret_credential: "h".into(),
|
||||
auth: ClaudeAuth::OAuthToken,
|
||||
instance: "i".into(),
|
||||
limits: ClaudeCodeLimits {
|
||||
deadline: Duration::from_secs(5),
|
||||
|
|
|
|||
Loading…
Reference in a new issue