Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| edf2f8e03c | |||
| 80c1fc6a69 |
16 changed files with 2198 additions and 46 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"
|
||||
|
|
|
|||
|
|
@ -50,10 +50,11 @@ Crate `crates/claude-connector` (library and the `claude-connector` binary that
|
|||
- 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
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
|
|
|
|||
|
|
@ -261,7 +261,7 @@ impl ClaudeCodeBackend {
|
|||
deadline,
|
||||
&request.model,
|
||||
request.output_schema_json.as_deref(),
|
||||
&self.quota,
|
||||
Some(&*self.quota),
|
||||
);
|
||||
child.kill();
|
||||
child.wait();
|
||||
|
|
@ -367,7 +367,7 @@ fn read_stream(
|
|||
deadline: Instant,
|
||||
model: &str,
|
||||
schema: Option<&str>,
|
||||
quota: &QuotaCell,
|
||||
quota: Option<&QuotaCell>,
|
||||
) -> Result<Finished, Failure> {
|
||||
let mut state = StreamState::new(model, schema, quota);
|
||||
let finished = loop {
|
||||
|
|
|
|||
|
|
@ -674,6 +674,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.
|
||||
|
|
@ -2113,7 +2122,16 @@ fn quota_of(rig: &Rig) -> model_connector::PlanQuotaSnapshot {
|
|||
|
||||
/// The windows with their observation stamps zeroed, for comparing readings.
|
||||
fn readings(rig: &Rig) -> Vec<model_connector::PlanQuota> {
|
||||
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<u64>) -> Vec<model_connector::PlanQuota> {
|
||||
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;
|
||||
}
|
||||
|
|
@ -2764,9 +2782,10 @@ 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;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,27 @@
|
|||
use std::path::PathBuf;
|
||||
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 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, given to the `claude` CLI child by
|
||||
/// [`ClaudeCodeBackend`](crate::ClaudeCodeBackend). The plan's usage is
|
||||
/// metered.
|
||||
OAuthToken,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
/// What the connector's binary hands the backend. Every path is absolute.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ClaudeCodeConfig {
|
||||
|
|
@ -22,7 +38,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
|
||||
|
|
|
|||
|
|
@ -25,7 +25,8 @@ use crate::unit::SystemdUnits;
|
|||
#[cfg(unix)]
|
||||
use crate::meter;
|
||||
use crate::{
|
||||
ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource, StderrSink,
|
||||
ClaudeAuth, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource,
|
||||
MessagesBackend, MessagesConfig, StderrSink,
|
||||
};
|
||||
|
||||
const CONFIG_KEY: &str = "runtime";
|
||||
|
|
@ -106,6 +107,11 @@ pub struct ClaudeConnectorConfig {
|
|||
/// least 32 bytes), the key every handle is authenticated with.
|
||||
#[cultcache(key = 22)]
|
||||
pub handle_secret_credential: String,
|
||||
/// Which credential `token_credential` holds: the subscription token, or an
|
||||
/// Anthropic API key. A document written before this field existed is refused at
|
||||
/// load (the canonical-form check): the installer authors the document again.
|
||||
#[cultcache(key = 23)]
|
||||
pub auth: ClaudeAuth,
|
||||
}
|
||||
|
||||
/// A refusal. It names the field or stage that failed and nothing the
|
||||
|
|
@ -242,6 +248,13 @@ impl ClaudeConnectorConfig {
|
|||
}
|
||||
|
||||
fn validate_leases(&self) -> Result<(), ConfigError> {
|
||||
// A key has no plan and is never lent: no lease socket, no lease row, whatever else the
|
||||
// document says. Personas call with their own connection keys and need neither.
|
||||
if self.auth == ClaudeAuth::ApiKey
|
||||
&& (self.lease_socket.is_some() || !self.lease_callers.is_empty())
|
||||
{
|
||||
return Err(ConfigError::Invalid("auth"));
|
||||
}
|
||||
let Some(socket) = &self.lease_socket else {
|
||||
return if self.lease_callers.is_empty() {
|
||||
Ok(())
|
||||
|
|
@ -291,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,
|
||||
|
|
@ -436,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)?;
|
||||
}
|
||||
|
|
@ -550,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(
|
||||
|
|
@ -565,10 +602,15 @@ fn serve_config_with(
|
|||
.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. An API key has no subscription plan to read:
|
||||
// no meter runs, the cell stays empty, and no lease waits for it.
|
||||
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);
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Some(socket) = &config.lease_socket {
|
||||
|
|
@ -640,6 +682,7 @@ mod tests {
|
|||
instance: "persona-a".to_string(),
|
||||
token_credential: "claude-token".to_string(),
|
||||
handle_secret_credential: "claude-handle-secret".to_string(),
|
||||
auth: ClaudeAuth::OAuthToken,
|
||||
deadline_ms: 600_000,
|
||||
max_line_bytes: 4 << 20,
|
||||
max_total_bytes: 64 << 20,
|
||||
|
|
|
|||
|
|
@ -13,13 +13,13 @@ use model_connector::{ProviderRequest, ReasoningEffort};
|
|||
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.
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ mod handle;
|
|||
mod launch;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod lease;
|
||||
mod messages;
|
||||
mod meter;
|
||||
mod process;
|
||||
mod quota;
|
||||
|
|
@ -19,12 +20,13 @@ mod stream;
|
|||
mod unit;
|
||||
|
||||
pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource};
|
||||
pub use config::{ClaudeCodeConfig, ClaudeCodeLimits};
|
||||
pub use config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits};
|
||||
pub use daemon::{
|
||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, check_ready, load_config, write_config,
|
||||
};
|
||||
#[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")]
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ use std::process::ExitCode;
|
|||
|
||||
use claude_connector::ask::{self, AskArgs, AskError};
|
||||
use claude_connector::{
|
||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready,
|
||||
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready,
|
||||
load_config, write_config,
|
||||
};
|
||||
use model_connector::{CallerConfig, LeaseTurn, frame_bytes_for_payload};
|
||||
|
|
@ -159,7 +159,8 @@ const CALLER: [&str; 5] = [
|
|||
"--max-output-tokens",
|
||||
];
|
||||
|
||||
const INIT: [&str; 21] = [
|
||||
const INIT: [&str; 22] = [
|
||||
"--auth",
|
||||
"--listen",
|
||||
"--replay-store",
|
||||
"--claude-binary",
|
||||
|
|
@ -240,6 +241,15 @@ impl Flags {
|
|||
.map_err(|_| Failure::Malformed(name))
|
||||
}
|
||||
|
||||
/// Which credential `--token-credential` names: `oauth-token` (the default) or `api-key`.
|
||||
fn auth(&self) -> Result<ClaudeAuth, Failure> {
|
||||
match self.single.get("--auth").map(String::as_str) {
|
||||
None | Some("oauth-token") => Ok(ClaudeAuth::OAuthToken),
|
||||
Some("api-key") => Ok(ClaudeAuth::ApiKey),
|
||||
Some(_) => Err(Failure::Malformed("--auth")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of turn a leasing account serves: `self` or `persona`.
|
||||
fn turn(&self) -> Result<LeaseTurn, Failure> {
|
||||
match self.text("--turn")?.as_str() {
|
||||
|
|
@ -391,6 +401,7 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
|
|||
lease_callers,
|
||||
lease_max_ms: flags.number_or("--lease-max-ms", 3_600_000)?,
|
||||
handle_secret_credential: flags.text("--handle-secret-credential")?,
|
||||
auth: flags.auth()?,
|
||||
};
|
||||
// Validate before the secret file exists: a refused document leaves nothing.
|
||||
config.validate()?;
|
||||
|
|
|
|||
626
crates/claude-connector/src/messages.rs
Normal file
626
crates/claude-connector/src/messages.rs
Normal file
|
|
@ -0,0 +1,626 @@
|
|||
//! 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`, `claude-opus-5-5` and any model
|
||||
//! [`rejects_forced_tool_choice`] does not name answer a forced
|
||||
//! `tool_choice` (`any`, `tool`) with a 400. [`ToolChoice::Required`] is
|
||||
//! `tool_choice: any` on a model that accepts it and a typed refusal before
|
||||
//! sending on one that does not; the request's `system` never depends on it.
|
||||
//! Thinking is `{"type":"adaptive"}` with `output_config.effort`
|
||||
//! (`thinking.budget_tokens` is rejected), 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 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`.
|
||||
//!
|
||||
//! 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, 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;
|
||||
|
||||
/// Whether the API answers `tool_choice: any` with a 400 for this model, by
|
||||
/// the table in the tool-use docs (read 2026-11-29). A model not named as
|
||||
/// accepting it is treated as rejecting it, so a new model is refused here
|
||||
/// until someone reads its row.
|
||||
fn rejects_forced_tool_choice(model: &str) -> bool {
|
||||
let base = match model.rsplit_once('-') {
|
||||
Some((base, date)) if date.len() == 8 && date.bytes().all(|b| b.is_ascii_digit()) => base,
|
||||
_ => model,
|
||||
};
|
||||
!matches!(
|
||||
base,
|
||||
"claude-opus-5"
|
||||
| "claude-sonnet-5"
|
||||
| "claude-haiku-5-5"
|
||||
| "claude-haiku-4-5"
|
||||
| "claude-opus-4-8"
|
||||
| "claude-opus-4-7"
|
||||
| "claude-opus-4-6"
|
||||
| "claude-opus-4-5"
|
||||
| "claude-sonnet-4-6"
|
||||
| "claude-sonnet-4-5"
|
||||
)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
.max_redirects(0)
|
||||
.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);
|
||||
}
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
body.insert(
|
||||
"system".into(),
|
||||
json!([{"type": "text", "text": request.instructions}]),
|
||||
);
|
||||
|
||||
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));
|
||||
let kind = if request.tool_choice == ToolChoice::Required {
|
||||
if rejects_forced_tool_choice(&request.model) {
|
||||
return Err(format!(
|
||||
"model {} does not accept a required tool choice",
|
||||
request.model
|
||||
));
|
||||
}
|
||||
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(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>,
|
||||
}
|
||||
|
||||
/// `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<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(),
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
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> {
|
||||
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 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.
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(error: &Value) -> bool {
|
||||
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))
|
||||
})
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
let kind = if status == 400 && spend_exhausted(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.
|
||||
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")
|
||||
}
|
||||
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!("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;
|
||||
1095
crates/claude-connector/src/messages/tests.rs
Normal file
1095
crates/claude-connector/src/messages/tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -155,7 +155,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
|
||||
|
|
|
|||
|
|
@ -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<String>,
|
||||
texts: Vec<String>,
|
||||
message_id: Option<String>,
|
||||
|
|
@ -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::<Value>(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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -526,7 +526,7 @@ 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, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, ProcessPort, RunningChild,
|
||||
SessionStore, StderrSink, TokenSource,
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use std::process::{Command, Output};
|
|||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use claude_connector::{
|
||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, load_config, write_config,
|
||||
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, load_config, write_config,
|
||||
};
|
||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use model_connector::{CallerConfig, LeaseTurn};
|
||||
|
|
@ -53,6 +53,7 @@ fn valid() -> ClaudeConnectorConfig {
|
|||
instance: "persona-a".to_string(),
|
||||
token_credential: "claude-token".to_string(),
|
||||
handle_secret_credential: "claude-handle-secret".to_string(),
|
||||
auth: ClaudeAuth::OAuthToken,
|
||||
deadline_ms: 600_000,
|
||||
max_line_bytes: 4 << 20,
|
||||
max_total_bytes: 64 << 20,
|
||||
|
|
@ -295,3 +296,205 @@ 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 the_auth_choice_round_trips() {
|
||||
let scratch = Scratch::new();
|
||||
let path = scratch.path("connector.cc");
|
||||
let keyed = ClaudeConnectorConfig {
|
||||
auth: ClaudeAuth::ApiKey,
|
||||
lease_socket: None,
|
||||
lease_callers: vec![],
|
||||
..valid()
|
||||
};
|
||||
write_config(&path, &keyed).unwrap();
|
||||
assert_eq!(load_config(&path).unwrap().auth, ClaudeAuth::ApiKey);
|
||||
}
|
||||
|
||||
/// A document written before the auth field existed: the same type id, keys 0 to 22.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(type = "gamecult.model_connector.claude_connector_config.v2")]
|
||||
struct BeforeAuth {
|
||||
#[cultcache(key = 0)]
|
||||
listen: String,
|
||||
#[cultcache(key = 1)]
|
||||
replay_store: PathBuf,
|
||||
#[cultcache(key = 2)]
|
||||
claude_binary: PathBuf,
|
||||
#[cultcache(key = 3)]
|
||||
claude_binary_sha256: [u8; 32],
|
||||
#[cultcache(key = 4)]
|
||||
work_dir: PathBuf,
|
||||
#[cultcache(key = 5)]
|
||||
config_dir: PathBuf,
|
||||
#[cultcache(key = 6)]
|
||||
prompt_dir: PathBuf,
|
||||
#[cultcache(key = 7)]
|
||||
instance: String,
|
||||
#[cultcache(key = 8)]
|
||||
token_credential: String,
|
||||
#[cultcache(key = 9)]
|
||||
deadline_ms: u64,
|
||||
#[cultcache(key = 10)]
|
||||
max_line_bytes: usize,
|
||||
#[cultcache(key = 11)]
|
||||
max_total_bytes: usize,
|
||||
#[cultcache(key = 12)]
|
||||
stderr_tail_bytes: usize,
|
||||
#[cultcache(key = 13)]
|
||||
max_frame_bytes: usize,
|
||||
#[cultcache(key = 14)]
|
||||
max_connections: usize,
|
||||
#[cultcache(key = 15)]
|
||||
socket_timeout_ms: u64,
|
||||
#[cultcache(key = 16)]
|
||||
max_expiry_skew_ms: u64,
|
||||
#[cultcache(key = 17)]
|
||||
callers: Vec<CallerConfig>,
|
||||
#[cultcache(key = 19)]
|
||||
lease_socket: Option<PathBuf>,
|
||||
#[cultcache(key = 20)]
|
||||
lease_callers: Vec<LeaseCallerConfig>,
|
||||
#[cultcache(key = 21)]
|
||||
lease_max_ms: u64,
|
||||
#[cultcache(key = 22)]
|
||||
handle_secret_credential: String,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_from_before_the_auth_field_is_refused_until_it_is_authored_again() {
|
||||
let scratch = Scratch::new();
|
||||
let path = scratch.path("before.cc");
|
||||
let now = valid();
|
||||
{
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<BeforeAuth>().unwrap();
|
||||
cache
|
||||
.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))
|
||||
.unwrap();
|
||||
cache
|
||||
.put(
|
||||
"runtime".to_string(),
|
||||
&BeforeAuth {
|
||||
listen: now.listen.clone(),
|
||||
replay_store: now.replay_store.clone(),
|
||||
claude_binary: now.claude_binary.clone(),
|
||||
claude_binary_sha256: now.claude_binary_sha256,
|
||||
work_dir: now.work_dir.clone(),
|
||||
config_dir: now.config_dir.clone(),
|
||||
prompt_dir: now.prompt_dir.clone(),
|
||||
instance: now.instance.clone(),
|
||||
token_credential: now.token_credential.clone(),
|
||||
deadline_ms: now.deadline_ms,
|
||||
max_line_bytes: now.max_line_bytes,
|
||||
max_total_bytes: now.max_total_bytes,
|
||||
stderr_tail_bytes: now.stderr_tail_bytes,
|
||||
max_frame_bytes: now.max_frame_bytes,
|
||||
max_connections: now.max_connections,
|
||||
socket_timeout_ms: now.socket_timeout_ms,
|
||||
max_expiry_skew_ms: now.max_expiry_skew_ms,
|
||||
callers: now.callers.clone(),
|
||||
lease_socket: now.lease_socket.clone(),
|
||||
lease_callers: now.lease_callers.clone(),
|
||||
lease_max_ms: now.lease_max_ms,
|
||||
handle_secret_credential: now.handle_secret_credential.clone(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert!(matches!(load_config(&path), Err(ConfigError::Store)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_init_takes_the_auth_flag_and_refuses_an_unknown_one() {
|
||||
let auth_of = |extra: &[&str]| {
|
||||
let scratch = Scratch::new();
|
||||
let made = init(&scratch, &init_flags(&scratch, extra));
|
||||
made.status
|
||||
.success()
|
||||
.then(|| load_config(&scratch.path("connector.cc")).unwrap().auth)
|
||||
};
|
||||
assert_eq!(auth_of(&[]), Some(ClaudeAuth::OAuthToken));
|
||||
assert_eq!(auth_of(&["--auth", "oauth-token"]), Some(ClaudeAuth::OAuthToken));
|
||||
assert_eq!(auth_of(&["--auth", "api-key"]), Some(ClaudeAuth::ApiKey));
|
||||
assert_eq!(auth_of(&["--auth", "key"]), None);
|
||||
}
|
||||
|
||||
/// The document an operator could author by hand around `write_config`'s refusal: a key and a lease.
|
||||
fn keyed_with_a_lease() -> ClaudeConnectorConfig {
|
||||
ClaudeConnectorConfig {
|
||||
auth: ClaudeAuth::ApiKey,
|
||||
..valid()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_is_never_lent_so_no_lease_socket_or_row_may_accompany_it() {
|
||||
assert_eq!(refused(&keyed_with_a_lease()), "auth");
|
||||
let socket_only = ClaudeConnectorConfig {
|
||||
lease_callers: vec![],
|
||||
..keyed_with_a_lease()
|
||||
};
|
||||
assert_eq!(refused(&socket_only), "auth");
|
||||
let rows_only = ClaudeConnectorConfig {
|
||||
lease_socket: None,
|
||||
..keyed_with_a_lease()
|
||||
};
|
||||
assert_eq!(refused(&rows_only), "auth");
|
||||
let personas_only = ClaudeConnectorConfig {
|
||||
lease_socket: None,
|
||||
lease_callers: vec![],
|
||||
..keyed_with_a_lease()
|
||||
};
|
||||
assert!(personas_only.validate().is_ok());
|
||||
let scratch = Scratch::new();
|
||||
assert!(write_config(&scratch.path("keyed.cc"), &keyed_with_a_lease()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_init_refuses_a_key_with_a_lease_and_accepts_it_without() {
|
||||
let lease = [
|
||||
"--lease-socket",
|
||||
"/run/claude-connector/lease.sock",
|
||||
"--lease-user",
|
||||
"mind-a-self",
|
||||
"--turn",
|
||||
"self",
|
||||
"--lease-unit-instance",
|
||||
"a",
|
||||
];
|
||||
let scratch = Scratch::new();
|
||||
let leased = init(&scratch, &init_flags(&scratch, &[&["--auth", "api-key"], &lease[..]].concat()));
|
||||
assert!(!leased.status.success(), "{leased:?}");
|
||||
assert!(!scratch.path("connector.cc").exists());
|
||||
let scratch = Scratch::new();
|
||||
let bare = init(&scratch, &init_flags(&scratch, &["--auth", "api-key"]));
|
||||
assert!(bare.status.success(), "{bare:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_and_check_refuse_a_key_document_that_carries_a_lease() {
|
||||
let scratch = Scratch::new();
|
||||
let path = scratch.path("handmade.cc");
|
||||
{
|
||||
// Written around write_config, which would refuse it.
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<ClaudeConnectorConfig>().unwrap();
|
||||
cache
|
||||
.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))
|
||||
.unwrap();
|
||||
cache
|
||||
.put("runtime".to_string(), &keyed_with_a_lease())
|
||||
.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:?}");
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stderr).contains("auth"),
|
||||
"{args:?}: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue