Switchyard lets LLM applications route traffic across models and providers while preserving native OpenAI and Anthropic API compatibility - enabling flexible model selection, benchmarking, and cost/performance optimization.
Rust
fix(libsy): warn when Claude Code predates sub-agent identity headers (#696)
Lin Jia4cf2c5d625e6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ad606717f..9a20cbba7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -135,6 +135,16 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).the tool. The decoder now reports `tool_use` when the completed output holdsa `function_call` or `custom_tool_call`, or when it already decoded tooldeltas, matching the buffered decoder.+- **Harnesses without sub-agent identity on sub-agent routes** — Claude Code+ sends the child identity header (`x-claude-code-agent-id`) that sub-agent+ routing needs only from version 2.1.139. Older builds send just the session+ id, so their sub-agent requests silently routed through the parent route.+ Header normalization now flags such builds on+ `switchyard_protocol::Metadata` as `subagent_identity_unsupported`, a route+ with a `subagents` table logs one warning when it sees one, and the sub-agent+ routing guide states the version floor. The new public field means downstream+ code that builds `Metadata` with a full struct literal must add it or use+ `..Metadata::default()`.- **Encrypted-only reasoning items open no summary part** — the Responsesstream encoder opened a `reasoning_summary_part` for every reasoning item andclosed it only when text had streamed, so an encrypted-only item left a partdiff --git a/crates/libsy/src/algorithms/subagent.rs b/crates/libsy/src/algorithms/subagent.rsindex a4b340a4c..74334abfd 100644--- a/crates/libsy/src/algorithms/subagent.rs+++ b/crates/libsy/src/algorithms/subagent.rs@@ -4,6 +4,7 @@//! Delegated sub-agent routing around an arbitrary parent algorithm.use std::sync::Arc;+use std::sync::atomic::{AtomicBool, Ordering};use switchyard_protocol::{Category, Metadata, Request};@@ -44,6 +45,8 @@ impl SubagentRouterConfig {pub struct SubagentRouter {parent: Arc<dyn Algorithm>,subagent: FallThrough<State>,+ /// Whether the one-time warning about a harness without sub-agent identity has been emitted.+ identity_warning_emitted: AtomicBool,}impl SubagentRouter {@@ -79,7 +82,32 @@ impl SubagentRouter {.with_classifier(Arc::new(SubagentGate::new(config.classifier))).with_classifier(Arc::new(DefaultCategoryClassifier(config.default_target)));- Ok(Self { parent, subagent })+ Ok(Self {+ parent,+ subagent,+ identity_warning_emitted: AtomicBool::new(false),+ })+ }++ /// Warns once when a harness that cannot identify its children reaches this route.+ ///+ /// Such a build sends only the session id, so its sub-agent requests look like the+ /// parent's and route through the parent algorithm. Without this the route reports+ /// itself as configured while never routing any delegated work.+ fn warn_if_subagent_identity_unsupported(&self, request: &Request) {+ let unsupported = request+ .metadata+ .as_ref()+ .is_some_and(|metadata| metadata.subagent_identity_unsupported);+ if !unsupported || self.identity_warning_emitted.swap(true, Ordering::Relaxed) {+ return;+ }+ tracing::warn!(+ target: "libsy",+ "this route has sub-agent routing but the calling harness does not send \+ sub-agent identity, so its delegated requests route through the parent route; \+ a harness upgrade may be required"+ );}}@@ -98,6 +126,7 @@ impl Algorithm for SubagentRouter {// Delegated work routes over the sub-agent's own models, never the parent's.self.subagent.execute(driver.for_subagent()?, request).await} else {+ self.warn_if_subagent_identity_unsupported(&request);self.parent.clone().route(driver, request).await}}@@ -176,6 +205,34 @@ mod tests {)?))}+ fn without_subagent_identity() -> Request {+ request(Some(Metadata {+ session_id: Some("session-1".to_string()),+ subagent_identity_unsupported: true,+ ..Metadata::default()+ }))+ }++ #[tokio::test]+ async fn harness_without_subagent_identity_warns_once_and_routes_through_the_parent()+ -> crate::Result<()> {+ // Without child identity the request is indistinguishable from the parent's, so it+ // keeps routing through the parent algorithm; the warning fires once per route.+ let router = configured(Arc::new(ScriptedClassifier {+ calls: AtomicUsize::new(0),+ }))?;+ let models = RuntimeModels::new([(Category::Any, vec![ModelId::from("parent")])].into())+ .with_subagent([(Category::Any, vec![ModelId::from("worker")])].into());+ for _ in 0..2 {+ let request = without_subagent_identity();+ let (selected, _) =+ test_drive_with_models(router.clone(), request, models.clone(), echo()).await?;+ assert_eq!(selected, "parent");+ }+ assert!(router.identity_warning_emitted.load(Ordering::Relaxed));+ Ok(())+ }+#[tokio::test]async fn routes_parent_and_children_with_affinity_and_default() -> crate::Result<()> {let classifier = Arc::new(ScriptedClassifier {diff --git a/crates/protocol/src/metadata.rs b/crates/protocol/src/metadata.rsindex a45987b57..c4e91bcab 100644--- a/crates/protocol/src/metadata.rs+++ b/crates/protocol/src/metadata.rs@@ -65,6 +65,13 @@ const TASK_ID_HEADER: &str = "x-task-id";const REQUEST_ID_HEADER: &str = "x-request-id";const CLIENT_REQUEST_ID_HEADER: &str = "x-client-request-id";+// Caller identification. Coding harnesses report their name and version here.+const USER_AGENT_HEADER: &str = "user-agent";++/// First Claude Code release whose sub-agents send `x-claude-code-agent-id`. Earlier builds+/// send only the session id, so their delegated requests look like the parent's.+const CLAUDE_CHILD_IDENTITY_VERSION: [u64; 3] = [2, 1, 139];+/// Harness-defined sub-agent kinds that carry delegated user work rather than/// harness maintenance (`compact`, `memory_consolidation`, ...). Unknown kinds/// are excluded deliberately; extend with captured request fixtures.@@ -186,6 +193,10 @@ pub struct Metadata {pub session_final: Option<bool>,/// External trace/request id for joining with the host's telemetry.pub correlation_id: Option<String>,+ /// Whether the calling harness build is known not to send child-agent identity, so its+ /// delegated sub-agent requests cannot be told apart from the parent's. Derived during+ /// header normalization from the harness's `User-Agent`.+ pub subagent_identity_unsupported: bool,/// Switchyard target that successfully served a response.pub served_model: Option<ModelId>,/// Arbitrary host-defined key/value metadata.@@ -216,6 +227,7 @@ impl Metadata {.as_deref().and_then(parse_bool),correlation_id: sy_header(headers, SWITCHYARD_REQUEST_ID_HEADER),+ subagent_identity_unsupported: claude_lacks_child_identity(headers),..Metadata::default()}}@@ -292,6 +304,32 @@ fn claude_lineage(headers: &http::HeaderMap) -> (Option<&str>, bool) {(parent, is_subagent)}+/// Whether the request comes from a Claude Code build that predates its child identity headers.+///+/// Claude Code names itself in `User-Agent` as `claude-cli/<version> (...)`. A prerelease of+/// the first release with the headers (`2.1.139-beta.1`) predates it too. Build metadata after+/// `+` is ignored. Other clients never match.+fn claude_lacks_child_identity(headers: &http::HeaderMap) -> bool {+ fn parse(user_agent: &str) -> Option<([u64; 3], bool)> {+ let tagged = user_agent+ .strip_prefix("claude-cli/")?+ .split([' ', '+'])+ .next()?;+ let (version, prerelease) = match tagged.split_once('-') {+ Some((version, _)) => (version, true),+ None => (tagged, false),+ };+ let mut parts = version.split('.').map(|part| part.parse::<u64>().ok());+ Some(([parts.next()??, parts.next()??, parts.next()??], prerelease))+ }+ header(headers, USER_AGENT_HEADER)+ .and_then(parse)+ .is_some_and(|(version, prerelease)| {+ version < CLAUDE_CHILD_IDENTITY_VERSION+ || (prerelease && version == CLAUDE_CHILD_IDENTITY_VERSION)+ })+}+/// Parses the common textual spellings of a boolean header value.fn parse_bool(value: &str) -> Option<bool> {match value.trim().to_ascii_lowercase().as_str() {@@ -487,6 +525,23 @@ mod tests {assert!(!root.is_subagent);}+ #[test]+ fn flags_claude_code_builds_without_child_identity() {+ let unsupported = |user_agent: &str| {+ metadata(&[("user-agent", user_agent)]).subagent_identity_unsupported+ };+ // Builds before the headers existed, including a prerelease of the first build with them.+ assert!(unsupported(" claude-cli/2.1.121 (external, cli) "));+ assert!(unsupported("claude-cli/2.1.139-beta.1"));+ // The first build with the headers and anything newer.+ assert!(!unsupported("claude-cli/2.1.139 (external, cli)"));+ assert!(!unsupported("claude-cli/2.1.211+build (external, cli)"));+ // Other clients and unparseable versions are never flagged.+ assert!(!unsupported("codex_cli_rs/0.120.0"));+ assert!(!unsupported("claude-cli/nightly"));+ assert!(!metadata(&[]).subagent_identity_unsupported);+ }+#[test]fn normalizes_correlation_and_session_headers_without_routing() {// Integrating-host headers are correlation data, not routing signals.diff --git a/docs/routing_algorithms/subagent_routing.md b/docs/routing_algorithms/subagent_routing.mdindex b3bdcd9f3..d22d2eb33 100644--- a/docs/routing_algorithms/subagent_routing.md+++ b/docs/routing_algorithms/subagent_routing.md@@ -110,6 +110,13 @@ that is not registered as a route is rejected before sub-agent classification.`message_hash_fallback` is not supported for sub-agent routing because affinityrequires harness-provided child identity.+Claude Code sends child identity (`x-claude-code-agent-id`) starting with version+2.1.139. Older builds send only the session id, so Switchyard cannot tell a+sub-agent request from the parent's and routes it through the parent route.+When a route with a `subagents` table sees an older Claude Code, Switchyard logs+one warning that a harness upgrade may be required. Upgrade Claude Code to+2.1.139 or later.+To send every delegated sub-agent request to one fixed target without calling aclassifier, replace the `subagents` table above with: