| 1 | //! End-to-end shape lock for the per-model-call `turn_usage` event on the |
| 2 | //! `codewhale exec --output-format stream-json` stream (#52 / FINISH-0.9.4). |
| 3 | //! |
| 4 | //! A `wiremock` OpenAI-compatible endpoint stands in for the provider. Two |
| 5 | //! cases pin the contract: |
| 6 | //! |
| 7 | //! - usage reported by the provider -> exactly one `turn_usage` event per |
| 8 | //! model call, carrying the reported input/output/reasoning/cache fields, |
| 9 | //! and the pre-existing event sequence (`content` … `metadata` → `done`) |
| 10 | //! is unchanged for existing consumers; |
| 11 | //! - usage absent from the provider stream -> no `turn_usage` event at all |
| 12 | //! (honest absence, never fabricated zeros-as-data). |
| 13 | |
| 14 | #![cfg(unix)] |
| 15 | |
| 16 | use std::io::Read; |
| 17 | use std::process::{Command, Stdio}; |
| 18 | use std::time::Duration; |
| 19 | |
| 20 | use serde_json::{Value, json}; |
| 21 | use tempfile::TempDir; |
| 22 | use wait_timeout::ChildExt; |
| 23 | use wiremock::matchers::{method, path}; |
| 24 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 25 | |
| 26 | const TEST_MODEL: &str = "turn-usage-model"; |
| 27 | const RUN_TIMEOUT: Duration = Duration::from_secs(60); |
| 28 | |
| 29 | fn sse_chunk(value: Value) -> String { |
| 30 | format!( |
| 31 | "data: {}\n\n", |
| 32 | serde_json::to_string(&value).expect("SSE JSON") |
| 33 | ) |
| 34 | } |
| 35 | |
| 36 | /// Final-answer SSE whose closing chunk reports usage with reasoning and |
| 37 | /// DeepSeek-style prompt-cache fields. |
| 38 | fn answer_sse_with_usage(answer: &str) -> String { |
| 39 | [ |
| 40 | sse_chunk(json!({ |
| 41 | "id": "chatcmpl-usage", |
| 42 | "object": "chat.completion.chunk", |
| 43 | "model": TEST_MODEL, |
| 44 | "choices": [{"index": 0, "delta": {"content": answer}, "finish_reason": null}] |
| 45 | })), |
| 46 | sse_chunk(json!({ |
| 47 | "id": "chatcmpl-usage", |
| 48 | "object": "chat.completion.chunk", |
| 49 | "model": TEST_MODEL, |
| 50 | "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], |
| 51 | "usage": { |
| 52 | "prompt_tokens": 20, |
| 53 | "completion_tokens": 8, |
| 54 | "total_tokens": 28, |
| 55 | "completion_tokens_details": {"reasoning_tokens": 5}, |
| 56 | "prompt_cache_hit_tokens": 12, |
| 57 | "prompt_cache_miss_tokens": 8 |
| 58 | } |
| 59 | })), |
| 60 | "data: [DONE]\n\n".to_string(), |
| 61 | ] |
| 62 | .join("") |
| 63 | } |
| 64 | |
| 65 | /// Final-answer SSE whose provider never reports usage. |
| 66 | fn answer_sse_without_usage(answer: &str) -> String { |
| 67 | [ |
| 68 | sse_chunk(json!({ |
| 69 | "id": "chatcmpl-no-usage", |
| 70 | "object": "chat.completion.chunk", |
| 71 | "model": TEST_MODEL, |
| 72 | "choices": [{"index": 0, "delta": {"content": answer}, "finish_reason": null}] |
| 73 | })), |
| 74 | sse_chunk(json!({ |
| 75 | "id": "chatcmpl-no-usage", |
| 76 | "object": "chat.completion.chunk", |
| 77 | "model": TEST_MODEL, |
| 78 | "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}] |
| 79 | })), |
| 80 | "data: [DONE]\n\n".to_string(), |
| 81 | ] |
| 82 | .join("") |
| 83 | } |
| 84 | |
| 85 | fn sse_response(body: String) -> ResponseTemplate { |
| 86 | ResponseTemplate::new(200) |
| 87 | .insert_header("content-type", "text/event-stream") |
| 88 | .insert_header("cache-control", "no-cache") |
| 89 | .set_body_string(body) |
| 90 | } |
| 91 | |
| 92 | fn json_response(value: Value) -> ResponseTemplate { |
| 93 | ResponseTemplate::new(200) |
| 94 | .insert_header("content-type", "application/json") |
| 95 | .set_body_json(value) |
| 96 | } |
| 97 | |
| 98 | async fn start_mock_llm(answer_sse: String) -> MockServer { |
| 99 | let server = MockServer::start().await; |
| 100 | |
| 101 | Mock::given(method("GET")) |
| 102 | .and(path("/v1/models")) |
| 103 | .respond_with(json_response(json!({ |
| 104 | "object": "list", |
| 105 | "data": [{ "id": TEST_MODEL, "object": "model" }] |
| 106 | }))) |
| 107 | .mount(&server) |
| 108 | .await; |
| 109 | |
| 110 | Mock::given(method("POST")) |
| 111 | .and(path("/v1/chat/completions")) |
| 112 | .respond_with(sse_response(answer_sse)) |
| 113 | .mount(&server) |
| 114 | .await; |
| 115 | |
| 116 | server |
| 117 | } |
| 118 | |
| 119 | fn preserve_host_env(command: &mut Command) { |
| 120 | command.env_clear(); |
| 121 | for key in [ |
| 122 | "PATH", |
| 123 | "PATHEXT", |
| 124 | "SystemRoot", |
| 125 | "SystemDrive", |
| 126 | "WINDIR", |
| 127 | "COMSPEC", |
| 128 | "TEMP", |
| 129 | "TMP", |
| 130 | "TERM", |
| 131 | "COLORTERM", |
| 132 | "LANG", |
| 133 | "LC_ALL", |
| 134 | ] { |
| 135 | if let Some(value) = std::env::var_os(key) { |
| 136 | command.env(key, value); |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | fn run_exec_stream_json(server: &MockServer) -> Vec<Value> { |
| 142 | let stdout = run_exec( |
| 143 | server, |
| 144 | &[ |
| 145 | "--auto", |
| 146 | "--model", |
| 147 | TEST_MODEL, |
| 148 | "--output-format", |
| 149 | "stream-json", |
| 150 | "answer briefly", |
| 151 | ], |
| 152 | ); |
| 153 | stdout |
| 154 | .lines() |
| 155 | .filter(|line| !line.trim().is_empty()) |
| 156 | .map(|line| { |
| 157 | serde_json::from_str(line).unwrap_or_else(|err| { |
| 158 | panic!("stream-json line should parse: {err}\nline: {line}\nstdout:\n{stdout}") |
| 159 | }) |
| 160 | }) |
| 161 | .collect() |
| 162 | } |
| 163 | |
| 164 | /// Run `codewhale exec <exec_args>` against `server` and return stdout. |
| 165 | fn run_exec(server: &MockServer, exec_args: &[&str]) -> String { |
| 166 | let (success, stdout, stderr) = run_exec_unchecked(server, exec_args); |
| 167 | assert!( |
| 168 | success, |
| 169 | "codewhale exec failed\nstdout:\n{stdout}\nstderr:\n{stderr}" |
| 170 | ); |
| 171 | stdout |
| 172 | } |
| 173 | |
| 174 | /// Run `codewhale exec <exec_args>` and return whether it exited |
| 175 | /// successfully, its stdout and its stderr. |
| 176 | fn run_exec_unchecked(server: &MockServer, exec_args: &[&str]) -> (bool, String, String) { |
| 177 | run_exec_in_home(server, exec_args, |_| {}) |
| 178 | } |
| 179 | |
| 180 | /// [`run_exec_unchecked`] with a hook that prepares the isolated `$HOME` |
| 181 | /// before the run, e.g. to install an MCP config. |
| 182 | fn run_exec_in_home( |
| 183 | server: &MockServer, |
| 184 | exec_args: &[&str], |
| 185 | prepare_home: impl FnOnce(&std::path::Path), |
| 186 | ) -> (bool, String, String) { |
| 187 | run_exec_with_stdin(server, exec_args, prepare_home, None) |
| 188 | } |
| 189 | |
| 190 | /// [`run_exec_in_home`] that optionally pipes `stdin` into the child. |
| 191 | fn run_exec_with_stdin( |
| 192 | server: &MockServer, |
| 193 | exec_args: &[&str], |
| 194 | prepare_home: impl FnOnce(&std::path::Path), |
| 195 | stdin: Option<Vec<u8>>, |
| 196 | ) -> (bool, String, String) { |
| 197 | let workspace = TempDir::new().expect("workspace tempdir"); |
| 198 | let home = TempDir::new().expect("home tempdir"); |
| 199 | |
| 200 | let mut command = Command::new(crate::binary::codewhale()); |
| 201 | preserve_host_env(&mut command); |
| 202 | command |
| 203 | .current_dir(workspace.path()) |
| 204 | .arg("--workspace") |
| 205 | .arg(workspace.path()) |
| 206 | .arg("--no-project-config") |
| 207 | .arg("exec") |
| 208 | .args(exec_args) |
| 209 | .env("HOME", home.path()) |
| 210 | .env("USERPROFILE", home.path()) |
| 211 | .env("XDG_CONFIG_HOME", home.path().join(".config")) |
| 212 | .env("XDG_DATA_HOME", home.path().join(".local").join("share")) |
| 213 | .env("XDG_CACHE_HOME", home.path().join(".cache")) |
| 214 | .env( |
| 215 | "CODEWHALE_CONFIG_PATH", |
| 216 | home.path().join(".codewhale").join("config.toml"), |
| 217 | ) |
| 218 | .env( |
| 219 | "DEEPSEEK_CONFIG_PATH", |
| 220 | home.path().join(".deepseek").join("config.toml"), |
| 221 | ) |
| 222 | .env("DEEPSEEK_API_KEY", "ci-test-key-not-real") |
| 223 | .env("DEEPSEEK_BASE_URL", server.uri()) |
| 224 | .env("CODEWHALE_BASE_URL", server.uri()) |
| 225 | .env("DEEPSEEK_MODEL", TEST_MODEL) |
| 226 | .env("CODEWHALE_MODEL", TEST_MODEL) |
| 227 | .env("RUST_LOG", "warn") |
| 228 | .stdout(Stdio::piped()) |
| 229 | .stderr(Stdio::piped()); |
| 230 | |
| 231 | std::fs::create_dir_all(home.path().join(".codewhale")).expect("create codewhale config dir"); |
| 232 | std::fs::create_dir_all(home.path().join(".deepseek")).expect("create deepseek config dir"); |
| 233 | prepare_home(home.path()); |
| 234 | |
| 235 | run_with_timeout(command, stdin) |
| 236 | } |
| 237 | |
| 238 | fn run_with_timeout(mut command: Command, stdin: Option<Vec<u8>>) -> (bool, String, String) { |
| 239 | if stdin.is_some() { |
| 240 | command.stdin(Stdio::piped()); |
| 241 | } |
| 242 | let mut child = command.spawn().expect("spawn codewhale exec"); |
| 243 | let stdin_writer = stdin.map(|bytes| { |
| 244 | let mut pipe = child.stdin.take().expect("stdin pipe"); |
| 245 | std::thread::spawn(move || { |
| 246 | use std::io::Write; |
| 247 | // The child may exit without reading; a broken pipe is fine. |
| 248 | let _ = pipe.write_all(&bytes); |
| 249 | }) |
| 250 | }); |
| 251 | let stdout_reader = read_pipe_in_background(child.stdout.take().expect("stdout pipe")); |
| 252 | let stderr_reader = read_pipe_in_background(child.stderr.take().expect("stderr pipe")); |
| 253 | |
| 254 | let status = match child.wait_timeout(RUN_TIMEOUT).expect("wait for codewhale") { |
| 255 | Some(status) => status, |
| 256 | None => { |
| 257 | let _ = child.kill(); |
| 258 | let _ = child.wait(); |
| 259 | let stdout = join_pipe_reader(stdout_reader, "stdout"); |
| 260 | let stderr = join_pipe_reader(stderr_reader, "stderr"); |
| 261 | panic!( |
| 262 | "codewhale exec timed out after {RUN_TIMEOUT:?}\nstdout:\n{}\nstderr:\n{}", |
| 263 | String::from_utf8_lossy(&stdout), |
| 264 | String::from_utf8_lossy(&stderr) |
| 265 | ); |
| 266 | } |
| 267 | }; |
| 268 | |
| 269 | if let Some(writer) = stdin_writer { |
| 270 | writer.join().expect("stdin writer thread"); |
| 271 | } |
| 272 | let stdout = join_pipe_reader(stdout_reader, "stdout"); |
| 273 | let stderr = join_pipe_reader(stderr_reader, "stderr"); |
| 274 | ( |
| 275 | status.success(), |
| 276 | String::from_utf8_lossy(&stdout).into_owned(), |
| 277 | String::from_utf8_lossy(&stderr).into_owned(), |
| 278 | ) |
| 279 | } |
| 280 | |
| 281 | #[tokio::test(flavor = "multi_thread")] |
| 282 | async fn go_exec_selects_and_resumes_its_exact_connection_across_processes() { |
| 283 | let go = MockServer::start().await; |
| 284 | let other = MockServer::start().await; |
| 285 | let base = format!("{}/inference/go/v1", go.uri()); |
| 286 | let chat = format!("{}/inference/go/openai/v1", go.uri()); |
| 287 | Mock::given(method("GET")).and(path("/inference/go/v1/models")) |
| 288 | .and(wiremock::matchers::header("authorization", "Bearer local-go-fixture")) |
| 289 | .respond_with(json_response(json!({"data":[{"id":"step-5","type":"chat","api":{"chat-completions":{"base_url":chat}},"capabilities":{"tools":{"supported":true}}}]}))) |
| 290 | .mount(&go).await; |
| 291 | Mock::given(method("POST")) |
| 292 | .and(path("/inference/go/openai/v1/chat/completions")) |
| 293 | .and(wiremock::matchers::body_partial_json( |
| 294 | json!({"model":"step-5"}), |
| 295 | )) |
| 296 | .respond_with(sse_response( |
| 297 | answer_sse_with_usage("tide").replace(TEST_MODEL, "step-5"), |
| 298 | )) |
| 299 | .mount(&go) |
| 300 | .await; |
| 301 | let home = TempDir::new().unwrap(); |
| 302 | let workspace = TempDir::new().unwrap(); |
| 303 | let config_dir = home.path().join(".codewhale"); |
| 304 | std::fs::create_dir(&config_dir).unwrap(); |
| 305 | let config_path = config_dir.join("config.toml"); |
| 306 | std::fs::write(&config_path, format!( |
| 307 | "provider = \"opencode-go\"\n[providers.opencode_go]\napi_key_env = \"OPENCODE_GO_API_KEY\"\nbase_url = {base:?}\nmodel = \"deepseek-v4-pro\"\n[providers.duplicate]\nkind = \"openai-compatible\"\nbase_url = \"{}/v1\"\nmodel = \"step-5\"\nauth_mode = \"none\"\n", other.uri() |
| 308 | )).unwrap(); |
| 309 | let run = |args: &[&str], key: &str| { |
| 310 | let mut command = Command::new(crate::binary::codewhale()); |
| 311 | preserve_host_env(&mut command); |
| 312 | command |
| 313 | .current_dir(workspace.path()) |
| 314 | .arg("--workspace") |
| 315 | .arg(workspace.path()) |
| 316 | .arg("--no-project-config") |
| 317 | .args(args) |
| 318 | .env("CODEWHALE_HOME", &config_dir) |
| 319 | .env("CODEWHALE_CONFIG_PATH", &config_path) |
| 320 | .env("HOME", home.path()) |
| 321 | .env("USERPROFILE", home.path()) |
| 322 | .env("XDG_CONFIG_HOME", home.path().join(".config")) |
| 323 | .env("XDG_CACHE_HOME", home.path().join(".cache")) |
| 324 | .env("XDG_DATA_HOME", home.path().join(".local/share")) |
| 325 | .env("OPENCODE_GO_API_KEY", key) |
| 326 | .stdout(Stdio::piped()) |
| 327 | .stderr(Stdio::piped()); |
| 328 | run_with_timeout(command, None) |
| 329 | }; |
| 330 | let (ok, out, err) = run( |
| 331 | &["models", "--update", "--provider", "opencode-go"], |
| 332 | "local-go-fixture", |
| 333 | ); |
| 334 | assert!(ok, "{out}\n{err}"); |
| 335 | let (ok, out, err) = run( |
| 336 | &[ |
| 337 | "exec", |
| 338 | "--model", |
| 339 | "step-5", |
| 340 | "--output-format", |
| 341 | "stream-json", |
| 342 | "report the tide", |
| 343 | ], |
| 344 | "local-go-fixture", |
| 345 | ); |
| 346 | assert!(ok, "{out}\n{err}"); |
| 347 | let metadata = out |
| 348 | .lines() |
| 349 | .filter_map(|line| serde_json::from_str::<Value>(line).ok()) |
| 350 | .find(|event| event["type"] == "metadata") |
| 351 | .unwrap(); |
| 352 | assert_eq!(metadata["meta"]["provider"], "opencode-go"); |
| 353 | let saved = out |
| 354 | .lines() |
| 355 | .filter_map(|line| serde_json::from_str::<Value>(line).ok()) |
| 356 | .find_map(|event| event["saved_session_id"].as_str().map(str::to_owned)) |
| 357 | .unwrap(); |
| 358 | let session = saved.as_str(); |
| 359 | let resume = [ |
| 360 | "exec", |
| 361 | "--resume", |
| 362 | session, |
| 363 | "--output-format", |
| 364 | "stream-json", |
| 365 | "report the tide again", |
| 366 | ]; |
| 367 | let (ok, out, err) = run(&resume, "local-go-fixture"); |
| 368 | assert!(ok, "{out}\n{err}"); |
| 369 | let requests = go.received_requests().await.unwrap(); |
| 370 | let sessions: Vec<_> = requests |
| 371 | .iter() |
| 372 | .filter(|r| r.method.as_str() == "POST") |
| 373 | .map(|r| { |
| 374 | r.headers |
| 375 | .get("x-opencode-session") |
| 376 | .unwrap() |
| 377 | .to_str() |
| 378 | .unwrap() |
| 379 | }) |
| 380 | .collect(); |
| 381 | assert_eq!(sessions.len(), 2); |
| 382 | assert_eq!(sessions[0], sessions[1]); |
| 383 | let (ok, out, err) = run(&resume, "rotated-go-fixture"); |
| 384 | assert!(!ok, "{out}\n{err}"); |
| 385 | assert_eq!(go.received_requests().await.unwrap().len(), requests.len()); |
| 386 | assert!(other.received_requests().await.unwrap().is_empty()); |
| 387 | let (ok, out, err) = run( |
| 388 | &[ |
| 389 | "exec", |
| 390 | "--provider", |
| 391 | "opencode-go", |
| 392 | "--model", |
| 393 | "step-5", |
| 394 | "--output-format", |
| 395 | "stream-json", |
| 396 | "report the tide explicitly", |
| 397 | ], |
| 398 | "local-go-fixture", |
| 399 | ); |
| 400 | assert!(ok, "{out}\n{err}"); |
| 401 | assert_eq!( |
| 402 | go.received_requests() |
| 403 | .await |
| 404 | .unwrap() |
| 405 | .iter() |
| 406 | .filter(|request| request.method.as_str() == "POST") |
| 407 | .count(), |
| 408 | 3 |
| 409 | ); |
| 410 | let task = workspace.path().join("mission.json"); |
| 411 | std::fs::write( |
| 412 | &task, |
| 413 | serde_json::to_vec(&json!({ |
| 414 | "name": "Go validation", |
| 415 | "tasks": [{ |
| 416 | "id": "step-task", |
| 417 | "name": "Review", |
| 418 | "instructions": "Read the fixture", |
| 419 | "worker": {"provider": "opencode-go", "model": "step-5"} |
| 420 | }] |
| 421 | })) |
| 422 | .unwrap(), |
| 423 | ) |
| 424 | .unwrap(); |
| 425 | let before = go.received_requests().await.unwrap().len(); |
| 426 | let (ok, out, err) = run( |
| 427 | &[ |
| 428 | "--provider", |
| 429 | "opencode-go", |
| 430 | "--model", |
| 431 | "step-5", |
| 432 | "fleet", |
| 433 | "run", |
| 434 | task.to_str().unwrap(), |
| 435 | "--check", |
| 436 | ], |
| 437 | "local-go-fixture", |
| 438 | ); |
| 439 | assert!(ok, "{out}\n{err}"); |
| 440 | assert!(out.contains("Fleet spec ok"), "{out}"); |
| 441 | let after = go.received_requests().await.unwrap(); |
| 442 | assert_eq!(after.len(), before + 1); |
| 443 | assert_eq!(after[before].method.as_str(), "GET"); |
| 444 | assert!(!workspace.path().join(".codewhale/fleet.jsonl").exists()); |
| 445 | assert!(other.received_requests().await.unwrap().is_empty()); |
| 446 | } |
| 447 | |
| 448 | fn read_pipe_in_background<R>(mut reader: R) -> std::thread::JoinHandle<std::io::Result<Vec<u8>>> |
| 449 | where |
| 450 | R: Read + Send + 'static, |
| 451 | { |
| 452 | std::thread::spawn(move || { |
| 453 | let mut output = Vec::new(); |
| 454 | reader.read_to_end(&mut output).map(|_| output) |
| 455 | }) |
| 456 | } |
| 457 | |
| 458 | fn join_pipe_reader( |
| 459 | handle: std::thread::JoinHandle<std::io::Result<Vec<u8>>>, |
| 460 | stream_name: &str, |
| 461 | ) -> Vec<u8> { |
| 462 | handle |
| 463 | .join() |
| 464 | .unwrap_or_else(|_| panic!("{stream_name} reader thread panicked")) |
| 465 | .unwrap_or_else(|err| panic!("failed to read {stream_name}: {err}")) |
| 466 | } |
| 467 | |
| 468 | fn events_of_type<'a>(events: &'a [Value], event_type: &str) -> Vec<&'a Value> { |
| 469 | events |
| 470 | .iter() |
| 471 | .filter(|event| event.get("type").and_then(Value::as_str) == Some(event_type)) |
| 472 | .collect() |
| 473 | } |
| 474 | |
| 475 | #[tokio::test(flavor = "multi_thread")] |
| 476 | async fn turn_usage_event_is_emitted_with_reported_fields_and_stream_contract_holds() { |
| 477 | let server = start_mock_llm(answer_sse_with_usage("done in one step")).await; |
| 478 | let events = run_exec_stream_json(&server); |
| 479 | |
| 480 | // Every event carries the stream schema envelope. |
| 481 | for event in &events { |
| 482 | assert_eq!(event["schema"], "codewhale.exec-stream"); |
| 483 | assert_eq!(event["schema_version"], 1); |
| 484 | } |
| 485 | |
| 486 | // Exactly one per-call usage receipt, numbered from 1. |
| 487 | let usage_events = events_of_type(&events, "turn_usage"); |
| 488 | assert_eq!( |
| 489 | usage_events.len(), |
| 490 | 1, |
| 491 | "expected one turn_usage event: {events:#?}" |
| 492 | ); |
| 493 | let usage = usage_events[0]; |
| 494 | assert_eq!(usage["turn"], 1); |
| 495 | assert_eq!(usage["input_tokens"], 20); |
| 496 | assert_eq!(usage["output_tokens"], 8); |
| 497 | assert_eq!(usage["reasoning_tokens"], 5); |
| 498 | assert_eq!(usage["prompt_cache_hit_tokens"], 12); |
| 499 | assert_eq!(usage["prompt_cache_miss_tokens"], 8); |
| 500 | assert!( |
| 501 | usage["duration_ms"].as_u64().is_some(), |
| 502 | "duration_ms must be a non-negative integer: {usage}" |
| 503 | ); |
| 504 | // Fields the provider did not report are omitted, not zero-filled. |
| 505 | let usage_object = usage.as_object().expect("turn_usage object"); |
| 506 | for absent in ["prompt_cache_write_tokens", "reasoning_replay_tokens"] { |
| 507 | assert!( |
| 508 | !usage_object.contains_key(absent), |
| 509 | "{absent} must be omitted when unreported: {usage}" |
| 510 | ); |
| 511 | } |
| 512 | |
| 513 | // The usage receipt lands after the model output it accounts for and |
| 514 | // before the terminal receipts. |
| 515 | let types: Vec<&str> = events |
| 516 | .iter() |
| 517 | .filter_map(|event| event.get("type").and_then(Value::as_str)) |
| 518 | .collect(); |
| 519 | let content_pos = types.iter().position(|t| *t == "content"); |
| 520 | let usage_pos = types.iter().position(|t| *t == "turn_usage"); |
| 521 | assert!( |
| 522 | content_pos.is_some_and(|c| usage_pos.is_some_and(|u| c < u)), |
| 523 | "turn_usage must follow the content it accounts for: {types:?}" |
| 524 | ); |
| 525 | |
| 526 | // Existing consumers' terminal contract is unchanged: `metadata` |
| 527 | // immediately precedes exactly one trailing `done`. |
| 528 | assert_eq!(types.last(), Some(&"done"), "stream must end with done"); |
| 529 | assert_eq!( |
| 530 | types.get(types.len() - 2), |
| 531 | Some(&"metadata"), |
| 532 | "metadata must immediately precede done: {types:?}" |
| 533 | ); |
| 534 | assert_eq!( |
| 535 | events_of_type(&events, "done").len(), |
| 536 | 1, |
| 537 | "exactly one done event" |
| 538 | ); |
| 539 | let metadata = events_of_type(&events, "metadata"); |
| 540 | assert_eq!(metadata.len(), 1, "exactly one metadata event"); |
| 541 | // The terminal receipt still carries the cumulative usage. |
| 542 | assert_eq!(metadata[0]["meta"]["input_tokens"], 20); |
| 543 | assert_eq!(metadata[0]["meta"]["output_tokens"], 8); |
| 544 | assert_eq!(metadata[0]["meta"]["reasoning_tokens"], 5); |
| 545 | assert_eq!(metadata[0]["meta"]["usage_status"], "complete"); |
| 546 | assert_eq!(metadata[0]["meta"]["stop_reason"], "provider_no_tool_call"); |
| 547 | } |
| 548 | |
| 549 | #[tokio::test(flavor = "multi_thread")] |
| 550 | async fn turn_usage_event_is_skipped_when_provider_reports_no_usage() { |
| 551 | let server = start_mock_llm(answer_sse_without_usage("quiet answer")).await; |
| 552 | let events = run_exec_stream_json(&server); |
| 553 | |
| 554 | assert!( |
| 555 | events_of_type(&events, "turn_usage").is_empty(), |
| 556 | "no turn_usage event without provider-reported usage: {events:#?}" |
| 557 | ); |
| 558 | |
| 559 | // The rest of the stream contract still holds. |
| 560 | let types: Vec<&str> = events |
| 561 | .iter() |
| 562 | .filter_map(|event| event.get("type").and_then(Value::as_str)) |
| 563 | .collect(); |
| 564 | assert!(types.contains(&"content"), "content missing: {types:?}"); |
| 565 | assert_eq!(types.last(), Some(&"done"), "stream must end with done"); |
| 566 | assert_eq!(types.get(types.len() - 2), Some(&"metadata")); |
| 567 | |
| 568 | let meta = &events_of_type(&events, "metadata")[0]["meta"]; |
| 569 | assert_eq!(meta["usage_status"], "unreported", "{meta}"); |
| 570 | for absent in ["input_tokens", "output_tokens"] { |
| 571 | assert!( |
| 572 | meta.get(absent).is_none(), |
| 573 | "{absent} must be omitted when unreported: {meta}" |
| 574 | ); |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | #[tokio::test(flavor = "multi_thread")] |
| 579 | async fn agent_exec_json_receipt_reports_success_and_usage() { |
| 580 | let server = start_mock_llm(answer_sse_with_usage("pong")).await; |
| 581 | let json_stdout = run_exec( |
| 582 | &server, |
| 583 | &["--json", "--model", TEST_MODEL, "answer briefly"], |
| 584 | ); |
| 585 | let receipt: Value = serde_json::from_str(&json_stdout) |
| 586 | .unwrap_or_else(|err| panic!("--json receipt should parse: {err}\n{json_stdout}")); |
| 587 | assert_eq!(receipt["mode"], "agent", "{receipt}"); |
| 588 | assert_eq!(receipt["success"], true, "{receipt}"); |
| 589 | assert_eq!(receipt["status"], "completed", "{receipt}"); |
| 590 | assert_eq!(receipt["usage"]["input_tokens"], 20, "{receipt}"); |
| 591 | assert_eq!(receipt["usage"]["output_tokens"], 8, "{receipt}"); |
| 592 | assert_eq!(receipt["usage_status"], "complete", "{receipt}"); |
| 593 | assert!( |
| 594 | receipt["agents"].as_array().is_some_and(Vec::is_empty), |
| 595 | "{receipt}" |
| 596 | ); |
| 597 | } |
| 598 | |
| 599 | #[tokio::test(flavor = "multi_thread")] |
| 600 | async fn exec_writes_a_failed_receipt_when_it_fails_before_the_turn() { |
| 601 | let server = start_mock_llm(answer_sse_with_usage("pong")).await; |
| 602 | let missing = "/codewhale-exec-receipt-missing-add-dir"; |
| 603 | |
| 604 | let (success, stdout, stderr) = run_exec_unchecked( |
| 605 | &server, |
| 606 | &["--json", "--add-dir", missing, "--model", TEST_MODEL, "hi"], |
| 607 | ); |
| 608 | assert!(!success, "stdout:\n{stdout}\nstderr:\n{stderr}"); |
| 609 | let receipt: Value = serde_json::from_str(&stdout) |
| 610 | .unwrap_or_else(|err| panic!("--json receipt should parse: {err}\n{stdout}\n{stderr}")); |
| 611 | assert_eq!(receipt["success"], false, "{receipt}"); |
| 612 | assert_eq!(receipt["status"], "failed", "{receipt}"); |
| 613 | assert!(receipt["usage"].is_null(), "{receipt}"); |
| 614 | assert_eq!(receipt["usage_status"], "unreported", "{receipt}"); |
| 615 | assert!( |
| 616 | receipt["error"] |
| 617 | .as_str() |
| 618 | .is_some_and(|error| error.contains("--add-dir")), |
| 619 | "{receipt}" |
| 620 | ); |
| 621 | |
| 622 | let (success, stdout, stderr) = run_exec_unchecked( |
| 623 | &server, |
| 624 | &[ |
| 625 | "--output-format", |
| 626 | "stream-json", |
| 627 | "--add-dir", |
| 628 | missing, |
| 629 | "--model", |
| 630 | TEST_MODEL, |
| 631 | "hi", |
| 632 | ], |
| 633 | ); |
| 634 | assert!(!success, "stdout:\n{stdout}\nstderr:\n{stderr}"); |
| 635 | let event: Value = serde_json::from_str(stdout.trim()) |
| 636 | .unwrap_or_else(|err| panic!("one stream event should parse: {err}\n{stdout}")); |
| 637 | assert_eq!(event["type"], "error", "{event}"); |
| 638 | assert_eq!(event["schema"], "codewhale.exec-stream", "{event}"); |
| 639 | assert!(chat_bodies(&server).await.is_empty(), "no model call"); |
| 640 | } |
| 641 | |
| 642 | /// #6510: plain `exec` bypassed the Engine — text mode sent no system prompt, |
| 643 | /// `--json` sent an inline "coding assistant" line — so the output format |
| 644 | /// changed the model's instructions and nothing was logged. Both now run one |
| 645 | /// Engine turn with the one base prompt and no tool catalog, and `--json` |
| 646 | /// keeps its documented one-shot receipt fields. |
| 647 | #[tokio::test(flavor = "multi_thread")] |
| 648 | async fn plain_exec_runs_one_engine_turn_under_one_prompt_authority() { |
| 649 | let server = start_mock_llm(answer_sse_with_usage("pong")).await; |
| 650 | |
| 651 | let text = run_exec( |
| 652 | &server, |
| 653 | &["--no-tools", "--model", TEST_MODEL, "answer briefly"], |
| 654 | ); |
| 655 | assert_eq!(text.trim(), "pong", "text mode prints the answer: {text}"); |
| 656 | |
| 657 | let json_stdout = run_exec( |
| 658 | &server, |
| 659 | &[ |
| 660 | "--no-tools", |
| 661 | "--json", |
| 662 | "--model", |
| 663 | TEST_MODEL, |
| 664 | "answer briefly", |
| 665 | ], |
| 666 | ); |
| 667 | let receipt: Value = serde_json::from_str(&json_stdout) |
| 668 | .unwrap_or_else(|err| panic!("--json receipt should parse: {err}\n{json_stdout}")); |
| 669 | assert_eq!(receipt["mode"], "one-shot"); |
| 670 | assert_eq!(receipt["model"], TEST_MODEL); |
| 671 | assert_eq!(receipt["success"], true); |
| 672 | assert_eq!(receipt["output"], "pong"); |
| 673 | assert_eq!(receipt["usage"]["input_tokens"], 20); |
| 674 | assert_eq!(receipt["usage"]["output_tokens"], 8); |
| 675 | assert!( |
| 676 | receipt["tools"].as_array().is_some_and(Vec::is_empty), |
| 677 | "{receipt}" |
| 678 | ); |
| 679 | |
| 680 | let bodies = chat_bodies(&server).await; |
| 681 | assert_eq!(bodies.len(), 2, "one model call per run: {bodies:#?}"); |
| 682 | for body in &bodies { |
| 683 | let messages = body["messages"].to_string(); |
| 684 | assert!( |
| 685 | messages.contains("You are Codewhale, an agent with real tools and a real workspace"), |
| 686 | "both formats must carry the one base prompt: {messages}" |
| 687 | ); |
| 688 | assert!( |
| 689 | !messages.contains("You are a coding assistant. Give concise"), |
| 690 | "the old --json-only instruction must be gone: {messages}" |
| 691 | ); |
| 692 | assert!( |
| 693 | body.get("tools") |
| 694 | .is_none_or(|tools| tools.as_array().is_some_and(Vec::is_empty)), |
| 695 | "--no-tools offers no tools: {body}" |
| 696 | ); |
| 697 | } |
| 698 | } |
| 699 | |
| 700 | /// Chat-completions bodies the mock received, in order. |
| 701 | async fn chat_bodies(server: &MockServer) -> Vec<Value> { |
| 702 | server |
| 703 | .received_requests() |
| 704 | .await |
| 705 | .expect("request recording") |
| 706 | .into_iter() |
| 707 | .filter(|request| request.url.path() == "/v1/chat/completions") |
| 708 | .map(|request| serde_json::from_slice(&request.body).expect("request body JSON")) |
| 709 | .collect() |
| 710 | } |
| 711 | |
| 712 | /// #6510: a limit is not a tool grant. `--max-turns`, `--disallowed-tools` |
| 713 | /// and `--append-system-prompt` used to put plain exec on the full tool |
| 714 | /// catalog, so `exec --max-turns 1 "hi"` became a tool-using agent. |
| 715 | #[tokio::test(flavor = "multi_thread")] |
| 716 | async fn plain_exec_limits_do_not_grant_tools() { |
| 717 | let server = start_mock_llm(answer_sse_with_usage("pong")).await; |
| 718 | |
| 719 | for flags in [ |
| 720 | &["--max-turns", "1"][..], |
| 721 | &["--disallowed-tools", "exec_shell"], |
| 722 | &["--append-system-prompt", "Be brief."], |
| 723 | ] { |
| 724 | let mut args = flags.to_vec(); |
| 725 | args.extend(["--no-tools", "--model", TEST_MODEL, "answer briefly"]); |
| 726 | let text = run_exec(&server, &args); |
| 727 | assert_eq!(text.trim(), "pong", "{flags:?}: {text}"); |
| 728 | } |
| 729 | |
| 730 | let bodies = chat_bodies(&server).await; |
| 731 | assert_eq!(bodies.len(), 3, "one model call per run: {bodies:#?}"); |
| 732 | for body in &bodies { |
| 733 | assert!( |
| 734 | body.get("tools") |
| 735 | .is_none_or(|tools| tools.as_array().is_some_and(Vec::is_empty)), |
| 736 | "a limit flag must not offer tools: {body}" |
| 737 | ); |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | /// #6510: plain exec now runs on the Engine, so an output-limit stop follows |
| 742 | /// the Engine's one policy: the partial answer is kept, the model is asked to |
| 743 | /// continue, and the run succeeds with the whole answer. The old direct call |
| 744 | /// printed the partial answer and failed. |
| 745 | #[tokio::test(flavor = "multi_thread")] |
| 746 | async fn plain_exec_continues_past_an_output_limit_stop() { |
| 747 | let server = MockServer::start().await; |
| 748 | Mock::given(method("GET")) |
| 749 | .and(path("/v1/models")) |
| 750 | .respond_with(json_response(json!({ |
| 751 | "object": "list", |
| 752 | "data": [{ "id": TEST_MODEL, "object": "model" }] |
| 753 | }))) |
| 754 | .mount(&server) |
| 755 | .await; |
| 756 | let truncated = [ |
| 757 | sse_chunk(json!({ |
| 758 | "id": "chatcmpl-cut", |
| 759 | "object": "chat.completion.chunk", |
| 760 | "model": TEST_MODEL, |
| 761 | "choices": [{"index": 0, "delta": {"content": "first half"}, "finish_reason": null}] |
| 762 | })), |
| 763 | sse_chunk(json!({ |
| 764 | "id": "chatcmpl-cut", |
| 765 | "object": "chat.completion.chunk", |
| 766 | "model": TEST_MODEL, |
| 767 | "choices": [{"index": 0, "delta": {}, "finish_reason": "length"}] |
| 768 | })), |
| 769 | "data: [DONE]\n\n".to_string(), |
| 770 | ] |
| 771 | .join(""); |
| 772 | Mock::given(method("POST")) |
| 773 | .and(path("/v1/chat/completions")) |
| 774 | .respond_with(sse_response(truncated)) |
| 775 | .up_to_n_times(1) |
| 776 | .with_priority(1) |
| 777 | .mount(&server) |
| 778 | .await; |
| 779 | Mock::given(method("POST")) |
| 780 | .and(path("/v1/chat/completions")) |
| 781 | .respond_with(sse_response(answer_sse_without_usage(" second half"))) |
| 782 | .with_priority(2) |
| 783 | .mount(&server) |
| 784 | .await; |
| 785 | |
| 786 | let json_stdout = run_exec( |
| 787 | &server, |
| 788 | &[ |
| 789 | "--no-tools", |
| 790 | "--json", |
| 791 | "--model", |
| 792 | TEST_MODEL, |
| 793 | "answer briefly", |
| 794 | ], |
| 795 | ); |
| 796 | let receipt: Value = serde_json::from_str(&json_stdout) |
| 797 | .unwrap_or_else(|err| panic!("--json receipt should parse: {err}\n{json_stdout}")); |
| 798 | assert_eq!(receipt["mode"], "one-shot", "{receipt}"); |
| 799 | assert_eq!(receipt["success"], true, "{receipt}"); |
| 800 | let output = receipt["output"].as_str().unwrap_or_default(); |
| 801 | assert!( |
| 802 | output.contains("first half") && output.contains("second half"), |
| 803 | "{receipt}" |
| 804 | ); |
| 805 | |
| 806 | let bodies = chat_bodies(&server).await; |
| 807 | assert_eq!(bodies.len(), 2, "one continuation request: {bodies:#?}"); |
| 808 | assert!( |
| 809 | bodies[1]["messages"] |
| 810 | .to_string() |
| 811 | .contains("stopped generation at its output limit"), |
| 812 | "the continuation names the truncation: {}", |
| 813 | bodies[1]["messages"] |
| 814 | ); |
| 815 | } |
| 816 | |
| 817 | /// #6510 review: a model that keeps stopping at its output limit must not be |
| 818 | /// re-asked until the turn wall clock. Plain exec caps its continuations at a |
| 819 | /// small default (8 model steps) unless `--max-turns` sets another, ends the |
| 820 | /// run as failed with the partial answer, and never injects the agent wrap-up |
| 821 | /// notices (soft landing, final report) into a one-shot answer. |
| 822 | #[tokio::test(flavor = "multi_thread")] |
| 823 | async fn plain_exec_bounds_output_limit_continuations() { |
| 824 | let always_truncated = [ |
| 825 | sse_chunk(json!({ |
| 826 | "id": "chatcmpl-cut", |
| 827 | "object": "chat.completion.chunk", |
| 828 | "model": TEST_MODEL, |
| 829 | "choices": [{"index": 0, "delta": {"content": "again"}, "finish_reason": null}] |
| 830 | })), |
| 831 | sse_chunk(json!({ |
| 832 | "id": "chatcmpl-cut", |
| 833 | "object": "chat.completion.chunk", |
| 834 | "model": TEST_MODEL, |
| 835 | "choices": [{"index": 0, "delta": {}, "finish_reason": "length"}] |
| 836 | })), |
| 837 | "data: [DONE]\n\n".to_string(), |
| 838 | ] |
| 839 | .join(""); |
| 840 | |
| 841 | for (flags, expected_requests) in [(&[][..], 8usize), (&["--max-turns", "2"][..], 2)] { |
| 842 | let server = start_mock_llm(always_truncated.clone()).await; |
| 843 | let mut args = flags.to_vec(); |
| 844 | args.extend([ |
| 845 | "--no-tools", |
| 846 | "--json", |
| 847 | "--model", |
| 848 | TEST_MODEL, |
| 849 | "answer briefly", |
| 850 | ]); |
| 851 | let (success, stdout, stderr) = run_exec_unchecked(&server, &args); |
| 852 | assert!( |
| 853 | !success, |
| 854 | "{flags:?}: a capped run must not exit 0\n{stderr}" |
| 855 | ); |
| 856 | let receipt: Value = serde_json::from_str(&stdout) |
| 857 | .unwrap_or_else(|err| panic!("--json receipt should parse: {err}\n{stdout}")); |
| 858 | assert_eq!(receipt["mode"], "one-shot", "{receipt}"); |
| 859 | assert_eq!(receipt["success"], false, "{receipt}"); |
| 860 | assert!( |
| 861 | receipt["output"] |
| 862 | .as_str() |
| 863 | .is_some_and(|output| output.contains("again")), |
| 864 | "the partial answer is kept: {receipt}" |
| 865 | ); |
| 866 | |
| 867 | let bodies = chat_bodies(&server).await; |
| 868 | assert_eq!(bodies.len(), expected_requests, "{flags:?}: {bodies:#?}"); |
| 869 | for body in &bodies { |
| 870 | let messages = body["messages"].to_string(); |
| 871 | assert!( |
| 872 | !messages.contains("Step budget soft landing") |
| 873 | && !messages.contains("Write your final report now"), |
| 874 | "{flags:?}: no agent wrap-up notice in a one-shot answer: {messages}" |
| 875 | ); |
| 876 | } |
| 877 | } |
| 878 | } |
| 879 | |
| 880 | /// SSE for a response that reports `finish_reason: stop` while its usage says |
| 881 | /// the whole requested output allowance was used (#6889). `completion_tokens` |
| 882 | /// echoes the ceiling the request carried, whichever key it used. |
| 883 | fn stop_at_ceiling_response(content: Option<&'static str>) -> impl wiremock::Respond { |
| 884 | move |request: &wiremock::Request| { |
| 885 | let body: Value = serde_json::from_slice(&request.body).expect("request body JSON"); |
| 886 | let ceiling = body |
| 887 | .get("max_tokens") |
| 888 | .or_else(|| body.get("max_completion_tokens")) |
| 889 | .and_then(Value::as_u64) |
| 890 | .expect("the request names an output ceiling"); |
| 891 | let delta = content.map_or_else(|| json!({}), |text| json!({ "content": text })); |
| 892 | sse_response( |
| 893 | [ |
| 894 | sse_chunk(json!({ |
| 895 | "id": "chatcmpl-ceiling", |
| 896 | "object": "chat.completion.chunk", |
| 897 | "model": TEST_MODEL, |
| 898 | "choices": [{"index": 0, "delta": delta, "finish_reason": null}] |
| 899 | })), |
| 900 | sse_chunk(json!({ |
| 901 | "id": "chatcmpl-ceiling", |
| 902 | "object": "chat.completion.chunk", |
| 903 | "model": TEST_MODEL, |
| 904 | "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], |
| 905 | "usage": { |
| 906 | "prompt_tokens": 20, |
| 907 | "completion_tokens": ceiling, |
| 908 | "total_tokens": ceiling + 20 |
| 909 | } |
| 910 | })), |
| 911 | "data: [DONE]\n\n".to_string(), |
| 912 | ] |
| 913 | .join(""), |
| 914 | ) |
| 915 | } |
| 916 | } |
| 917 | |
| 918 | /// #6889: a provider can cut a response at the requested ceiling and still |
| 919 | /// report `finish_reason: stop`. Its own usage gives it away: the completion |
| 920 | /// tokens equal the ceiling. That response follows the same policy as a |
| 921 | /// `length` stop, so the partial answer is kept and the model is asked to |
| 922 | /// continue instead of the cut-off answer passing for a finished one. |
| 923 | #[tokio::test(flavor = "multi_thread")] |
| 924 | async fn plain_exec_continues_past_a_stop_that_used_the_whole_output_allowance() { |
| 925 | let server = MockServer::start().await; |
| 926 | Mock::given(method("GET")) |
| 927 | .and(path("/v1/models")) |
| 928 | .respond_with(json_response(json!({ |
| 929 | "object": "list", |
| 930 | "data": [{ "id": TEST_MODEL, "object": "model" }] |
| 931 | }))) |
| 932 | .mount(&server) |
| 933 | .await; |
| 934 | Mock::given(method("POST")) |
| 935 | .and(path("/v1/chat/completions")) |
| 936 | .respond_with(stop_at_ceiling_response(Some("first half"))) |
| 937 | .up_to_n_times(1) |
| 938 | .with_priority(1) |
| 939 | .mount(&server) |
| 940 | .await; |
| 941 | Mock::given(method("POST")) |
| 942 | .and(path("/v1/chat/completions")) |
| 943 | .respond_with(sse_response(answer_sse_without_usage(" second half"))) |
| 944 | .with_priority(2) |
| 945 | .mount(&server) |
| 946 | .await; |
| 947 | |
| 948 | let json_stdout = run_exec( |
| 949 | &server, |
| 950 | &[ |
| 951 | "--no-tools", |
| 952 | "--json", |
| 953 | "--model", |
| 954 | TEST_MODEL, |
| 955 | "answer briefly", |
| 956 | ], |
| 957 | ); |
| 958 | let receipt: Value = serde_json::from_str(&json_stdout) |
| 959 | .unwrap_or_else(|err| panic!("--json receipt should parse: {err}\n{json_stdout}")); |
| 960 | assert_eq!(receipt["success"], true, "{receipt}"); |
| 961 | let output = receipt["output"].as_str().unwrap_or_default(); |
| 962 | assert!( |
| 963 | output.contains("first half") && output.contains("second half"), |
| 964 | "{receipt}" |
| 965 | ); |
| 966 | |
| 967 | let bodies = chat_bodies(&server).await; |
| 968 | assert_eq!(bodies.len(), 2, "one continuation request: {bodies:#?}"); |
| 969 | assert!( |
| 970 | bodies[1]["messages"] |
| 971 | .to_string() |
| 972 | .contains("stopped generation at its output limit"), |
| 973 | "the continuation names the truncation: {}", |
| 974 | bodies[1]["messages"] |
| 975 | ); |
| 976 | } |
| 977 | |
| 978 | /// #6889: when the allowance was spent before any answer was written, the |
| 979 | /// response is empty and still says `stop`. Asking again reproduces it, so |
| 980 | /// the run fails after that one request instead of re-requesting it. |
| 981 | #[tokio::test(flavor = "multi_thread")] |
| 982 | async fn plain_exec_does_not_re_request_an_empty_stop_at_the_output_ceiling() { |
| 983 | let server = MockServer::start().await; |
| 984 | Mock::given(method("GET")) |
| 985 | .and(path("/v1/models")) |
| 986 | .respond_with(json_response(json!({ |
| 987 | "object": "list", |
| 988 | "data": [{ "id": TEST_MODEL, "object": "model" }] |
| 989 | }))) |
| 990 | .mount(&server) |
| 991 | .await; |
| 992 | Mock::given(method("POST")) |
| 993 | .and(path("/v1/chat/completions")) |
| 994 | .respond_with(stop_at_ceiling_response(None)) |
| 995 | .mount(&server) |
| 996 | .await; |
| 997 | |
| 998 | let (success, stdout, stderr) = run_exec_unchecked( |
| 999 | &server, |
| 1000 | &[ |
| 1001 | "--no-tools", |
| 1002 | "--json", |
| 1003 | "--model", |
| 1004 | TEST_MODEL, |
| 1005 | "answer briefly", |
| 1006 | ], |
| 1007 | ); |
| 1008 | assert!( |
| 1009 | !success, |
| 1010 | "an answerless response must not exit 0\nstdout:\n{stdout}\nstderr:\n{stderr}" |
| 1011 | ); |
| 1012 | |
| 1013 | let bodies = chat_bodies(&server).await; |
| 1014 | assert_eq!( |
| 1015 | bodies.len(), |
| 1016 | 1, |
| 1017 | "a stop at the ceiling is not re-requested: {bodies:#?}" |
| 1018 | ); |
| 1019 | } |
| 1020 | |
| 1021 | /// A stdio MCP server that reads `initialize`, closes its stdin, answers, and |
| 1022 | /// stays alive: the client's next write (`notifications/initialized`) always |
| 1023 | /// hits a pipe with no reader. That is the shape of the real failure, where a |
| 1024 | /// plugin's MCP server whose `node` could not start made `exec --auto` die of |
| 1025 | /// SIGPIPE (exit 141) before printing anything. |
| 1026 | const STDIN_CLOSING_MCP_SERVER: &str = r#"IFS= read -r _line; exec 0<&-; printf '%s\n' '{"jsonrpc":"2.0","id":"1","result":{"protocolVersion":"2024-11-05","serverInfo":{"name":"stdin-closer","version":"1.0.0"},"capabilities":{"tools":{}}}}'; sleep 10"#; |
| 1027 | |
| 1028 | #[tokio::test(flavor = "multi_thread")] |
| 1029 | async fn exec_auto_survives_an_mcp_server_that_closes_its_stdin() { |
| 1030 | let server = start_mock_llm(answer_sse_without_usage("ok")).await; |
| 1031 | let (success, stdout, stderr) = run_exec_in_home( |
| 1032 | &server, |
| 1033 | &["--auto", "--model", TEST_MODEL, "Reply with exactly: ok"], |
| 1034 | |home| { |
| 1035 | let config = json!({ |
| 1036 | "mcpServers": { |
| 1037 | "stdin-closer": { |
| 1038 | "command": "sh", |
| 1039 | "args": ["-c", STDIN_CLOSING_MCP_SERVER], |
| 1040 | // Connect at session start, as the Computer Use |
| 1041 | // plugin's server does, instead of on first use. |
| 1042 | "required": true |
| 1043 | } |
| 1044 | } |
| 1045 | }); |
| 1046 | let path = home.join(".codewhale").join("mcp.json"); |
| 1047 | std::fs::write(&path, config.to_string()).expect("write mcp.json"); |
| 1048 | }, |
| 1049 | ); |
| 1050 | assert!( |
| 1051 | success, |
| 1052 | "exec --auto must not die when an MCP peer closes its pipe\nstdout:\n{stdout}\nstderr:\n{stderr}" |
| 1053 | ); |
| 1054 | assert_eq!(stdout.trim(), "ok", "stderr:\n{stderr}"); |
| 1055 | } |
| 1056 | |
| 1057 | /// `exec --no-tools` offers no tools, yet DeepSeek can still answer with nothing |
| 1058 | /// but a DSML tool call. The markup must never reach stdout, and the run must |
| 1059 | /// fail once with the real reason instead of re-requesting the same call and |
| 1060 | /// ending on "the provider response was incomplete". |
| 1061 | #[tokio::test(flavor = "multi_thread")] |
| 1062 | async fn one_shot_exec_strips_deepseek_dsml_and_points_at_auto() { |
| 1063 | let dsml = "<||DSML|| calls>\n<||DSML|| invoke name=\"read_file\">\n<||DSML|| parameter name=\"path\" string=\"true\">note.txt</||DSML|| parameter>\n</||DSML|| invoke>\n</||DSML|| calls>\n"; |
| 1064 | let server = start_mock_llm(answer_sse_without_usage(dsml)).await; |
| 1065 | let (success, stdout, stderr) = run_exec_unchecked( |
| 1066 | &server, |
| 1067 | &[ |
| 1068 | "--no-tools", |
| 1069 | "--model", |
| 1070 | TEST_MODEL, |
| 1071 | "Read note.txt and tell me its contents.", |
| 1072 | ], |
| 1073 | ); |
| 1074 | assert!( |
| 1075 | !success, |
| 1076 | "a tool-call-only answer is not an answer\nstdout:\n{stdout}\nstderr:\n{stderr}" |
| 1077 | ); |
| 1078 | assert!( |
| 1079 | !stdout.contains("DSML") && !stdout.contains("read_file"), |
| 1080 | "raw tool-call markup reached stdout: {stdout:?}" |
| 1081 | ); |
| 1082 | assert!( |
| 1083 | stderr.contains("--auto") && stderr.contains("offers no tools"), |
| 1084 | "the user is told the task needs tools: {stderr}" |
| 1085 | ); |
| 1086 | assert_eq!( |
| 1087 | chat_bodies(&server).await.len(), |
| 1088 | 1, |
| 1089 | "a zero-tool text call must not be re-requested\nstderr:\n{stderr}" |
| 1090 | ); |
| 1091 | } |
| 1092 | |
| 1093 | /// Last user message text of a chat-completions body, without the |
| 1094 | /// `<turn_meta>` block the engine appends. |
| 1095 | fn last_user_text(body: &Value) -> String { |
| 1096 | let text = body["messages"] |
| 1097 | .as_array() |
| 1098 | .expect("messages array") |
| 1099 | .iter() |
| 1100 | .rev() |
| 1101 | .filter(|message| message["role"] == "user") |
| 1102 | .map(|message| match &message["content"] { |
| 1103 | Value::String(text) => text.clone(), |
| 1104 | other => other.to_string(), |
| 1105 | }) |
| 1106 | .find(|text| !text.starts_with("<codewhale:runtime_event")) |
| 1107 | .expect("a user message"); |
| 1108 | match text.split_once("\n<turn_meta>") { |
| 1109 | Some((prompt, _)) => prompt.to_string(), |
| 1110 | None => text, |
| 1111 | } |
| 1112 | } |
| 1113 | |
| 1114 | /// #6688: the prompt the model receives comes from `--prompt-file <PATH>` or |
| 1115 | /// `--prompt-file -` (stdin), past argv's 128 KiB per-argument ceiling. A |
| 1116 | /// positional `-` stays literal text, and piped stdin is appended to an argv |
| 1117 | /// prompt. |
| 1118 | #[tokio::test(flavor = "multi_thread")] |
| 1119 | async fn exec_prompt_reaches_the_model_from_prompt_file_and_stdin() { |
| 1120 | let server = start_mock_llm(answer_sse_with_usage("pong")).await; |
| 1121 | let dir = TempDir::new().expect("prompt tempdir"); |
| 1122 | let file_body = format!("FILE-PROMPT {}", "x".repeat(200 * 1024)); |
| 1123 | let file = dir.path().join("prompt.txt"); |
| 1124 | std::fs::write(&file, &file_body).expect("write prompt file"); |
| 1125 | let file_arg = file.to_str().expect("utf-8 path"); |
| 1126 | |
| 1127 | let (ok, stdout, stderr) = run_exec_with_stdin( |
| 1128 | &server, |
| 1129 | &["--model", TEST_MODEL, "--prompt-file", file_arg], |
| 1130 | |_| {}, |
| 1131 | None, |
| 1132 | ); |
| 1133 | assert!( |
| 1134 | ok, |
| 1135 | "--prompt-file <PATH>\nstdout:\n{stdout}\nstderr:\n{stderr}" |
| 1136 | ); |
| 1137 | let (ok, stdout, stderr) = run_exec_with_stdin( |
| 1138 | &server, |
| 1139 | &["--model", TEST_MODEL, "--prompt-file", "-"], |
| 1140 | |_| {}, |
| 1141 | Some(b"STDIN-PROMPT answer briefly".to_vec()), |
| 1142 | ); |
| 1143 | assert!(ok, "--prompt-file -\nstdout:\n{stdout}\nstderr:\n{stderr}"); |
| 1144 | let (ok, stdout, stderr) = run_exec_with_stdin( |
| 1145 | &server, |
| 1146 | &["--model", TEST_MODEL, "-"], |
| 1147 | |_| {}, |
| 1148 | Some(b"STDIN-APPENDED".to_vec()), |
| 1149 | ); |
| 1150 | assert!(ok, "positional -\nstdout:\n{stdout}\nstderr:\n{stderr}"); |
| 1151 | |
| 1152 | let bodies = chat_bodies(&server).await; |
| 1153 | assert_eq!(bodies.len(), 3, "one model call per run"); |
| 1154 | assert_eq!(last_user_text(&bodies[0]), file_body); |
| 1155 | assert_eq!(last_user_text(&bodies[1]), "STDIN-PROMPT answer briefly"); |
| 1156 | assert_eq!(last_user_text(&bodies[2]), "-\n\nSTDIN-APPENDED"); |
| 1157 | } |
| 1158 | |
| 1159 | #[tokio::test(flavor = "multi_thread")] |
| 1160 | async fn exec_json_schema_validates_plain_and_fenced_replies_without_changing_prefix() { |
| 1161 | let schema = r#"{"type":"object","properties":{"ok":{"type":"boolean"}},"required":["ok"],"additionalProperties":false}"#; |
| 1162 | let plain_server = start_mock_llm(answer_sse_with_usage(r#"{"ok":true}"#)).await; |
| 1163 | let (ok, stdout, stderr) = run_exec_unchecked( |
| 1164 | &plain_server, |
| 1165 | &["--no-tools", "--model", TEST_MODEL, "return json"], |
| 1166 | ); |
| 1167 | assert!(ok, "baseline failed\nstdout:\n{stdout}\nstderr:\n{stderr}"); |
| 1168 | let baseline_body = chat_bodies(&plain_server) |
| 1169 | .await |
| 1170 | .pop() |
| 1171 | .expect("baseline request"); |
| 1172 | |
| 1173 | let (ok, stdout, stderr) = run_exec_unchecked( |
| 1174 | &plain_server, |
| 1175 | &[ |
| 1176 | "--no-tools", |
| 1177 | "--model", |
| 1178 | TEST_MODEL, |
| 1179 | "--json-schema", |
| 1180 | schema, |
| 1181 | "return json", |
| 1182 | ], |
| 1183 | ); |
| 1184 | assert!( |
| 1185 | ok, |
| 1186 | "text schema failed\nstdout:\n{stdout}\nstderr:\n{stderr}" |
| 1187 | ); |
| 1188 | let parsed: Value = serde_json::from_str(stdout.trim()).expect("validated json stdout"); |
| 1189 | assert_eq!(parsed, json!({"ok": true})); |
| 1190 | |
| 1191 | let schema_bodies = chat_bodies(&plain_server).await; |
| 1192 | let schema_body = schema_bodies.last().expect("schema request"); |
| 1193 | assert_eq!(schema_body["messages"][0], baseline_body["messages"][0]); |
| 1194 | assert_eq!(schema_body["tools"], baseline_body["tools"]); |
| 1195 | |
| 1196 | let fenced_server = start_mock_llm(answer_sse_with_usage("```json\n{\"ok\":false}\n```")).await; |
| 1197 | let (ok, stdout, stderr) = run_exec_unchecked( |
| 1198 | &fenced_server, |
| 1199 | &[ |
| 1200 | "--no-tools", |
| 1201 | "--model", |
| 1202 | TEST_MODEL, |
| 1203 | "--json-schema", |
| 1204 | schema, |
| 1205 | "--output-format", |
| 1206 | "stream-json", |
| 1207 | "return json", |
| 1208 | ], |
| 1209 | ); |
| 1210 | assert!( |
| 1211 | ok, |
| 1212 | "stream-json fenced failed\nstdout:\n{stdout}\nstderr:\n{stderr}" |
| 1213 | ); |
| 1214 | let meta = stdout |
| 1215 | .lines() |
| 1216 | .filter(|l| !l.trim().is_empty()) |
| 1217 | .map(|l| serde_json::from_str::<Value>(l).expect("stream-json line")) |
| 1218 | .find(|v| v["type"] == "metadata") |
| 1219 | .expect("metadata event"); |
| 1220 | assert_eq!(meta["meta"]["structured_output"], json!({"ok": false})); |
| 1221 | |
| 1222 | let schema_dir = TempDir::new().expect("schema tempdir"); |
| 1223 | let schema_file = schema_dir.path().join("schema.json"); |
| 1224 | std::fs::write(&schema_file, schema).expect("write schema file"); |
| 1225 | let at_file = format!("@{}", schema_file.display()); |
| 1226 | let (ok, stdout, stderr) = run_exec_unchecked( |
| 1227 | &plain_server, |
| 1228 | &[ |
| 1229 | "--no-tools", |
| 1230 | "--model", |
| 1231 | TEST_MODEL, |
| 1232 | "--json-schema", |
| 1233 | &at_file, |
| 1234 | "return json", |
| 1235 | ], |
| 1236 | ); |
| 1237 | assert!( |
| 1238 | ok, |
| 1239 | "@file schema failed\nstdout:\n{stdout}\nstderr:\n{stderr}" |
| 1240 | ); |
| 1241 | let parsed: Value = serde_json::from_str(stdout.trim()).expect("validated @file json stdout"); |
| 1242 | assert_eq!(parsed, json!({"ok": true})); |
| 1243 | } |
| 1244 | |
| 1245 | #[tokio::test(flavor = "multi_thread")] |
| 1246 | async fn exec_json_schema_fails_closed_on_invalid_json_or_schema_violation_and_before_call() { |
| 1247 | let schema = |
| 1248 | r#"{"type":"object","properties":{"count":{"type":"integer"}},"required":["count"]}"#; |
| 1249 | |
| 1250 | let bad_schema_server = start_mock_llm(answer_sse_with_usage("{}")).await; |
| 1251 | let (ok, _, stderr) = run_exec_unchecked( |
| 1252 | &bad_schema_server, |
| 1253 | &[ |
| 1254 | "--no-tools", |
| 1255 | "--model", |
| 1256 | TEST_MODEL, |
| 1257 | "--json-schema", |
| 1258 | r#"{"type":"not-a-type"}"#, |
| 1259 | "return json", |
| 1260 | ], |
| 1261 | ); |
| 1262 | assert!(!ok, "invalid schema must fail"); |
| 1263 | assert!(stderr.contains("invalid schema"), "{stderr}"); |
| 1264 | assert!( |
| 1265 | chat_bodies(&bad_schema_server).await.is_empty(), |
| 1266 | "invalid schema must fail before any provider call" |
| 1267 | ); |
| 1268 | |
| 1269 | let (ok, _, stderr) = run_exec_unchecked( |
| 1270 | &bad_schema_server, |
| 1271 | &[ |
| 1272 | "--no-tools", |
| 1273 | "--model", |
| 1274 | TEST_MODEL, |
| 1275 | "--json-schema", |
| 1276 | "@", |
| 1277 | "return json", |
| 1278 | ], |
| 1279 | ); |
| 1280 | assert!(!ok, "bare @ must fail"); |
| 1281 | assert!(stderr.contains("requires a file path"), "{stderr}"); |
| 1282 | |
| 1283 | let (ok, _, stderr) = run_exec_unchecked( |
| 1284 | &bad_schema_server, |
| 1285 | &["--agent", "claude", "--json-schema", schema, "return json"], |
| 1286 | ); |
| 1287 | assert!(!ok, "--agent with --json-schema must fail"); |
| 1288 | assert!(stderr.contains("--json-schema"), "{stderr}"); |
| 1289 | |
| 1290 | let non_json_server = start_mock_llm(answer_sse_with_usage("not valid json at all")).await; |
| 1291 | let (ok, stdout, _) = run_exec_unchecked( |
| 1292 | &non_json_server, |
| 1293 | &[ |
| 1294 | "--no-tools", |
| 1295 | "--model", |
| 1296 | TEST_MODEL, |
| 1297 | "--json-schema", |
| 1298 | schema, |
| 1299 | "--output-format", |
| 1300 | "stream-json", |
| 1301 | "return json", |
| 1302 | ], |
| 1303 | ); |
| 1304 | assert!(!ok, "non-JSON reply must exit 1"); |
| 1305 | let meta = stdout |
| 1306 | .lines() |
| 1307 | .filter(|l| !l.trim().is_empty()) |
| 1308 | .map(|l| serde_json::from_str::<Value>(l).expect("stream-json line")) |
| 1309 | .find(|v| v["type"] == "metadata") |
| 1310 | .expect("metadata event"); |
| 1311 | assert_eq!(meta["meta"]["status"], "failed"); |
| 1312 | assert_eq!(meta["meta"]["termination_reason"], "unresolved"); |
| 1313 | assert!( |
| 1314 | meta["meta"]["error"] |
| 1315 | .as_str() |
| 1316 | .unwrap_or("") |
| 1317 | .contains("not valid JSON"), |
| 1318 | "{meta}" |
| 1319 | ); |
| 1320 | |
| 1321 | let violation_server = start_mock_llm(answer_sse_with_usage(r#"{"count":"two"}"#)).await; |
| 1322 | let (ok, stdout, _) = run_exec_unchecked( |
| 1323 | &violation_server, |
| 1324 | &[ |
| 1325 | "--no-tools", |
| 1326 | "--model", |
| 1327 | TEST_MODEL, |
| 1328 | "--json-schema", |
| 1329 | schema, |
| 1330 | "--json", |
| 1331 | "return json", |
| 1332 | ], |
| 1333 | ); |
| 1334 | assert!(!ok, "schema violation must exit 1"); |
| 1335 | let summary: Value = serde_json::from_str(&stdout).expect("summary json"); |
| 1336 | assert_eq!(summary["status"], "failed"); |
| 1337 | assert_eq!(summary["termination_reason"], "unresolved"); |
| 1338 | assert!( |
| 1339 | summary["error"] |
| 1340 | .as_str() |
| 1341 | .unwrap_or("") |
| 1342 | .contains("schema validation"), |
| 1343 | "{summary}" |
| 1344 | ); |
| 1345 | assert!(summary.get("structured_output").is_none()); |
| 1346 | } |
| 1347 |