//! Codex-shaped requests: reasoning, tool choice, parallel calls and known prompt text. use crate::harness::{ Stack, assert_stream_invariants, body, scripted_text, sse_events, text_of, tool_markup, }; use crate::second_worker::{self, SecondWorker}; use leleka_backend_api::Usage; use leleka_backend_api::scripted::Script; use serde_json::{Value, json}; use std::sync::Arc; use strata_control::wire::Generate; #[rustfmt::skip] fn shell_tool() -> Value { let command = json!({"type": "array", "items": {"type": "string"}}); let parameters = json!({"type": "object", "properties": {"command": command}, "required": ["command"]}); json!({"type": "function", "name": "shell", "description": "Run a command", "strict": false, "parameters": parameters}) } const TURN_ONE_MARKUP: &str = concat!( "The user wants a listing.\n\n", "\n\n\n[\"ls\",\"-la\"]\n\n", "\n" ); /// The first request of the Codex console: instructions, the shell tool, reasoning and no storage. fn turn_one_request() -> Value { json!({ "model": "fixture", "instructions": "You are a coding agent.", "input": [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "List the files."}]}], "tools": [shell_tool()], "tool_choice": "auto", "parallel_tool_calls": false, "reasoning": {"effort": "medium", "summary": "auto"}, "store": false, "stream": true, "include": ["reasoning.encrypted_content"], "prompt_cache_key": "019a0000-0000-7000-8000-000000000000", "text": {"verbosity": "low"}, "service_tier": "priority", "client_metadata": {"x-codex-installation-id": "synthetic-installation"} }) } /// Turn two replays the whole transcript, the way a stateless client does. fn turn_two_request(turn_one: &Value, output: Vec, call: &Value) -> Value { let mut input = turn_one["input"].as_array().unwrap().clone(); input.extend(output); input.push( json!({"type": "function_call_output", "call_id": call["call_id"], "output": "Cargo.toml\nsrc"}), ); let mut turn_two = turn_one.clone(); turn_two["input"] = Value::Array(input); turn_two["reasoning"] = json!({"effort": "medium", "summary": "auto"}); turn_two } /// The streamed first turn: reasoning, one `shell` call; returns the final response and the call. fn assert_turn_one_stream(text: &str) -> (Value, Value) { let events = sse_events(text); assert_stream_invariants(&events); assert_eq!(events.last().unwrap()["type"], "response.completed"); let kinds: Vec<&str> = events.iter().map(|e| e["type"].as_str().unwrap()).collect(); assert!( kinds.contains(&"response.reasoning_text.delta"), "{kinds:?}" ); assert!( kinds.contains(&"response.function_call_arguments.done"), "{kinds:?}" ); let response = events.last().unwrap()["response"].clone(); assert_eq!(response["store"], json!(false)); let output = response["output"].as_array().unwrap(); let reasoning = output.iter().find(|i| i["type"] == "reasoning").unwrap(); assert_eq!(reasoning["content"][0]["text"], "The user wants a listing."); let call = output .iter() .find(|i| i["type"] == "function_call") .unwrap() .clone(); assert_eq!(call["name"], "shell"); assert_eq!( serde_json::from_str::(call["arguments"].as_str().unwrap()).unwrap(), json!({"command": ["ls", "-la"]}) ); (response, call) } /// The prompt the engine saw: the instructions as the system turn, thinking opened for the model. fn assert_turn_one_prompt(stack: &Stack) { let prompt = stack.engine.requests()[0].prompt.clone(); assert!(prompt.starts_with("<|im_start|>system\n"), "{prompt}"); assert!(prompt.contains("You are a coding agent."), "{prompt}"); assert!(prompt.contains("List the files."), "{prompt}"); assert!(prompt.ends_with("\n"), "{prompt}"); assert_eq!(stack.engine.requests()[0].max_output_tokens, 4096); } fn assert_turn_two_replayed(stack: &Stack, text: &str) { let events = sse_events(text); assert_stream_invariants(&events); assert_eq!(events.last().unwrap()["type"], "response.completed"); let final_text = text_of(&events.last().unwrap()["response"]); assert_eq!(final_text, "Cargo.toml and src."); let second = &stack.engine.requests()[1].prompt; assert!(second.contains("Cargo.toml\nsrc"), "{second}"); assert!(second.contains("The user wants a listing."), "{second}"); assert!(second.contains(""), "{second}"); } /// The request shape of the Codex console (fields and values as it sends them), two turns, stateless /// replay of the first turn's output items, through the runtime stack. Synthetic prompts and scripted /// engine output: this checks that the surface is accepted and the protocol holds, not Codex itself. #[tokio::test] async fn a_codex_shaped_request_streams_reasoning_and_a_tool_call_and_replays_statelessly() { let stack = Stack::start("bw-codex").await; let turn_one = turn_one_request(); scripted_text(&stack.engine, TURN_ONE_MARKUP, 11); let (status, text) = stack.post("/v1/responses", &turn_one).await; assert_eq!(status, 200, "{text}"); let (response, call) = assert_turn_one_stream(&text); assert_turn_one_prompt(&stack); // store:false really stores nothing. let (status, _) = stack .get(&format!( "/v1/responses/{}", response["id"].as_str().unwrap() )) .await; assert_eq!(status, 404); let output = response["output"].as_array().unwrap().clone(); let turn_two = turn_two_request(&turn_one, output, &call); scripted_text( &stack.engine, "There are two entries.\n\nCargo.toml and src.", 13, ); let (status, text) = stack.post("/v1/responses", &turn_two).await; assert_eq!(status, 200, "{text}"); assert_turn_two_replayed(&stack, &text); stack.finish().await; } fn tool_request(extra: Value) -> Value { let mut value = body(json!({"tools": [shell_tool()], "stream": true})); for (key, item) in extra.as_object().unwrap() { value[key] = item.clone(); } value } /// Scripts `markup` as the engine output and returns the events of the streamed response. async fn tool_events(stack: &Stack, markup: &str, extra: Value) -> Vec { scripted_text(&stack.engine, markup, 17); let (_, text) = stack.post("/v1/responses", &tool_request(extra)).await; sse_events(&text) } fn last_type(events: &[Value]) -> String { events.last().unwrap()["type"].as_str().unwrap().to_owned() } fn function_calls(events: &[Value]) -> usize { events.last().unwrap()["response"]["output"] .as_array() .unwrap() .iter() .filter(|i| i["type"] == "function_call") .count() } #[tokio::test] async fn codex_tool_choice_and_parallel_calls_are_enforced_on_the_generated_calls() { let stack = Stack::start("bw-toolchoice").await; let two_calls = format!( "{}\n{}", tool_markup("shell", &json!({"command": ["ls"]})), tool_markup("shell", &json!({"command": ["pwd"]})) ); // parallel_tool_calls:false + two calls => the response fails instead of publishing both. let events = tool_events(&stack, &two_calls, json!({"parallel_tool_calls": false})).await; assert_stream_invariants(&events); assert_eq!(last_type(&events), "response.failed"); // parallel allowed => both calls arrive. let events = tool_events(&stack, &two_calls, json!({"parallel_tool_calls": true})).await; assert_eq!(last_type(&events), "response.completed"); assert_eq!(function_calls(&events), 2); // tool_choice none + a call => failure; required + plain text => failure; forced name mismatch. let one_call = tool_markup("shell", &json!({"command": ["ls"]})); let events = tool_events(&stack, &one_call, json!({"tool_choice": "none"})).await; assert_eq!(last_type(&events), "response.failed"); let events = tool_events(&stack, "just words", json!({"tool_choice": "required"})).await; assert_eq!(last_type(&events), "response.failed"); let forced = json!({"tool_choice": {"type": "function", "name": "shell"}}); let events = tool_events(&stack, &one_call, forced).await; assert_eq!(last_type(&events), "response.completed"); stack.finish().await; } /// A second worker whose scripted engine always answers "ok". async fn start_ok_worker(stack: &Stack) -> SecondWorker { let worker = second_worker::start(stack).await; worker.handle.respond_with(|_| { Script::stop_with( &["ok"], Usage { input_tokens: 1, output_tokens: 1, reused_input_tokens: 0, }, ) }); worker } /// Sends `text` as ids with an optional claim of the prompt text they came from, and waits for the answer. async fn ask(worker: &SecondWorker, stack: &Stack, text: &str, claimed: Option<&str>) { let request = Generate { token_ids: stack.tokenizer.encode(text, true).unwrap(), max_new: 8, prompt_text: claimed.map(Arc::from), ..Default::default() }; second_worker::submit(&worker.requests, request) .await .expect("served"); } #[tokio::test] async fn a_known_prompt_text_is_sent_only_when_the_ids_decode_to_it() { let stack = Stack::start("bw-known-text").await; let worker = start_ok_worker(&stack).await; // the text the ids were produced from: the engine gets exactly that text let known = "hello tool<|im_end|>\n"; ask(&worker, &stack, known, Some(known)).await; // a claim the ids do not decode to is not trusted: the engine gets the text of the ids let claim = Some("something else entirely"); ask(&worker, &stack, "hello tool", claim).await; // no claim: the ids are decoded and checked as before ask(&worker, &stack, "tool hello", None).await; let prompts: Vec = worker .handle .requests() .into_iter() .map(|r| r.prompt) .collect(); assert_eq!( prompts, ["hello tool<|im_end|>\n", "hello tool", "tool hello"] ); stack.finish().await; }