| 1 | use codewhale_engine::client::{CodewhaleClient, WireDialect}; |
| 2 | use codewhale_models::{ |
| 3 | ContentBlock, Message, MessageRequest, Role, SystemBlock, SystemPrompt, Tool, |
| 4 | }; |
| 5 | use codewhale_runtime::config::{Config, ProviderConfig, ProvidersConfig}; |
| 6 | use serde_json::{Value, json}; |
| 7 | |
| 8 | struct Route { |
| 9 | name: &'static str, |
| 10 | provider: &'static str, |
| 11 | model: &'static str, |
| 12 | base_url: &'static str, |
| 13 | dialect: WireDialect, |
| 14 | } |
| 15 | |
| 16 | const ROUTES: &[Route] = &[ |
| 17 | Route { |
| 18 | name: "anthropic", |
| 19 | provider: "anthropic", |
| 20 | model: "claude-sonnet-4-5", |
| 21 | base_url: "https://api.anthropic.com", |
| 22 | dialect: WireDialect::AnthropicMessages, |
| 23 | }, |
| 24 | Route { |
| 25 | name: "openai-responses", |
| 26 | provider: "responses-ledger", |
| 27 | model: "gpt-5.5", |
| 28 | base_url: "https://api.openai.com/v1", |
| 29 | dialect: WireDialect::OpenAiResponses, |
| 30 | }, |
| 31 | Route { |
| 32 | name: "deepseek", |
| 33 | provider: "deepseek", |
| 34 | model: "deepseek-v4-pro", |
| 35 | base_url: "https://api.deepseek.com", |
| 36 | dialect: WireDialect::ChatCompletions, |
| 37 | }, |
| 38 | ]; |
| 39 | |
| 40 | fn config(route: &Route) -> Config { |
| 41 | let entry = ProviderConfig { |
| 42 | api_key: Some(format!("sk-test-{}-prefix-ledger", route.name)), |
| 43 | base_url: Some(route.base_url.to_string()), |
| 44 | model: Some(route.model.to_string()), |
| 45 | ..ProviderConfig::default() |
| 46 | }; |
| 47 | let mut providers = ProvidersConfig::default(); |
| 48 | match route.provider { |
| 49 | "anthropic" => providers.anthropic = entry, |
| 50 | "responses-ledger" => { |
| 51 | providers.custom.insert( |
| 52 | route.provider.to_string(), |
| 53 | ProviderConfig { |
| 54 | kind: Some("openai-compatible".to_string()), |
| 55 | wire: Some("responses".to_string()), |
| 56 | ..entry |
| 57 | }, |
| 58 | ); |
| 59 | } |
| 60 | "deepseek" => providers.deepseek = entry, |
| 61 | other => panic!("unhandled ledger provider {other}"), |
| 62 | } |
| 63 | let mut config = Config::default(); |
| 64 | config.provider = Some(route.provider.to_string()); |
| 65 | config.providers = Some(providers); |
| 66 | config |
| 67 | } |
| 68 | |
| 69 | fn tool(name: &str, properties: Value, required: &[&str]) -> Tool { |
| 70 | serde_json::from_value(json!({ |
| 71 | "name": name, |
| 72 | "description": format!("{name} tool used by the prefix ledger"), |
| 73 | "input_schema": { |
| 74 | "type": "object", |
| 75 | "properties": properties, |
| 76 | "required": required, |
| 77 | }, |
| 78 | })) |
| 79 | .unwrap() |
| 80 | } |
| 81 | |
| 82 | fn tools() -> Vec<Tool> { |
| 83 | vec![ |
| 84 | tool( |
| 85 | "read_file", |
| 86 | json!({ |
| 87 | "path": {"type": "string", "description": "file to read"}, |
| 88 | "offset": {"type": "integer", "minimum": 0}, |
| 89 | "limit": {"type": "integer", "minimum": 1}, |
| 90 | "encoding": {"type": "string", "enum": ["utf-8", "latin1", "binary"]}, |
| 91 | }), |
| 92 | &["path"], |
| 93 | ), |
| 94 | tool( |
| 95 | "exec_shell", |
| 96 | json!({ |
| 97 | "command": {"type": "string"}, |
| 98 | "workdir": {"type": "string"}, |
| 99 | "timeout_ms": {"type": "integer"}, |
| 100 | "env": { |
| 101 | "type": "object", |
| 102 | "properties": { |
| 103 | "zeta": {"type": "string"}, |
| 104 | "alpha": {"type": "string"}, |
| 105 | "mid": {"type": "string"}, |
| 106 | }, |
| 107 | }, |
| 108 | "background": {"type": "boolean"}, |
| 109 | }), |
| 110 | &["command"], |
| 111 | ), |
| 112 | tool( |
| 113 | "edit_file", |
| 114 | json!({ |
| 115 | "path": {"type": "string"}, |
| 116 | "old_string": {"type": "string"}, |
| 117 | "new_string": {"type": "string"}, |
| 118 | "replace_all": {"type": "boolean"}, |
| 119 | "edits": { |
| 120 | "type": "array", |
| 121 | "items": { |
| 122 | "type": "object", |
| 123 | "properties": { |
| 124 | "start": {"type": "integer"}, |
| 125 | "end": {"type": "integer"}, |
| 126 | "text": {"type": "string"}, |
| 127 | }, |
| 128 | "required": ["start", "end", "text"], |
| 129 | }, |
| 130 | }, |
| 131 | }), |
| 132 | &["path"], |
| 133 | ), |
| 134 | tool( |
| 135 | "grep_files", |
| 136 | json!({ |
| 137 | "pattern": {"type": "string"}, |
| 138 | "glob": {"type": "string"}, |
| 139 | "case_sensitive": {"type": "boolean"}, |
| 140 | "max_results": {"type": "integer"}, |
| 141 | }), |
| 142 | &["pattern"], |
| 143 | ), |
| 144 | ] |
| 145 | } |
| 146 | |
| 147 | fn text(role: Role, text: &str) -> Message { |
| 148 | Message { |
| 149 | role, |
| 150 | content: vec![ContentBlock::Text { |
| 151 | text: text.to_string(), |
| 152 | cache_control: None, |
| 153 | }], |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | fn tool_call(id: &str, name: &str, input: Value) -> Message { |
| 158 | Message { |
| 159 | role: Role::Assistant, |
| 160 | content: vec![ContentBlock::ToolUse { |
| 161 | id: id.to_string(), |
| 162 | name: name.to_string(), |
| 163 | input, |
| 164 | execution_id: None, |
| 165 | caller: None, |
| 166 | thought_signature: None, |
| 167 | }], |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | fn tool_result(id: &str, content: &str) -> Message { |
| 172 | Message { |
| 173 | role: Role::User, |
| 174 | content: vec![ContentBlock::ToolResult { |
| 175 | tool_use_id: id.to_string(), |
| 176 | content: content.to_string(), |
| 177 | execution_id: None, |
| 178 | is_error: None, |
| 179 | content_blocks: None, |
| 180 | }], |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | fn first_turn() -> Vec<Message> { |
| 185 | vec![ |
| 186 | text( |
| 187 | Role::User, |
| 188 | "Find where retries are classified and summarize it.", |
| 189 | ), |
| 190 | tool_call( |
| 191 | "call_grep_1", |
| 192 | "grep_files", |
| 193 | json!({"pattern": "is_retryable", "glob": "*.rs", "max_results": 20, "case_sensitive": true}), |
| 194 | ), |
| 195 | tool_result( |
| 196 | "call_grep_1", |
| 197 | "crates/engine/src/llm_client/mod.rs:636: pub fn is_retryable_for", |
| 198 | ), |
| 199 | tool_call( |
| 200 | "call_read_1", |
| 201 | "read_file", |
| 202 | json!({"path": "crates/engine/src/llm_client/mod.rs", "offset": 620, "limit": 40}), |
| 203 | ), |
| 204 | tool_result( |
| 205 | "call_read_1", |
| 206 | "pub fn is_retryable_for(&self, operation: RetryOperation) -> bool {", |
| 207 | ), |
| 208 | ] |
| 209 | } |
| 210 | |
| 211 | fn second_turn() -> Vec<Message> { |
| 212 | let mut messages = first_turn(); |
| 213 | messages.push(text( |
| 214 | Role::Assistant, |
| 215 | "Inference retries only rate limits and pre-dispatch connect failures.", |
| 216 | )); |
| 217 | messages.push(text(Role::User, "Now check the stream-open path too.")); |
| 218 | messages.push(tool_call( |
| 219 | "call_shell_1", |
| 220 | "exec_shell", |
| 221 | json!({"command": "rg -n stream_retry_budget", "env": {"zeta": "1", "alpha": "2", "mid": "3"}, "timeout_ms": 5000}), |
| 222 | )); |
| 223 | messages.push(tool_result( |
| 224 | "call_shell_1", |
| 225 | "model_step.rs:470: stream_retry_budget", |
| 226 | )); |
| 227 | messages |
| 228 | } |
| 229 | |
| 230 | fn request(route: &Route, messages: Vec<Message>) -> MessageRequest { |
| 231 | MessageRequest { |
| 232 | model: route.model.to_string(), |
| 233 | messages, |
| 234 | max_tokens: 4096, |
| 235 | system: Some(SystemPrompt::Blocks(vec![ |
| 236 | SystemBlock { |
| 237 | block_type: "text".to_string(), |
| 238 | text: "You are Codewhale. Follow the workspace rules.".to_string(), |
| 239 | cache_control: None, |
| 240 | }, |
| 241 | SystemBlock { |
| 242 | block_type: "text".to_string(), |
| 243 | text: "Workspace: /repo. Tools run in a sandbox.".to_string(), |
| 244 | cache_control: None, |
| 245 | }, |
| 246 | ])), |
| 247 | tools: Some(tools()), |
| 248 | tool_choice: Some(json!("auto")), |
| 249 | metadata: None, |
| 250 | thinking: None, |
| 251 | reasoning_effort: None, |
| 252 | stream: Some(true), |
| 253 | temperature: None, |
| 254 | top_p: None, |
| 255 | safety_check: None, |
| 256 | title: None, |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | fn prepare(route: &Route, messages: Vec<Message>) -> Value { |
| 261 | let client = CodewhaleClient::new(&config(route)) |
| 262 | .unwrap_or_else(|error| panic!("{}: client: {error:#}", route.name)); |
| 263 | let prepared = client |
| 264 | .prepare_outbound_request(request(route, messages), true) |
| 265 | .unwrap_or_else(|error| panic!("{}: prepare: {error:#}", route.name)); |
| 266 | assert_eq!(prepared.dialect, route.dialect, "{}: dialect", route.name); |
| 267 | prepared.body |
| 268 | } |
| 269 | |
| 270 | fn without_cache_markers(value: &Value) -> Value { |
| 271 | match value { |
| 272 | Value::Object(map) => Value::Object( |
| 273 | map.iter() |
| 274 | .filter(|(key, _)| key.as_str() != "cache_control") |
| 275 | .map(|(key, value)| (key.clone(), without_cache_markers(value))) |
| 276 | .collect(), |
| 277 | ), |
| 278 | Value::Array(items) => Value::Array(items.iter().map(without_cache_markers).collect()), |
| 279 | other => other.clone(), |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | fn segment(body: &Value, key: &str) -> String { |
| 284 | serde_json::to_string(&without_cache_markers( |
| 285 | body.get(key).unwrap_or(&Value::Null), |
| 286 | )) |
| 287 | .unwrap() |
| 288 | } |
| 289 | |
| 290 | fn history_key(dialect: WireDialect) -> &'static str { |
| 291 | match dialect { |
| 292 | WireDialect::OpenAiResponses => "input", |
| 293 | WireDialect::AnthropicMessages | WireDialect::ChatCompletions => "messages", |
| 294 | WireDialect::GenerateContent => "contents", |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | fn system_key(dialect: WireDialect) -> Option<&'static str> { |
| 299 | match dialect { |
| 300 | WireDialect::AnthropicMessages => Some("system"), |
| 301 | WireDialect::OpenAiResponses => Some("instructions"), |
| 302 | WireDialect::ChatCompletions => None, |
| 303 | WireDialect::GenerateContent => Some("systemInstruction"), |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | #[test] |
| 308 | fn identical_requests_serialize_byte_identically_across_fresh_clients() { |
| 309 | for route in ROUTES { |
| 310 | let baseline = serde_json::to_string(&prepare(route, second_turn())).unwrap(); |
| 311 | for attempt in 0..8 { |
| 312 | let again = serde_json::to_string(&prepare(route, second_turn())).unwrap(); |
| 313 | assert_eq!( |
| 314 | baseline, again, |
| 315 | "{}: attempt {attempt} serialized differently", |
| 316 | route.name |
| 317 | ); |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | #[test] |
| 323 | fn appending_a_turn_keeps_system_tools_and_prior_history_byte_identical() { |
| 324 | for route in ROUTES { |
| 325 | let before = prepare(route, first_turn()); |
| 326 | let after = prepare(route, second_turn()); |
| 327 | assert_eq!( |
| 328 | segment(&before, "tools"), |
| 329 | segment(&after, "tools"), |
| 330 | "{}: tools segment moved", |
| 331 | route.name |
| 332 | ); |
| 333 | assert!( |
| 334 | before |
| 335 | .get("tools") |
| 336 | .and_then(Value::as_array) |
| 337 | .is_some_and(|tools| tools.len() == 4), |
| 338 | "{}: tools missing from body", |
| 339 | route.name |
| 340 | ); |
| 341 | if let Some(key) = system_key(route.dialect) { |
| 342 | assert!(before.get(key).is_some(), "{}: {key} missing", route.name); |
| 343 | assert_eq!( |
| 344 | segment(&before, key), |
| 345 | segment(&after, key), |
| 346 | "{}: {key} segment moved", |
| 347 | route.name |
| 348 | ); |
| 349 | } |
| 350 | let key = history_key(route.dialect); |
| 351 | let prior = before[key].as_array().expect("prior history array"); |
| 352 | let next = after[key].as_array().expect("next history array"); |
| 353 | assert!( |
| 354 | next.len() > prior.len(), |
| 355 | "{}: history did not grow", |
| 356 | route.name |
| 357 | ); |
| 358 | for (index, item) in prior.iter().enumerate() { |
| 359 | assert_eq!( |
| 360 | serde_json::to_string(&without_cache_markers(item)).unwrap(), |
| 361 | serde_json::to_string(&without_cache_markers(&next[index])).unwrap(), |
| 362 | "{}: {key}[{index}] changed after appending a turn", |
| 363 | route.name |
| 364 | ); |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 |