From fda63c3a9f6e74c00ba21652c6f308e6ae6890b0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 21:09:37 +0100 Subject: [PATCH] claude-connector messages: outages are typed as outages, Required is tool_choice any or a refusal, no redirects, thinking tokens counted Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- crates/claude-connector/src/messages.rs | 124 ++++++-- crates/claude-connector/src/messages/tests.rs | 286 +++++++++++++++++- 3 files changed, 372 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 8f14b67..eb3a1e3 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ 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 a system sentence, because the current Sonnet and Opus reject a forced tool choice. A key has no plan: no meter runs, the plan windows stay empty, and a key document refuses leases. +- `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 subscription token is read from a systemd credential and reaches the child on a diff --git a/crates/claude-connector/src/messages.rs b/crates/claude-connector/src/messages.rs index 9c57ed9..4d31b94 100644 --- a/crates/claude-connector/src/messages.rs +++ b/crates/claude-connector/src/messages.rs @@ -6,20 +6,34 @@ //! //! 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. +//! - `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 `input_tokens` apart from `cache_read_input_tokens` and +//! - 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. +//! 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. +//! +//! 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; @@ -39,8 +53,30 @@ 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."; + +/// 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)] @@ -80,6 +116,7 @@ impl MessagesBackend { let agent: ureq::Agent = ureq::Agent::config_builder() .timeout_global(Some(config.deadline)) .http_status_as_error(false) + .max_redirects(0) .build() .into(); Self { @@ -134,7 +171,8 @@ impl MessagesBackend { if !(200..300).contains(&status) { return http_failure(status, &text); } - match parse(&text) { + let required = request.tool_choice == ToolChoice::Required && !request.tools.is_empty(); + match parse(&text, required) { Ok(done) => { let events = done .payloads @@ -189,11 +227,10 @@ fn render(request: &ProviderRequest) -> Result { 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)); + body.insert( + "system".into(), + json!([{"type": "text", "text": request.instructions}]), + ); let mut messages = messages_of(&request.input)?; if let Some(retention) = request.cache_retention { @@ -213,11 +250,25 @@ fn render(request: &ProviderRequest) -> Result { })); } 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 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); } } @@ -372,7 +423,9 @@ struct Failure { usage: Option, } -fn parse(bytes: &[u8]) -> Result { +/// `required`: the request forced a tool call, so an answer without one is a +/// failure, never a completed turn. +fn parse(bytes: &[u8], required: bool) -> Result { let provider_failure = |message: &str, usage: Option| Failure { kind: FailureKind::Provider, message: format!("anthropic-messages: {message}"), @@ -412,6 +465,13 @@ fn parse(bytes: &[u8]) -> Result { _ => {} } } + 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, @@ -442,18 +502,27 @@ fn usage_of(usage: &Value) -> Option { cache_read_tokens: count("cache_read_input_tokens"), cache_write_tokens: count("cache_creation_input_tokens"), output_tokens: count("output_tokens"), - reasoning_tokens: None, + 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, + 401 | 402 | 403 => FailureKind::Authentication, + 408 | 504 => FailureKind::Timeout, 429 => FailureKind::RateLimited, - 503 | 529 => FailureKind::Unavailable, + 300..=399 | 500..=599 => FailureKind::Unavailable, 400 => FailureKind::InvalidRequest, _ => FailureKind::Provider, } @@ -485,7 +554,10 @@ fn transport_failure(error: &ureq::Error) -> (Vec, TransportOutc ureq::Error::BodyExceedsLimit(_) => { (FailureKind::Provider, "the response passed its size cap") } - _ => (FailureKind::Provider, "the request could not be completed"), + 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) } diff --git a/crates/claude-connector/src/messages/tests.rs b/crates/claude-connector/src/messages/tests.rs index ba3bae2..170019b 100644 --- a/crates/claude-connector/src/messages/tests.rs +++ b/crates/claude-connector/src/messages/tests.rs @@ -494,10 +494,14 @@ fn every_stop_reason_the_api_names_maps() { ("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")); + let done = + parse(reply.as_bytes(), false).unwrap_or_else(|_| panic!("{name} did not parse")); assert_eq!(done.stop_reason, expected); } - let unknown = parse(answer(json!([]), "pause_turn", plain_usage()).as_bytes()); + let unknown = parse( + answer(json!([]), "pause_turn", plain_usage()).as_bytes(), + false, + ); let failure = unknown.err().unwrap(); assert_eq!(failure.kind, FailureKind::Provider); assert_eq!(failure.usage.unwrap().output_tokens, 7); @@ -540,17 +544,112 @@ fn t_c0_schema_by_forced_tool() { } #[test] -fn a_required_tool_choice_is_a_system_sentence_never_a_forced_choice() { +fn a_required_tool_choice_is_any_where_accepted_and_never_touches_system() { + for model in [ + "claude-haiku-5-5", + "claude-opus-5", + "claude-sonnet-5", + "claude-opus-4-8", + "claude-haiku-4-5-20251001", + "claude-sonnet-4-5-20250929", + ] { + let mut asked = request(); + asked.model = model.to_string(); + asked.tools = vec![weather_tool()]; + let auto = render(&asked).unwrap(); + asked.tool_choice = ToolChoice::Required; + let body = render(&asked).unwrap(); + assert_eq!(body["tool_choice"], json!({"type": "any"}), "{model}"); + assert_eq!(body["system"], auto["system"], "{model}"); + assert_eq!(body["system"].as_array().unwrap().len(), 1); + asked.parallel_tool_calls = false; + assert_eq!( + render(&asked).unwrap()["tool_choice"], + json!({"type": "any", "disable_parallel_tool_use": true}), + "{model}" + ); + } +} + +#[test] +fn a_required_tool_choice_is_refused_on_a_model_that_rejects_it() { + for model in [ + "claude-sonnet-5-5", + "claude-opus-5-5", + "claude-fable-5-2", + "claude-mythos-5-1", + "claude-unheard-of-9", + ] { + let mut asked = request(); + asked.model = model.to_string(); + asked.tools = vec![weather_tool()]; + asked.tool_choice = ToolChoice::Required; + let refusal = render(&asked).unwrap_err(); + assert!( + refusal.contains("required tool choice"), + "{model}: {refusal}" + ); + // Auto is still served, with the same system block. + asked.tool_choice = ToolChoice::Auto; + assert_eq!( + render(&asked).unwrap()["system"].as_array().unwrap().len(), + 1 + ); + } + // Over the wire: a typed refusal, no request sent. + let (url, seen) = mock(vec![(200, answer(json!([]), "end_turn", plain_usage()))]); let mut asked = request(); asked.tools = vec![weather_tool()]; asked.tool_choice = ToolChoice::Required; - let 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""#)); + let (events, outcome) = backend(url, Some(KEY)).run(&asked); + assert!(events.is_empty()); + assert_eq!(failure_of(&outcome).0, FailureKind::InvalidRequest); + assert!(seen.lock().unwrap().is_empty()); +} + +#[test] +fn a_required_turn_without_a_tool_call_fails_and_is_never_completed() { + let mut asked = request(); + asked.model = "claude-haiku-5-5".to_string(); + asked.tools = vec![weather_tool()]; + asked.tool_choice = ToolChoice::Required; + let (url, _) = mock(vec![( + 200, + answer( + json!([{"type": "text", "text": "No tool needed."}]), + "end_turn", + plain_usage(), + ), + )]); + let (events, outcome) = backend(url, Some(KEY)).run(&asked); + assert!(events.is_empty()); + let (kind, message, usage) = failure_of(&outcome); + assert_eq!(kind, FailureKind::Provider); + assert!(message.contains("required tool call did not come")); + assert_eq!(usage.as_ref().map(|u| u.output_tokens), Some(7)); + + // With the call present it completes; an Auto turn without one completes too. + let (url, _) = mock(vec![( + 200, + answer( + json!([{"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {"city": "Oslo"}}]), + "tool_use", + plain_usage(), + ), + )]); + let (_, outcome) = backend(url, Some(KEY)).run(&asked); + assert_eq!(*completed(&outcome).0, StopReason::ToolUse); + let (url, _) = mock(vec![( + 200, + answer( + json!([{"type": "text", "text": "hi"}]), + "end_turn", + plain_usage(), + ), + )]); + asked.tool_choice = ToolChoice::Auto; + let (_, outcome) = backend(url, Some(KEY)).run(&asked); + assert_eq!(*completed(&outcome).0, StopReason::EndTurn); } #[test] @@ -586,7 +685,27 @@ fn t_c0_http_errors_typed() { 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, "bad gateway"), + ( + 402, + FailureKind::Authentication, + r#"{"type":"error","error":{"type":"billing_error","message":"credit exhausted"}}"#, + ), + ( + 500, + FailureKind::Unavailable, + r#"{"type":"error","error":{"type":"api_error","message":"internal"}}"#, + ), + (502, FailureKind::Unavailable, "bad gateway"), + ( + 504, + FailureKind::Timeout, + r#"{"type":"error","error":{"type":"timeout_error","message":"slow"}}"#, + ), + ( + 404, + FailureKind::Provider, + r#"{"type":"error","error":{"type":"not_found_error","message":"no model"}}"#, + ), ] { let (url, _) = mock(vec![(status, body.to_string())]); let (events, outcome) = backend(url, Some(KEY)).run(&request()); @@ -613,7 +732,7 @@ fn a_dead_endpoint_and_a_slow_one_are_typed() { 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); + assert_eq!(failure_of(&outcome).0, FailureKind::Unavailable); let silent = TcpListener::bind("127.0.0.1:0").unwrap(); let url = format!("http://{}", silent.local_addr().unwrap()); @@ -649,7 +768,148 @@ fn a_response_over_its_cap_is_a_provider_failure() { url, ); let (_, outcome) = small.run(&request()); - assert_eq!(failure_of(&outcome).0, FailureKind::Provider); + let (kind, message, _) = failure_of(&outcome); + assert_eq!(kind, FailureKind::Provider); + assert_eq!( + message, + "anthropic-messages: the response passed its size cap" + ); +} + +#[test] +fn a_receipt_message_is_bounded_on_a_char_boundary() { + let at_cap = "a".repeat(MESSAGE_BYTES); + assert_eq!(bounded(at_cap.clone()), at_cap); + assert_eq!(bounded("a".repeat(MESSAGE_BYTES + 1)), at_cap); + assert_eq!(bounded("short".to_string()), "short"); + // A three-byte char straddling the cap is dropped whole, one byte in or two. + for lead in [MESSAGE_BYTES - 1, MESSAGE_BYTES - 2] { + let text = format!("{}{}", "a".repeat(lead), "\u{20ac}\u{20ac}"); + let cut = bounded(text); + assert_eq!(cut, "a".repeat(lead)); + } + // A char that ends exactly on the cap is kept. + let text = format!("{}\u{20ac}tail", "a".repeat(MESSAGE_BYTES - 3)); + assert_eq!( + bounded(text), + format!("{}\u{20ac}", "a".repeat(MESSAGE_BYTES - 3)) + ); + // A provider's long message reaches the receipt bounded. + let long = + json!({"type": "error", "error": {"type": "api_error", "message": "x".repeat(5000)}}); + let (_, outcome) = http_failure(500, long.to_string().as_bytes()); + assert_eq!(failure_of(&outcome).1.len(), MESSAGE_BYTES); +} + +#[test] +fn a_redirect_is_a_failure_and_the_key_goes_nowhere_else() { + let target = TcpListener::bind("127.0.0.1:0").unwrap(); + let elsewhere = format!("http://{}/stolen", target.local_addr().unwrap()); + target.set_nonblocking(true).unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url2 = format!("http://{}", listener.local_addr().unwrap()); + let hits = Arc::new(Mutex::new(0_u32)); + let counted = hits.clone(); + let location = elsewhere.clone(); + thread::spawn(move || { + for _ in 0..2 { + let Ok((mut stream, _)) = listener.accept() else { + return; + }; + *counted.lock().unwrap() += 1; + let mut chunk = [0_u8; 8192]; + let _ = stream.read(&mut chunk); + let _ = stream.write_all( + format!( + "HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) + .as_bytes(), + ); + } + }); + let (events, outcome) = backend(url2, Some(KEY)).run(&request()); + assert!(events.is_empty()); + let (kind, message, _) = failure_of(&outcome); + assert_eq!(kind, FailureKind::Unavailable); + assert!(message.starts_with("anthropic-messages: HTTP 302")); + assert_eq!(*hits.lock().unwrap(), 1); + assert!( + target.accept().is_err(), + "the redirect target was contacted" + ); +} + +#[test] +fn thinking_tokens_are_reasoning_tokens() { + let reply = answer( + json!([{"type": "text", "text": "hi"}]), + "end_turn", + json!({ + "input_tokens": 5, + "output_tokens": 90, + "output_tokens_details": {"thinking_tokens": 64} + }), + ); + let (url, _) = mock(vec![(200, reply)]); + let (_, outcome) = backend(url, Some(KEY)).run(&request()); + let (_, usage) = completed(&outcome); + assert_eq!(usage.output_tokens, 90); + assert_eq!(usage.reasoning_tokens, Some(64)); +} + +#[test] +fn tool_results_come_first_in_their_user_message() { + let mut asked = request(); + asked.input = vec![ + InputItem::UserText { + text: "go".to_string(), + }, + InputItem::ToolCall { + call_id: "toolu_01X".to_string(), + name: "get_weather".to_string(), + arguments: r#"{"city":"Oslo"}"#.to_string(), + }, + InputItem::UserText { + text: "first, text".to_string(), + }, + InputItem::ToolResult { + call_id: "toolu_01X".to_string(), + output: "cold".to_string(), + }, + InputItem::UserText { + text: "then, more text".to_string(), + }, + ]; + asked.tools = vec![weather_tool()]; + let body = render(&asked).unwrap(); + let last = body["messages"][2]["content"].as_array().unwrap(); + let types: Vec<&str> = last.iter().map(|b| b["type"].as_str().unwrap()).collect(); + assert_eq!(types, ["tool_result", "text", "text"]); + assert_eq!(last[1]["text"], "first, text"); + assert_eq!(last[2]["text"], "then, more text"); + // An assistant message is never reordered. + let mut asked = request(); + asked.input = vec![ + InputItem::AssistantText { + text: "a".to_string(), + }, + InputItem::ToolCall { + call_id: "toolu_01X".to_string(), + name: "get_weather".to_string(), + arguments: "{}".to_string(), + }, + InputItem::AssistantText { + text: "b".to_string(), + }, + ]; + let body = render(&asked).unwrap(); + let types: Vec<&str> = body["messages"][0]["content"] + .as_array() + .unwrap() + .iter() + .map(|b| b["type"].as_str().unwrap()) + .collect(); + assert_eq!(types, ["text", "tool_use", "text"]); } #[test]