okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6ca60e9a0
main
1"""serve/test_responses.py - #451: the Responses API (POST /v1/responses) against the mock engine (no GPU, no pack). 2 3python -m unittest serve.test_responses -v 4""" 5from __future__import annotations 6 7import base64 8import contextlib 9import http .client 10import io 11import json 12import sys 13import unittest 14from pathlib import Path 15 16sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 17from serve import responses # noqa: E402 18from serve .frontend import ChatTemplate # noqa: E402 19from serve .responses import (ENCRYPTED_PREFIX ,ResponsesError ,collect ,input_messages ,prompt_made ,# noqa: E402 20prompt_tools ,request_tools ,template_kwargs ,text_format ,thread_title_events ) 21from serve .server import ByteTokenizer ,MockEngine ,Service ,serve # noqa: E402 22 23ROOT = Path (__file__ ).resolve ().parents [1 ] 24TEMPLATE = ChatTemplate (ROOT / "serve/chat_template.jinja" ) 25 26CALL = ("Let me look.\n</think>\n\nChecking.\n\n<tool_call>\n<function=exec_command>\n<parameter=cmd>\ncat a.txt\n" 27"</parameter>\n</function>\n</tool_call>" ) 28ANSWER = "Read it.\n</think>\n\nThe file says before." 29TOOLS = [{"type" :"function" ,"name" :"exec_command" ,"description" :"Runs a command." ,"strict" :False , 30"parameters" : {"type" :"object" ,"properties" : {"cmd" : {"type" :"string" }},"required" : ["cmd" ]}}] 31 32 33# ------------------------------------------------------------------------------------------------ parsing 34class Parsing (unittest .TestCase ): 35def test_a_string_input_is_one_user_message (self ): 36self .assertEqual (input_messages ({"input" :"hi" ,"instructions" :"Be brief." }), 37 [{"role" :"system" ,"content" :"Be brief." }, {"role" :"user" ,"content" :"hi" }]) 38 39def test_leading_developer_messages_join_the_system_message_later_ones_become_user (self ): 40msgs = input_messages ({"instructions" :"I" ,"input" : [ 41 {"type" :"message" ,"role" :"developer" ,"content" : [{"type" :"input_text" ,"text" :"D1" }, 42 {"type" :"input_text" ,"text" :"D2" }]}, 43 {"role" :"user" ,"content" :"u" }, 44 {"type" :"message" ,"role" :"developer" ,"content" :"late" }]}) 45self .assertEqual (msgs , [{"role" :"system" ,"content" :"I\n\nD1D2" }, {"role" :"user" ,"content" :"u" }, 46 {"role" :"user" ,"content" :"late" }]) 47 48def test_codex_history_becomes_one_assistant_turn_per_answer (self ): 49items = [{"type" :"message" ,"role" :"user" ,"content" : [{"type" :"input_text" ,"text" :"edit it" }]}, 50 {"type" :"reasoning" ,"id" :"rs_1" ,"summary" : [], 51"content" : [{"type" :"reasoning_text" ,"text" :"look first" }]}, 52 {"type" :"message" ,"role" :"assistant" ,"content" : [{"type" :"output_text" ,"text" :"Looking." }]}, 53 {"type" :"function_call" ,"id" :"fc_1" ,"call_id" :"c1" ,"name" :"exec_command" , 54"arguments" :"{\"cmd\":\"cat a\"}" }, 55 {"type" :"function_call" ,"id" :"fc_2" ,"call_id" :"c2" ,"name" :"spawn_agent" , 56"namespace" :"multi_agent_v1" ,"arguments" :"{}" }, 57# results in the order they finished, not the order of the calls 58 {"type" :"function_call_output" ,"call_id" :"c2" ,"output" :"agent" }, 59 {"type" :"function_call_output" ,"call_id" :"c1" , 60"output" : [{"type" :"input_text" ,"text" :"before" }]}, 61 {"type" :"reasoning" ,"id" :"rs_2" ,"summary" : [{"type" :"summary_text" ,"text" :"s" }], 62"content" : [{"type" :"reasoning_text" ,"text" :"now write" }]}, 63 {"type" :"function_call" ,"call_id" :"c3" ,"name" :"exec_command" ,"arguments" :"{\"cmd\":\"w\"}" }, 64 {"type" :"function_call_output" ,"call_id" :"c3" ,"output" :"ok" }] 65self .assertEqual (input_messages ({"input" :items }), [ 66 {"role" :"user" ,"content" :"edit it" }, 67 {"role" :"assistant" ,"content" :"Looking." ,"reasoning_content" :"look first" ,"tool_calls" : [ 68 {"function" : {"name" :"exec_command" ,"arguments" : {"cmd" :"cat a" }}}, 69 {"function" : {"name" :"multi_agent_v1.spawn_agent" ,"arguments" : {}}}]}, 70 {"role" :"tool" ,"content" :"before" }, {"role" :"tool" ,"content" :"agent" }, 71 {"role" :"assistant" ,"content" :"" ,"reasoning_content" :"now write" ,"tool_calls" : [ 72 {"function" : {"name" :"exec_command" ,"arguments" : {"cmd" :"w" }}}]}, 73 {"role" :"tool" ,"content" :"ok" }]) 74 75def test_reasoning_comes_back_from_our_encrypted_content_and_foreign_tokens_are_ignored (self ): 76enc = ENCRYPTED_PREFIX + base64 .b64encode (json .dumps ({"text" :"hidden" }).encode ()).decode () 77for item ,want in (({"encrypted_content" :enc ,"summary" : []},"hidden" ), 78 ({"encrypted_content" :"gAAAAAB-someone-elses" ,"summary" : []},None )): 79msgs = input_messages ({"input" : [{"role" :"user" ,"content" :"q" }, {"type" :"reasoning" ,** item }, 80 {"role" :"assistant" ,"content" :"a" }]}) 81self .assertEqual (msgs [1 ].get ("reasoning_content" ),want ) 82with self .assertRaises (ResponsesError )as e : 83input_messages ({"input" : [{"type" :"reasoning" ,"encrypted_content" :ENCRYPTED_PREFIX + "!!" }]}) 84self .assertEqual (e .exception .param ,"input[0].encrypted_content" ) 85 86def test_bad_arguments_from_a_cut_off_call_do_not_refuse_the_conversation (self ): 87msgs = input_messages ({"input" : [{"role" :"user" ,"content" :"q" }, 88 {"type" :"function_call" ,"call_id" :"c" ,"name" :"f" ,"arguments" :"{\"a" }, 89 {"type" :"function_call_output" ,"call_id" :"c" ,"output" :"x" }]}) 90self .assertEqual (msgs [1 ]["tool_calls" ][0 ]["function" ]["arguments" ], {"arguments" :"{\"a" }) 91 92def test_unsupported_items_are_named (self ): 93for items ,param in (([{"type" :"item_reference" ,"id" :"msg_1" }],"input[0]" ), 94 ([{"type" :"web_search_call" }],"input[0].type" ), 95 ([{"role" :"user" ,"content" : [{"type" :"input_file" ,"file_id" :"f" }]}], 96"input[0].content[0].type" ), 97 ([{"role" :"robot" ,"content" :"x" }],"input[0].role" )): 98with self .assertRaises (ResponsesError )as e : 99input_messages ({"input" :items }) 100self .assertEqual (e .exception .param ,param ) 101with self .assertRaises (ResponsesError ): 102input_messages ({}) 103 104def test_tools_namespaces_custom_and_hosted (self ): 105tools ,names ,skipped = request_tools ({"tools" : [ 106* TOOLS , {"type" :"namespace" ,"name" :"mcp_fs" ,"description" :"Files." , 107"tools" : [{"type" :"function" ,"name" :"read" ,"parameters" : {"type" :"object" }}]}, 108 {"type" :"custom" ,"name" :"apply_patch" ,"description" :"Patch." , 109"format" : {"type" :"grammar" ,"syntax" :"lark" ,"definition" :"start: \"x\"" }}, 110 {"type" :"web_search" }]}) 111self .assertEqual ([t ["name" ]for t in tools ], ["exec_command" ,"mcp_fs.read" ,"apply_patch" ]) 112self .assertEqual (tools [1 ]["description" ],"Files." ) 113self .assertIn ("start: \"x\"" ,tools [2 ]["description" ]) 114self .assertEqual (names ["mcp_fs.read" ], ("mcp_fs" ,"read" ,"function" )) 115self .assertEqual (names ["apply_patch" ], (None ,"apply_patch" ,"custom" )) 116self .assertEqual (skipped , ["web_search" ]) 117self .assertIsNone (request_tools ({"tools" :TOOLS ,"tool_choice" :"none" })[0 ]) 118 119def test_additional_tools_input_items_are_accepted (self ): 120"""#782: Codex sends an `additional_tools` input item; it used to be refused with a 400.""" 121extra = {"type" :"additional_tools" ,"tools" : [{"type" :"function" ,"name" :"later_tool" , 122"parameters" : {"type" :"object" }}]} 123req = {"input" : [{"type" :"message" ,"role" :"user" ,"content" :"hi" },extra , 124 {"type" :"additional_tools" }],"tools" :TOOLS } 125self .assertEqual ([m ["role" ]for m in input_messages (req )], ["user" ]) 126tools ,names ,_ = request_tools (req ) 127self .assertEqual ([t ["name" ]for t in tools ], ["exec_command" ,"later_tool" ]) 128self .assertIn ("later_tool" ,names ) 129 130def test_effort_and_text_format (self ): 131self .assertEqual (template_kwargs ({"reasoning" : {"effort" :"minimal" }}, {}), {"enable_thinking" :False }) 132self .assertEqual (template_kwargs ({"reasoning" : {"effort" :"high" }}, {}), {"reasoning_effort" :"xhigh" }) 133self .assertEqual (template_kwargs ({"reasoning" : {"summary" :"auto" }}, {}), {})# Codex: the default 134self .assertEqual (template_kwargs ({}, {"reasoning_effort" :"low" }), {"reasoning_effort" :"low" }) 135with self .assertRaises (ResponsesError ): 136template_kwargs ({"reasoning" : {"effort" :"huge" }}, {}) 137self .assertEqual (text_format ({"text" : {"format" : {"type" :"json_schema" ,"name" :"n" ,"schema" : {}}}}), 138 {"type" :"json_schema" ,"json_schema" : {"name" :"n" ,"schema" : {}}}) 139self .assertIsNone (text_format ({"text" : {"format" : {"type" :"text" }}})) 140 141 142# ------------------------------------------------------------------------------------------------ Codex compaction 143HISTORY = [{"role" :"user" ,"content" :"hi" }, 144 {"type" :"function_call" ,"name" :"exec_command" ,"arguments" :"{}" ,"call_id" :"c1" }, 145 {"type" :"function_call_output" ,"call_id" :"c1" ,"output" :"ok" }] 146COMPACT_PROMPT = "You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary." # Codex's default 147OTHER_TOOLS = [{"type" :"function" ,"name" :"read_file" ,"description" :"Reads a file." , 148"parameters" : {"type" :"object" ,"properties" : {"path" : {"type" :"string" }}}}] 149A ,B = ("019a-a" ,"019a-a" ), ("019a-b" ,"019a-b" )# (session_id, thread_id) of two root conversations 150 151 152def codex_meta (kind ,conversation = A ): 153"""client_metadata as Codex 0.160 sends it: the turn metadata is a JSON string.""" 154session ,thread = conversation 155return {"session_id" :session ,"thread_id" :thread ,"x-codex-turn-metadata" :json .dumps ( 156 {"session_id" :session ,"thread_id" :thread ,"request_kind" :kind })} 157 158 159def codex_request (kind ,conversation = A ,tools = None ,last = COMPACT_PROMPT ,meta = None ): 160"""A Codex request; a compaction one is the conversation again with `tools: []` (codex-rs compact.rs). Every 161conversation sends the same prompt_cache_key here: it is not what tells them apart.""" 162req = {"instructions" :"Be brief" ,"tools" :tools or [],"tool_choice" :"auto" ,"prompt_cache_key" :"same" , 163"parallel_tool_calls" :bool (tools ),"input" :HISTORY + ([{"role" :"user" ,"content" :last }] 164if kind == "compaction" else [])} 165req ["client_metadata" ]= codex_meta (kind ,conversation )if meta is None else meta 166return req 167 168 169def tools_of (req ): 170"""(the request's tools, the prompt's tools), as _responses_prepare gets them (the prompt then goes out).""" 171tools = request_tools (req )[0 ] 172shown = prompt_tools (req ,tools ) 173prompt_made (req ,shown ) 174return tools ,shown 175 176 177class CodexCompaction (unittest .TestCase ): 178def setUp (self ): 179responses ._kept_prompt_tools = (None ,None ) 180 181def test_a_compaction_prompt_starts_as_its_conversations_last_prompt (self ): 182turn = codex_request ("turn" ,tools = TOOLS ) 183before = TEMPLATE .render (input_messages (turn ),tools = tools_of (turn )[1 ],add_generation_prompt = False ) 184req = codex_request ("compaction" ) 185own ,shown = tools_of (req ) 186self .assertIsNone (own )# the request's tools: still none 187self .assertEqual (shown ,request_tools (turn )[0 ]) 188self .assertTrue (TEMPLATE .render (input_messages (req ),tools = shown ).startswith (before )) 189self .assertFalse (TEMPLATE .render (input_messages (req ),tools = own ).startswith (before ))# what it was 190shown .clear ()# the kept list is nobody's to change 191self .assertEqual (tools_of (req )[1 ],request_tools (turn )[0 ]) 192self .assertEqual (tools_of (req )[1 ],request_tools (turn )[0 ])# a compaction leaves the entry as it was 193 194def test_another_conversation_never_gets_these_tools (self ): 195tools_of (codex_request ("turn" ,A ,TOOLS )) 196b = tools_of (codex_request ("turn" ,B ,OTHER_TOOLS ))[1 ] 197self .assertIsNone (tools_of (codex_request ("compaction" ,A ))[1 ])# one entry, B's: A reads again 198self .assertEqual (tools_of (codex_request ("compaction" ,B ))[1 ],b ) 199for other in (("019a-b" ,"019a-sub" ),# a sub-agent: the root's session, its own thread 200 ("019a-fork" ,"019a-fork" )):# a fork, or an ephemeral fork (same prompt_cache_key) 201self .assertIsNone (tools_of (codex_request ("compaction" ,other ))[1 ]) 202self .assertEqual (tools_of (codex_request ("compaction" ,B ))[1 ],b )# and they changed nothing 203tools_of (codex_request ("turn" ,A ,TOOLS )) 204self .assertIsNone (tools_of (codex_request ("compaction" ,B ))[1 ])# A's turn came last: B reads again 205self .assertEqual (tools_of (codex_request ("compaction" ,A ))[1 ],request_tools ({"tools" :TOOLS })[0 ]) 206 207def test_requests_that_are_not_a_codex_compaction_are_rendered_as_sent (self ): 208tools_of (codex_request ("turn" ,tools = TOOLS )) 209self .assertEqual (tools_of ({"input" :"another chat" }), (None ,None )) 210self .assertEqual (tools_of ({"input" :COMPACT_PROMPT ,"prompt_cache_key" :"same" }), (None ,None )) 211self .assertEqual (tools_of (codex_request ("compaction" ,meta = {})), (None ,None )) 212self .assertEqual (tools_of (codex_request ("compaction" ))[1 ],request_tools ({"tools" :TOOLS })[0 ]) 213self .assertEqual (tools_of (codex_request ("turn" )), (None ,None ))# a turn of A without tools ... 214self .assertIsNone (tools_of (codex_request ("compaction" ))[1 ])# ... is what its compaction follows 215 216def test_the_compact_prompt_in_a_message_is_not_a_compaction (self ): 217tools_of (codex_request ("turn" ,tools = TOOLS )) 218quoted = {"input" :HISTORY + [{"role" :"user" ,"content" :COMPACT_PROMPT }],"tools" : []} 219self .assertEqual (tools_of (quoted ), (None ,None ))# the compact prompt's words, without Codex saying so 220turn = codex_request ("turn" ,last = COMPACT_PROMPT ) 221turn ["input" ]= HISTORY + [{"role" :"user" ,"content" :"Explain this: " + COMPACT_PROMPT }] 222self .assertEqual (tools_of (turn ), (None ,None ))# Codex says it is a turn: as sent 223 224def test_a_thread_title_turn_does_not_replace_the_kept_tools (self ): 225tools_of (codex_request ("turn" ,tools = TOOLS )) 226kept = responses ._kept_prompt_tools 227title = codex_request ("turn" , ("019a-title" ,"019a-title" )) 228meta = json .loads (title ["client_metadata" ]["x-codex-turn-metadata" ]) 229meta ["thread_source" ]= "thread_title" 230title ["client_metadata" ]["x-codex-turn-metadata" ]= json .dumps (meta ) 231prompt_made (title ,None ) 232self .assertEqual (responses ._kept_prompt_tools ,kept ) 233self .assertEqual (tools_of (codex_request ("compaction" ))[1 ],request_tools ({"tools" :TOOLS })[0 ]) 234 235def test_a_custom_compact_prompt_is_a_compaction_when_codex_says_so (self ): 236first = tools_of (codex_request ("turn" ,tools = TOOLS ))[1 ] 237self .assertEqual (tools_of (codex_request ("compaction" ,last = "Summarize it my way." ))[1 ],first ) 238 239def test_a_compaction_that_sends_tools_keeps_them (self ): 240tools_of (codex_request ("turn" ,tools = TOOLS )) 241own ,shown = tools_of (codex_request ("compaction" ,tools = OTHER_TOOLS )) 242self .assertEqual (shown ,own ) 243 244def test_without_its_conversation_nothing_is_kept_or_used (self ): 245for meta in ({}, {"session_id" :"019a-a" ,"thread_id" :"019a-a" },# only the flat keys 246 {"x-codex-turn-metadata" :json .dumps ({"request_kind" :"turn" })}, 247 {"x-codex-turn-metadata" :json .dumps ({"request_kind" :"turn" ,"session_id" :"019a-a" })}, 248 {"x-codex-turn-metadata" :json .dumps ({"request_kind" :"turn" ,"thread_id" :"019a-a" })}): 249tools_of (codex_request ("turn" ,tools = TOOLS ,meta = meta )) 250self .assertEqual (responses ._kept_prompt_tools , (None ,None )) 251tools_of (codex_request ("turn" ,tools = TOOLS )) 252kept = responses ._kept_prompt_tools 253compaction = {"x-codex-turn-metadata" :json .dumps ({"request_kind" :"compaction" })} 254self .assertEqual (tools_of (codex_request ("compaction" ,meta = compaction )), (None ,None )) 255self .assertEqual (responses ._kept_prompt_tools ,kept ) 256 257def test_malformed_metadata_is_no_error_and_no_reuse (self ): 258first = tools_of (codex_request ("turn" ,tools = TOOLS ))[1 ] 259for meta in ("x" , ["x" ], {"x-codex-turn-metadata" :None }, {"x-codex-turn-metadata" :"{not json" }, 260 {"x-codex-turn-metadata" :"[]" }, {"x-codex-turn-metadata" :"\"compaction\"" }, 261 {"x-codex-turn-metadata" : {"request_kind" :"compaction" ,"session_id" :"019a-a" , 262"thread_id" :"019a-a" }},# an object: not what Codex sends 263 {"x-codex-turn-metadata" :json .dumps ({"request_kind" :"compaction" ,"session_id" :1 , 264"thread_id" :1 })}, 265 {"x-codex-turn-metadata" :json .dumps ({"request_kind" :"compaction" ,"session_id" :"" , 266"thread_id" :"" })}): 267self .assertEqual (tools_of (codex_request ("compaction" ,meta = meta )), (None ,None ),meta ) 268self .assertEqual (tools_of (codex_request ("compaction" ))[1 ],first )# A's entry was not touched 269odd = {"x-codex-turn-metadata" :json .dumps ({"request_kind" : ["compaction" ],"session_id" :"019a-a" , 270"thread_id" :"019a-a" })} 271self .assertEqual (tools_of (codex_request ("compaction" ,meta = odd )), (None ,None ))# not a compaction: as sent 272 273 274class NoLeakedSampler (unittest .TestCase ): 275"""Test isolation: a stopped server stops its hardware sampler. Every Service these tests started used to leave one 276running (21 after this file), polling NVML and psutil every second, which skewed serve/test_parallel's timings.""" 277 278def test_server_close_ends_the_sampler (self ): 279import time 280tok = ByteTokenizer () 281httpd = serve (Service (MockEngine (tok ,ANSWER ,max_context = 16384 ),tok ,TEMPLATE ),port = 0 ) 282sampler = getattr (getattr (httpd ,"svc" ,None ),"telemetry" ,None ) 283self .assertIsNotNone (sampler ,"the server did not initialize telemetry" ) 284thread = getattr (sampler ,"_thread" ,None ) 285self .assertIsNotNone (thread ,"the server did not start its hardware sampler thread" ) 286self .assertTrue (thread .is_alive (),"the hardware sampler thread died immediately" ) 287httpd .shutdown () 288httpd .server_close () 289thread .join (timeout = 5.0 ) 290self .assertFalse (thread .is_alive (),"a stopped server left its hardware sampler running" ) 291 292 293# ------------------------------------------------------------------------------------------------ over HTTP 294class Server (unittest .TestCase ): 295script = ANSWER 296 297def setUp (self ): 298self .tok = ByteTokenizer () 299self .engine = MockEngine (self .tok ,self .script ,max_context = 16384 ) 300self .svc = Service (self .engine ,self .tok ,TEMPLATE ) 301self .httpd = serve (self .svc ,port = 0 ) 302self .port = self .httpd .server_address [1 ] 303 304def tearDown (self ): 305self .httpd .shutdown () 306self .httpd .server_close () 307 308def post (self ,body ,path = "/v1/responses" ,headers = None ): 309"""(status, parsed body: a dict, or the list of SSE events of a stream).""" 310c = http .client .HTTPConnection ("127.0.0.1" ,self .port ,timeout = 30 ) 311try : 312with contextlib .redirect_stdout (io .StringIO ()): 313c .request ("POST" ,path ,body = json .dumps (body ).encode (), 314headers = {"Content-Type" :"application/json" ,** (headers or {})}) 315r = c .getresponse () 316raw = r .read ().decode () 317if r .getheader ("Content-Type" )== "text/event-stream" : 318events = [] 319for block in raw .split ("\n\n" ): 320lines = block .strip ().splitlines () 321if not lines or lines [0 ].startswith (":" ): 322continue 323name = lines [0 ][len ("event: " ):] 324data = json .loads (lines [1 ][len ("data: " ):]) 325self .assertEqual (name ,data ["type" ]) 326events .append (data ) 327return r .status ,events 328return r .status ,json .loads (raw ) 329finally : 330c .close () 331 332 333 334class OverHttp (Server ): 335def test_non_streaming_text_with_reasoning (self ): 336code ,r = self .post ({"model" :"m" ,"input" :"hi" ,"store" :False }) 337self .assertEqual (code ,200 ) 338self .assertEqual ((r ["object" ],r ["status" ],r ["error" ]), ("response" ,"completed" ,None )) 339rs ,msg = r ["output" ] 340self .assertEqual (rs ["type" ],"reasoning" ) 341self .assertEqual (rs ["content" ], [{"type" :"reasoning_text" ,"text" :"Read it.\n" }]) 342self .assertEqual (rs ["summary" ], []) 343self .assertNotIn ("encrypted_content" ,rs ) 344self .assertEqual (msg ["type" ],"message" ) 345self .assertEqual (msg ["content" ][0 ]["text" ],"The file says before." ) 346u = r ["usage" ] 347self .assertEqual (u ["output_tokens" ],len (self .tok .encode (ANSWER ))+ 1 )# + the end-of-turn token 348self .assertEqual (u ["output_tokens_details" ]["reasoning_tokens" ],len ("Read it.\n</think>" )) 349self .assertEqual (u ["total_tokens" ],u ["input_tokens" ]+ u ["output_tokens" ]) 350self .assertEqual (r ["store" ],False ) 351 352def test_stream_event_order (self ): 353code ,events = self .post ({"model" :"m" ,"input" :"hi" ,"stream" :True , 354"include" : ["reasoning.encrypted_content" ]}) 355self .assertEqual (code ,200 ) 356types = [e ["type" ]for e in events ] 357deltas_r = types .count ("response.reasoning_text.delta" ) 358deltas_t = types .count ("response.output_text.delta" ) 359self .assertGreater (deltas_r ,0 ) 360self .assertGreater (deltas_t ,0 ) 361self .assertEqual (types , ["response.created" ,"response.in_progress" , 362"response.output_item.added" ,* ["response.reasoning_text.delta" ]* deltas_r , 363"response.reasoning_text.done" ,"response.output_item.done" , 364"response.output_item.added" ,"response.content_part.added" , 365* ["response.output_text.delta" ]* deltas_t , 366"response.output_text.done" ,"response.content_part.done" , 367"response.output_item.done" ,"response.completed" ]) 368self .assertEqual ([e ["sequence_number" ]for e in events ],list (range (len (events )))) 369final = events [- 1 ]["response" ] 370self .assertEqual (final ["status" ],"completed" ) 371rs ,msg = final ["output" ] 372self .assertEqual ([e ["item" ]["id" ]for e in events if e ["type" ]== "response.output_item.done" ], 373 [rs ["id" ],msg ["id" ]]) 374self .assertEqual ("" .join (e ["delta" ]for e in events if e ["type" ]== "response.output_text.delta" ), 375msg ["content" ][0 ]["text" ]) 376self .assertTrue (rs ["encrypted_content" ].startswith (ENCRYPTED_PREFIX )) 377# the encrypted_content alone brings the thinking back into the prompt 378replay = input_messages ({"input" : [{"role" :"user" ,"content" :"hi" }, 379 {"type" :"reasoning" ,"summary" : [],"encrypted_content" : 380rs ["encrypted_content" ]},msg ]}) 381self .assertEqual (replay [1 ]["reasoning_content" ],"Read it.\n" ) 382 383def test_max_output_tokens_ends_incomplete (self ): 384code ,r = self .post ({"model" :"m" ,"input" :"hi" ,"max_output_tokens" :5 }) 385self .assertEqual (code ,200 ) 386self .assertEqual (r ["status" ],"incomplete" ) 387self .assertEqual (r ["incomplete_details" ], {"reason" :"max_output_tokens" }) 388self .assertEqual (r ["output" ][0 ]["status" ],"incomplete" ) 389code ,events = self .post ({"model" :"m" ,"input" :"hi" ,"max_output_tokens" :5 ,"stream" :True }) 390self .assertEqual (events [- 1 ]["type" ],"response.incomplete" ) 391 392def test_max_output_tokens_zero_and_minus_one_mean_no_cap (self ): 393# #4036: the documented "no cap" values; the answer is complete, not cut at the cap 394for n in (0 ,- 1 ): 395code ,r = self .post ({"model" :"m" ,"input" :"hi" ,"max_output_tokens" :n }) 396self .assertEqual ((code ,r ["status" ]), (200 ,"completed" ), (n ,r )) 397self .assertIsNone (r ["incomplete_details" ]) 398code ,events = self .post ({"model" :"m" ,"input" :"hi" ,"max_output_tokens" :n ,"stream" :True }) 399self .assertEqual ((code ,events [- 1 ]["type" ]), (200 ,"response.completed" ),n ) 400 401def test_max_output_tokens_bad_values_are_400 (self ): 402for n in (- 2 ,- 100 ,1.5 ,True ,"5" ): 403code ,r = self .post ({"model" :"m" ,"input" :"hi" ,"max_output_tokens" :n }) 404self .assertEqual (code ,400 , (n ,r )) 405self .assertEqual (r ["error" ]["param" ],"max_output_tokens" ,n ) 406 407def test_effort_none_does_not_think (self ): 408self .engine .scripts = [self .tok .encode ("Hello.<|im_end|>" ,parse_special = True )] 409self .engine .script = self .engine .scripts [0 ] 410code ,r = self .post ({"model" :"m" ,"input" :"hi" ,"reasoning" : {"effort" :"none" }}) 411self .assertEqual ([o ["type" ]for o in r ["output" ]], ["message" ]) 412self .assertIn ("<think>\n\n</think>" ,self .tok .decode (self .engine .last_prompt )) 413 414def test_errors_use_the_responses_format (self ): 415for body ,param in (({"model" :"m" },"input" ), ({"model" :"m" ,"input" :"x" ,"previous_response_id" :"r" }, 416"previous_response_id" ), 417 ({"model" :"m" ,"input" :"x" ,"reasoning" : {"effort" :"huge" }},"reasoning.effort" )): 418code ,r = self .post (body ) 419self .assertEqual (code ,400 ) 420self .assertEqual (set (r ["error" ]), {"message" ,"type" ,"param" ,"code" }) 421self .assertEqual (r ["error" ]["param" ],param ) 422code ,r = self .post ({},path = "/v1/responses/resp_123/cancel" ) 423self .assertEqual (code ,404 ) 424self .assertEqual (r ["error" ]["code" ],"not_found" ) 425c = http .client .HTTPConnection ("127.0.0.1" ,self .port ,timeout = 30 ) 426c .request ("POST" ,"/v1/responses" ,body = b"{not json" ,headers = {"Content-Type" :"application/json" }) 427r = c .getresponse () 428err = json .loads (r .read ())["error" ] 429c .close () 430self .assertEqual ((r .status ,err ["type" ],err ["param" ]), (400 ,"invalid_request_error" ,None )) 431 432def test_too_long_for_the_context (self ): 433code ,r = self .post ({"model" :"m" ,"input" :"x" * 20000 }) 434self .assertEqual (code ,400 ) 435self .assertEqual (r ["error" ]["code" ],"context_length_exceeded" ) 436 437def test_api_key_and_foreign_pages (self ): 438self .svc .api_key = "s3cret" 439self .assertEqual (self .post ({"model" :"m" ,"input" :"hi" })[0 ],401 ) 440self .assertEqual (self .post ({"model" :"m" ,"input" :"hi" },headers = {"Authorization" :"Bearer s3cret" })[0 ],200 ) 441self .svc .api_key = None 442code ,r = self .post ({"model" :"m" ,"input" :"hi" },headers = {"Origin" :"https://evil.example.com" }) 443self .assertEqual (code ,403 ) 444 445def test_a_foreign_page_cannot_name_a_file_as_an_image (self ): 446"""#553: the chat routes refuse a file image from another origin; so does /v1/responses.""" 447def body (src ): 448return {"model" :"m" ,"input" : [{"role" :"user" ,"content" : [ 449 {"type" :"input_text" ,"text" :"what is it?" }, {"type" :"input_image" ,"image_url" :src }]}]} 450self .svc .cors_origins = ["*" ]# a page cors_origins lets in may send JSON, not name a file 451for src in (r"\\host\share\x.png" ,"/etc/passwd" ,"file:///C:/x.png" ): 452with self .subTest (src = src ): 453code ,r = self .post (body (src ),headers = {"Origin" :"https://evil.example.com" }) 454self .assertEqual (code ,400 ,r ) 455self .assertIn ("another origin" ,r ["error" ]["message" ]) 456# data: and http(s) are the page's own to send: not refused by this check (no vision here, so a 400 of another kind) 457for src in ("data:image/png;base64,iVBORw0KGgo=" ,"https://example.com/x.png" ): 458code ,r = self .post (body (src ),headers = {"Origin" :"https://evil.example.com" }) 459self .assertNotIn ("another origin" ,json .dumps (r )) 460 461def test_json_schema_text_format (self ): 462self .engine .scripts = [self .tok .encode ("</think>\n\n{\"n\": 3}<|im_end|>" ,parse_special = True )] 463self .engine .script = self .engine .scripts [0 ] 464fmt = {"type" :"json_schema" ,"name" :"num" ,"strict" :True , 465"schema" : {"type" :"object" ,"properties" : {"n" : {"type" :"integer" }},"required" : ["n" ]}} 466code ,r = self .post ({"model" :"m" ,"input" :"a number" ,"text" : {"format" :fmt }}) 467self .assertEqual (code ,200 ,r ) 468self .assertEqual (r ["output" ][- 1 ]["content" ][0 ]["text" ],"{\"n\":3}" ) 469code ,events = self .post ({"model" :"m" ,"input" :"a number" ,"text" : {"format" :fmt },"stream" :True }) 470self .assertEqual ([e ["delta" ]for e in events if e ["type" ]== "response.output_text.delta" ], ["{\"n\":3}" ]) 471self .assertEqual (events [- 1 ]["type" ],"response.completed" ) 472# an answer that fails the schema - only jsonschema can tell: it is optional (serve/structured.py), and 473# without it a json_schema answer is checked to be one JSON object, which {"n": 3} is 474try : 475import jsonschema # noqa: F401 476except ImportError : 477return 478bad = {** fmt ,"schema" : {** fmt ["schema" ],"properties" : {"n" : {"type" :"string" }}}} 479code ,r = self .post ({"model" :"m" ,"input" :"a number" ,"text" : {"format" :bad }}) 480self .assertEqual ((code ,r ["error" ]["code" ]), (502 ,"structured_output_failed" )) 481code ,events = self .post ({"model" :"m" ,"input" :"a number" ,"text" : {"format" :bad },"stream" :True }) 482self .assertEqual (events [- 1 ]["type" ],"response.failed" ) 483self .assertEqual (events [- 1 ]["response" ]["error" ]["code" ],"structured_output_failed" ) 484 485def test_monitor_and_status (self ): 486self .svc .api_monitor = True 487self .post ({"model" :"m" ,"input" :"hi" ,"stream" :True }) 488rec = self .svc .request_records ()[0 ] 489self .assertEqual (rec ["path" ],"/v1/responses" ) 490full = self .svc .request_records (rec ["id" ]) 491self .assertEqual (full ["output" ],"The file says before." ) 492self .assertEqual (full ["reasoning" ],"Read it.\n" ) 493self .assertIn ("/v1/responses" ,self .svc .v1_status ()["dialects" ]) 494 495 496class ToolRoundTrip (Server ): 497script = [CALL ,ANSWER ] 498 499def test_function_call_round_trip (self ): 500user = {"type" :"message" ,"role" :"user" ,"content" : [{"type" :"input_text" ,"text" :"what is in a.txt?" }]} 501code ,events = self .post ({"model" :"m" ,"instructions" :"You are a coding agent." ,"input" : [user ], 502"tools" :TOOLS ,"store" :False ,"stream" :True , 503"include" : ["reasoning.encrypted_content" ],"reasoning" : {"summary" :"auto" }, 504"parallel_tool_calls" :True ,"tool_choice" :"auto" }) 505self .assertEqual (code ,200 ) 506first_prompt = self .tok .decode (self .engine .last_prompt ) 507types = [e ["type" ]for e in events ] 508n_args = types .count ("response.function_call_arguments.delta" ) 509self .assertGreater (n_args ,0 ) 510call_part = types [types .index ("response.output_text.done" )+ 2 :] 511self .assertEqual (call_part , ["response.output_item.done" ,"response.output_item.added" , 512* ["response.function_call_arguments.delta" ]* n_args , 513"response.function_call_arguments.done" ,"response.output_item.done" , 514"response.completed" ]) 515output = events [- 1 ]["response" ]["output" ] 516self .assertEqual ([o ["type" ]for o in output ], ["reasoning" ,"message" ,"function_call" ]) 517fc = output [2 ] 518self .assertEqual ((fc ["name" ],json .loads (fc ["arguments" ]),fc ["status" ]), 519 ("exec_command" , {"cmd" :"cat a.txt" },"completed" )) 520self .assertTrue (fc ["call_id" ]) 521added = next (e for e in events if e ["type" ]== "response.output_item.added" 522and e ["item" ]["type" ]== "function_call" ) 523self .assertEqual ((added ["item" ]["call_id" ],added ["item" ]["arguments" ]), (fc ["call_id" ],"" )) 524# Codex sends everything back, plus the result: the prompt continues exactly where the model stopped 525code ,r = self .post ({"model" :"m" ,"instructions" :"You are a coding agent." ,"tools" :TOOLS ,"store" :False , 526"input" : [user ,* output , {"type" :"function_call_output" ,"call_id" :fc ["call_id" ], 527"output" :"before" }]}) 528self .assertEqual (code ,200 ,r ) 529second_prompt = self .tok .decode (self .engine .last_prompt ) 530self .assertTrue (second_prompt .startswith (first_prompt + CALL + "<|im_end|>" ),second_prompt [- 600 :]) 531self .assertIn ("<tool_response>\nbefore\n</tool_response>" ,second_prompt ) 532self .assertEqual (r ["output" ][- 1 ]["content" ][0 ]["text" ],"The file says before." ) 533 534def test_quoted_incomplete_wrapper_is_not_a_completed_call (self ): 535text = "Format: " + CALL [CALL .index ("<tool_call>" ):].removesuffix ("</tool_call>" )+ "and then I explain it." 536self .engine .scripts = [self .tok .encode ("</think>\n\n" + text + "<|im_end|>" ,parse_special = True )] 537self .engine .script = self .engine .scripts [0 ] 538for stream in (False ,True ): 539code ,result = self .post ({"model" :"m" ,"input" :"explain the format" ,"tools" :TOOLS ,"stream" :stream }) 540self .assertEqual (code ,200 ,result ) 541final = result [- 1 ]["response" ]if stream else result 542calls = [item for item in final ["output" ]if item ["type" ]== "function_call" ] 543self .assertFalse (any (item ["status" ]== "completed" for item in calls )) 544for call in calls : 545with self .assertRaises (ValueError ): 546json .loads (call ["arguments" ]) 547self .assertEqual ("" .join (item ["content" ][0 ]["text" ]for item in final ["output" ] 548if item ["type" ]== "message" ),text ) 549 550def test_namespace_call_written_with_double_underscore (self ): 551# Qwen writes Codex's MCP tools in their flat `mcp__server__tool` form; Codex only 552# runs the call when it comes back with its namespace. 553self .engine .scripts = [self .tok .encode ( 554"</think>\n\n<tool_call>\n<function=mcp__websearch__web_search>\n<parameter=query>\nstrata\n" 555"</parameter>\n</function>\n</tool_call><|im_end|>" ,parse_special = True )] 556self .engine .script = self .engine .scripts [0 ] 557tools = [{"type" :"namespace" ,"name" :"mcp__websearch" ,"description" :"Search." ,"tools" : [ 558 {"type" :"function" ,"name" :"web_search" , 559"parameters" : {"type" :"object" ,"properties" : {"query" : {"type" :"string" }}}}]}] 560code ,r = self .post ({"model" :"m" ,"input" :"go" ,"tools" :tools }) 561self .assertEqual (code ,200 ,r ) 562call ,= r ["output" ] 563self .assertEqual ((call ["namespace" ],call ["name" ],json .loads (call ["arguments" ])), 564 ("mcp__websearch" ,"web_search" , {"query" :"strata" })) 565 566# Two canonical names share this alias. It must not invoke the first namespace. 567self .engine .scripts = [self .tok .encode ( 568"</think>\n\n<tool_call>\n<function=a__b__c>\n</function>\n</tool_call><|im_end|>" , 569parse_special = True )] 570self .engine .script = self .engine .scripts [0 ] 571tools = [{"type" :"namespace" ,"name" :"a" ,"tools" : [{"type" :"function" ,"name" :"b__c" }]}, 572 {"type" :"namespace" ,"name" :"a__b" ,"tools" : [{"type" :"function" ,"name" :"c" }]}] 573for stream in (False ,True ): 574code ,r = self .post ({"model" :"m" ,"input" :"go" ,"tools" :tools ,"stream" :stream }) 575self .assertEqual (code ,200 ,r ) 576output = r [- 1 ]["response" ]["output" ]if stream else r ["output" ] 577# not an alias of either: with tools declared (the 0.2.2 rule, #3075) a call for an undeclared name stays text 578self .assertFalse ([item for item in output if item .get ("type" )== "function_call" ],output ) 579self .assertIn ("a__b__c" ,json .dumps (output )) 580 581# A declared exact name wins over alias spellings and keeps its string schema. 582tools .append ({"type" :"function" ,"name" :"a__b__c" ,"parameters" : { 583"type" :"object" ,"properties" : {"path" : {"type" :"string" }}}}) 584self .engine .scripts = [self .tok .encode ( 585"</think>\n\n<tool_call>\n<function=a__b__c>\n<parameter=path>\n123\n</parameter>\n" 586"</function>\n</tool_call><|im_end|>" ,parse_special = True )] 587self .engine .script = self .engine .scripts [0 ] 588for stream in (False ,True ): 589code ,r = self .post ({"model" :"m" ,"input" :"go" ,"tools" :tools ,"stream" :stream }) 590self .assertEqual (code ,200 ,r ) 591output = r [- 1 ]["response" ]["output" ]if stream else r ["output" ] 592call ,= output 593self .assertNotIn ("namespace" ,call ) 594self .assertEqual ((call ["name" ],json .loads (call ["arguments" ])), ("a__b__c" , {"path" :"123" })) 595 596def test_namespace_and_custom_calls_come_back_under_their_own_names (self ): 597self .engine .scripts = [self .tok .encode ( 598"</think>\n\n<tool_call>\n<function=multi_agent_v1.spawn_agent>\n<parameter=message>\nhi\n</parameter>\n" 599"</function>\n</tool_call>\n<tool_call>\n<function=apply_patch>\n<parameter=input>\n*** Begin Patch\n" 600"</parameter>\n</function>\n</tool_call><|im_end|>" ,parse_special = True )] 601self .engine .script = self .engine .scripts [0 ] 602tools = [{"type" :"namespace" ,"name" :"multi_agent_v1" ,"description" :"Agents." ,"tools" : [ 603 {"type" :"function" ,"name" :"spawn_agent" ,"strict" :False , 604"parameters" : {"type" :"object" ,"properties" : {"message" : {"type" :"string" }}}}]}, 605 {"type" :"custom" ,"name" :"apply_patch" ,"description" :"Edit files." }] 606code ,r = self .post ({"model" :"m" ,"input" :"go" ,"tools" :tools }) 607self .assertEqual (code ,200 ,r ) 608ns ,custom = r ["output" ] 609self .assertEqual ((ns ["type" ],ns ["namespace" ],ns ["name" ],json .loads (ns ["arguments" ])), 610 ("function_call" ,"multi_agent_v1" ,"spawn_agent" , {"message" :"hi" })) 611self .assertEqual ((custom ["type" ],custom ["name" ],custom ["input" ]), 612 ("custom_tool_call" ,"apply_patch" ,"*** Begin Patch" )) 613msgs = input_messages ({"input" : [{"role" :"user" ,"content" :"go" },ns ,custom , 614 {"type" :"function_call_output" ,"call_id" :ns ["call_id" ],"output" :"1" }, 615 {"type" :"custom_tool_call_output" ,"call_id" :custom ["call_id" ], 616"output" :"2" }]}) 617self .assertEqual ([c ["function" ]["name" ]for c in msgs [1 ]["tool_calls" ]], 618 ["multi_agent_v1.spawn_agent" ,"apply_patch" ]) 619 620 621class JsonFormatWithTools (Server ): 622"""#782: Codex's review request carries an `additional_tools` item, tools, and `text.format` json_schema together. 623A tool call passes through; the schema is checked on the answer that ends in text.""" 624FMT = {"type" :"json_schema" ,"name" :"guardian_review" ,"strict" :True , 625"schema" : {"type" :"object" ,"properties" : {"outcome" : {"type" :"string" },"rationale" : {"type" :"string" }}, 626"required" : ["outcome" ,"rationale" ],"additionalProperties" :False }} 627 628def request (self ,** extra ): 629user = {"type" :"message" ,"role" :"user" ,"content" : [{"type" :"input_text" ,"text" :"review this call" }]} 630more = {"type" :"additional_tools" ,"role" :"developer" ,"tools" : [ 631 {"type" :"function" ,"name" :"later_tool" ,"parameters" : {"type" :"object" }}]} 632return {"model" :"m" ,"instructions" :"You are a reviewer." ,"input" : [more ,user ],"tools" :TOOLS , 633"tool_choice" :"auto" ,"parallel_tool_calls" :False ,"store" :False , 634"text" : {"format" :self .FMT },** extra } 635 636def script_with (self ,text ): 637self .engine .scripts = [self .tok .encode (text ,parse_special = True )] 638self .engine .script = self .engine .scripts [0 ] 639 640def test_a_tool_call_passes_through (self ): 641self .script_with (CALL + "<|im_end|>" ) 642for stream in (False ,True ): 643code ,r = self .post (self .request (stream = stream )) 644self .assertEqual (code ,200 ,r ) 645final = r if not stream else r [- 1 ]["response" ] 646self .assertEqual (final ["status" ],"completed" ) 647self .assertEqual ([o ["type" ]for o in final ["output" ]][- 2 :], ["message" ,"function_call" ]) 648call ,= [o for o in final ["output" ]if o ["type" ]== "function_call" ] 649self .assertEqual ((call ["type" ],call ["name" ],json .loads (call ["arguments" ])), 650 ("function_call" ,"exec_command" , {"cmd" :"cat a.txt" })) 651# the model is told the schema is for its final answer, not for a turn that calls a tool 652self .assertIn ("applies only to your final answer" ,self .tok .decode (self .engine .last_prompt )) 653 654def test_the_final_text_answer_is_the_schema_object (self ): 655self .script_with ('</think>\n\n{"outcome": "allow", "rationale": "read only"}<|im_end|>' ) 656code ,r = self .post (self .request ()) 657self .assertEqual (code ,200 ,r ) 658self .assertEqual (json .loads (r ["output" ][- 1 ]["content" ][0 ]["text" ]), 659 {"outcome" :"allow" ,"rationale" :"read only" }) 660code ,events = self .post (self .request (stream = True )) 661self .assertEqual (events [- 1 ]["type" ],"response.completed" ) 662self .assertEqual (len ([e for e in events if e ["type" ]== "response.output_text.delta" ]),1 ) 663 664def test_a_text_answer_that_breaks_the_schema_fails_as_without_tools (self ): 665try : 666import jsonschema # noqa: F401 667except ImportError : 668self .skipTest ("the schema check needs jsonschema" ) 669self .script_with ('</think>\n\n{"outcome": 3}<|im_end|>' ) 670code ,r = self .post (self .request ()) 671self .assertEqual ((code ,r ["error" ]["code" ]), (502 ,"structured_output_failed" )) 672 673 674class ThreadTitle (Server ): 675def test_a_thread_title_is_answered_without_the_engine (self ): 676self .svc .codex_thread_titles = True # opt-in: "codex_thread_titles": true in the config 677user = {"type" :"message" ,"role" :"user" ,"content" : [{"type" :"input_text" ,"text" :"what is in a.txt?" }]} 678code ,r = self .post ({"model" :"m" ,"instructions" :"You are a coding agent." ,"input" : [user ],"tools" :TOOLS }) 679self .assertEqual (code ,200 ,r ) 680seen = list (self .engine .last_prompt ) 681self .assertTrue (seen ) 682meta = {"session_id" :"019a-title" ,"thread_id" :"019a-title" ,"request_kind" :"turn" , 683"thread_source" :"thread_title" } 684code ,r = self .post ({ 685"model" :"m" ,"instructions" :"You are Codex" ,"tools" : [], 686"client_metadata" : {"x-codex-turn-metadata" :json .dumps (meta )}, 687"input" : [{"type" :"message" ,"role" :"user" ,"content" : [ 688 {"type" :"input_text" ,"text" :"Generate a concise title.\n\nUser prompt:\n只回四個字然後停:傾印測試" }]}]}) 689self .assertEqual (code ,200 ,r ) 690self .assertEqual (self .engine .last_prompt ,seen ) 691self .assertEqual (json .loads (r ["output" ][0 ]["content" ][0 ]["text" ]), {"title" :"只回四個字然後停:傾印測試" }) 692long = {"model" :"m" ,"instructions" :"You are Codex" ,"tools" : [], 693"client_metadata" : {"x-codex-turn-metadata" :json .dumps (meta )}, 694"input" :"User prompt:\n" + ("甲" * 40 )+ "。" } 695self .assertEqual (json .loads (collect (thread_title_events (long ,"m" ))["output" ][0 ]["content" ][0 ]["text" ]), 696 {"title" :"甲" * 36 }) 697 698def test_off_by_default_the_engine_answers (self ): 699meta = {"thread_source" :"thread_title" } 700code ,r = self .post ({"model" :"m" ,"instructions" :"You are Codex" ,"tools" : [], 701"client_metadata" : {"x-codex-turn-metadata" :json .dumps (meta )}, 702"input" :"User prompt:" + chr (10 )+ "hello" }) 703self .assertEqual (code ,200 ,r ) 704self .assertTrue (self .engine .last_prompt )# it ran on the engine 705self .assertNotIn ('"title"' ,json .dumps (r ["output" ])) 706 707 708class CodexCompactionOverHttp (Server ): 709# the compaction answer is tool calls the conversation's tools would make a namespace call and a custom call 710script = [CALL ,"</think>\n\n<tool_call>\n<function=multi_agent_v1.spawn_agent>\n<parameter=message>\nhi\n" 711"</parameter>\n</function>\n</tool_call>\n<tool_call>\n<function=apply_patch>\n<parameter=input>\n" 712"*** Begin Patch\n</parameter>\n</function>\n</tool_call>" ] 713tools = TOOLS + [{"type" :"namespace" ,"name" :"multi_agent_v1" ,"description" :"Agents." ,"tools" : [ 714 {"type" :"function" ,"name" :"spawn_agent" ,"parameters" : {"type" :"object" ,"properties" : { 715"message" : {"type" :"string" }}}}]}, {"type" :"custom" ,"name" :"apply_patch" ,"description" :"Edit files." }] 716 717def setUp (self ): 718super ().setUp () 719responses ._kept_prompt_tools = (None ,None ) 720self .svc .codex_compaction_cache = True # opt-in (#924) 721self .parser_tools = [] 722run = self .svc .run 723 724def recorded (ids ,thinking ,tools ,* rest ): 725self .parser_tools .append (tools ) 726return run (ids ,thinking ,tools ,* rest ) 727self .svc .run = recorded 728 729def compaction (self ,meta ,output = "before" ,between = None ,** extra ): 730"""Codex's turn, (`between`,) then its compaction request: (the compaction prompt, its status and response).""" 731self .engine .turns ,self .engine .script = 0 ,self .engine .scripts [0 ] 732user = {"type" :"message" ,"role" :"user" ,"content" : [{"type" :"input_text" ,"text" :"what is in a.txt?" }]} 733turn = {"model" :"m" ,"instructions" :"You are a coding agent." ,"input" : [user ],"tools" :self .tools , 734"include" : ["reasoning.encrypted_content" ],"client_metadata" :codex_meta ("turn" )} 735code ,r = self .post (turn ) 736self .assertEqual (code ,200 ,r ) 737self .first_prompt = self .tok .decode (self .engine .last_prompt ) 738call = r ["output" ][- 1 ] 739if between : 740between () 741code ,r = self .post ({** turn ,"tools" : [],"parallel_tool_calls" :False ,"client_metadata" :meta ,"input" : [ 742user ,* r ["output" ], {"type" :"function_call_output" ,"call_id" :call ["call_id" ],"output" :output }, 743 {"type" :"message" ,"role" :"user" ,"content" : [{"type" :"input_text" ,"text" :COMPACT_PROMPT }]}], 744** extra }) 745return self .tok .decode (self .engine .last_prompt ),code ,r 746 747def test_the_kept_tools_shape_only_the_prompt (self ): 748prompt ,code ,r = self .compaction (codex_meta ("compaction" )) 749self .assertEqual (code ,200 ,r ) 750self .assertTrue (prompt .startswith (self .first_prompt + CALL + "<|im_end|>" ))# the cached conversation 751self .assertIn ("multi_agent_v1.spawn_agent" ,prompt [:prompt .index ("<|im_end|>" )]) 752self .assertEqual (self .parser_tools [- 1 ],None )# the parser gets the request's tools: none 753self .assertEqual (r ["tools" ], []) 754# the calls come back as for any request without tools: no namespace, no custom tool 755outputs = [(o ["type" ],o ["name" ],o .get ("namespace" ))for o in r ["output" ]] 756self .assertEqual (outputs , [("function_call" ,"multi_agent_v1.spawn_agent" ,None ), 757 ("function_call" ,"apply_patch" ,None )]) 758# the same request without Codex's metadata (upstream's behaviour): the same answer, but its prompt starts 759# differently, so the engine reads it from the start 760plain ,code ,r2 = self .compaction ({}) 761self .assertEqual (code ,200 ,r2 ) 762self .assertFalse (plain .startswith (self .first_prompt )) 763self .assertNotIn ("multi_agent_v1.spawn_agent" ,plain [:plain .index ("<|im_end|>" )]) 764self .assertEqual (self .parser_tools [- 1 ],None ) 765self .assertEqual ([(o ["type" ],o ["name" ],o .get ("namespace" ))for o in r2 ["output" ]],outputs ) 766 767def test_a_compaction_too_long_with_the_kept_tools_is_rendered_as_sent (self ): 768long = "before\n" * 300 # a long tool output: the turn fits, its compaction barely 769plain ,code ,r = self .compaction ({},long ,max_output_tokens = 64 ) 770self .assertEqual (code ,200 ,r ) 771fits = len (self .engine .last_prompt )+ 64 + 8 # the request as sent, its output, CTX_SLACK 772shown ,code ,r = self .compaction (codex_meta ("compaction" ),long ,max_output_tokens = 64 ) 773self .assertGreater (len (self .engine .last_prompt )+ 64 + 8 ,fits )# with the kept tools it would not fit 774self .engine .max_context = fits 775again ,code ,r = self .compaction (codex_meta ("compaction" ),long ,max_output_tokens = 64 ) 776self .assertEqual (code ,200 ,r )# as without the kept tools, not a context error 777self .assertEqual (again ,plain ) 778self .assertEqual (self .parser_tools [- 1 ],None ) 779 780 781def test_a_request_that_fails_leaves_the_kept_tools_as_they_were (self ): 782before ,code ,r = self .compaction (codex_meta ("compaction" )) 783self .assertEqual (code ,200 ,r ) 784 785def fails ():# B's turn is too long: its prompt never reaches the engine 786code ,r = self .post ({"model" :"m" ,"input" :"x" * 20000 ,"tools" :TOOLS , 787"client_metadata" :codex_meta ("turn" ,B )}) 788self .assertEqual ((code ,r ["error" ]["code" ]), (400 ,"context_length_exceeded" )) 789again ,code ,r = self .compaction (codex_meta ("compaction" ),between = fails ) 790self .assertEqual (code ,200 ,r ) 791self .assertEqual (again ,before )# so A's compaction still starts as A's turn 792 793 794if __name__ == "__main__" : 795unittest .main ()