//! Codex-shaped requests: reasoning, tool choice, parallel calls and known prompt text. use crate::harness::{ Stack, assert_stream_invariants, body, runtime_config, scripted_text, sse_events, text_of, tool_markup, }; use leleka_backend_api::Usage; use leleka_backend_api::scripted::{Script, ScriptedEngine}; use serde_json::{Value, json}; use std::sync::Arc; use std::time::Duration; use strata_control::backend_worker::{BackendWorkerConfig, run_backend_worker}; use strata_control::worker::{WorkerState, WorkerStatus}; use tokio::sync::{RwLock, mpsc, watch}; fn shell_tool() -> Value { json!({"type": "function", "name": "shell", "description": "Run a command", "strict": false, "parameters": {"type": "object", "properties": {"command": {"type": "array", "items": {"type": "string"}}}, "required": ["command"]}}) } /// 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 = 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"} }); let markup = "The user wants a listing.\n\n\n\n\n[\"ls\",\"-la\"]\n\n\n"; scripted_text(&stack.engine, markup, 11); let (status, text) = stack.post("/v1/responses", &turn_one).await; assert_eq!(status, 200, "{text}"); 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().clone(); 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"]}) ); // The prompt the engine saw: the instructions as the system turn, thinking opened for the model. 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); // store:false really stores nothing. let (status, _) = stack .get(&format!( "/v1/responses/{}", response["id"].as_str().unwrap() )) .await; assert_eq!(status, 404); // Turn two replays the whole transcript, the way a stateless client does. 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"}); 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}"); 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}"); stack.finish().await; } #[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"]})) ); let request = |extra: Value| { let mut value = body(json!({"tools": [shell_tool()], "stream": true})); for (key, item) in extra.as_object().unwrap() { value[key] = item.clone(); } value }; // parallel_tool_calls:false + two calls => the response fails instead of publishing both. scripted_text(&stack.engine, &two_calls, 17); let (_, text) = stack .post( "/v1/responses", &request(json!({"parallel_tool_calls": false})), ) .await; let events = sse_events(&text); assert_stream_invariants(&events); assert_eq!(events.last().unwrap()["type"], "response.failed"); // parallel allowed => both calls arrive. scripted_text(&stack.engine, &two_calls, 17); let (_, text) = stack .post( "/v1/responses", &request(json!({"parallel_tool_calls": true})), ) .await; let events = sse_events(&text); assert_eq!(events.last().unwrap()["type"], "response.completed"); let calls = events.last().unwrap()["response"]["output"] .as_array() .unwrap() .iter() .filter(|i| i["type"] == "function_call") .count(); assert_eq!(calls, 2); // tool_choice none + a call => failure; required + plain text => failure; forced name mismatch. scripted_text( &stack.engine, &tool_markup("shell", &json!({"command": ["ls"]})), 17, ); let (_, text) = stack .post("/v1/responses", &request(json!({"tool_choice": "none"}))) .await; assert_eq!(sse_events(&text).last().unwrap()["type"], "response.failed"); scripted_text(&stack.engine, "just words", 17); let (_, text) = stack .post( "/v1/responses", &request(json!({"tool_choice": "required"})), ) .await; assert_eq!(sse_events(&text).last().unwrap()["type"], "response.failed"); scripted_text( &stack.engine, &tool_markup("shell", &json!({"command": ["ls"]})), 17, ); let (_, text) = stack .post( "/v1/responses", &request(json!({"tool_choice": {"type": "function", "name": "shell"}})), ) .await; assert_eq!( sse_events(&text).last().unwrap()["type"], "response.completed" ); stack.finish().await; } #[tokio::test] async fn a_known_prompt_text_is_sent_only_when_the_ids_decode_to_it() { use strata_control::wire::Generate; use strata_control::worker::{GenerationCommand, GenerationResult}; let stack = Stack::start("bw-known-text").await; let (requests, requests_rx) = mpsc::channel(1); let (_control, control_rx) = mpsc::channel(1); let (engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor()); handle.respond_with(|_| { Script::stop_with( &["ok"], Usage { input_tokens: 1, output_tokens: 1, reused_input_tokens: 0, }, ) }); let status = Arc::new(RwLock::new(WorkerStatus::default())); let (_stop, stop_rx) = watch::channel(false); let config = BackendWorkerConfig { tokenizer: stack.tokenizer.clone(), model: ScriptedEngine::fixture_descriptor(), runtime: runtime_config(), max_context: 262_144, max_output_tokens: 4096, health_interval: Duration::from_millis(20), generation_timeout: None, stall_timeout: None, attach_retry: Duration::from_millis(20), cancel_drain_timeout: Duration::from_secs(1), prefix_view: None, memory_view: None, }; tokio::spawn(run_backend_worker( Box::new(engine), config, status.clone(), stop_rx, requests_rx, control_rx, )); while status.read().await.state != WorkerState::Ready { tokio::time::sleep(Duration::from_millis(5)).await; } let ask = async |text: &str, claimed: Option<&str>| { let (sender, receiver) = tokio::sync::oneshot::channel(); requests .send(GenerationCommand { queue: None, activity: None, request: Generate { token_ids: stack.tokenizer.encode(text, true).unwrap(), max_new: 8, prompt_text: claimed.map(Arc::from), ..Default::default() }, result: GenerationResult::Buffered(sender), }) .await .unwrap(); receiver.await.unwrap().expect("served"); }; // the text the ids were produced from: the engine gets exactly that text ask("hello tool<|im_end|>\n", Some("hello tool<|im_end|>\n")).await; // a claim the ids do not decode to is not trusted: the engine gets the text of the ids ask("hello tool", Some("something else entirely")).await; // no claim: the ids are decoded and checked as before ask("tool hello", None).await; let prompts: Vec = handle.requests().into_iter().map(|r| r.prompt).collect(); assert_eq!( prompts, ["hello tool<|im_end|>\n", "hello tool", "tool hello"] ); stack.finish().await; }