forked from openai/openai-agents-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_codex_tool.py
More file actions
2048 lines (1723 loc) · 66.4 KB
/
test_codex_tool.py
File metadata and controls
2048 lines (1723 loc) · 66.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import copy
import dataclasses
import importlib
import inspect
import json
from dataclasses import dataclass, fields
from types import MappingProxyType, SimpleNamespace
from typing import Any, cast
import pytest
from openai.types.responses import ResponseFunctionToolCall
from pydantic import BaseModel, ConfigDict
from agents import Agent, function_tool
from agents.exceptions import ModelBehaviorError, UserError
from agents.extensions.experimental.codex import (
Codex,
CodexToolOptions,
CodexToolResult,
CodexToolStreamEvent,
Usage,
codex_tool,
)
from agents.extensions.experimental.codex.codex_tool import CodexToolInputItem
from agents.lifecycle import RunHooks
from agents.run_config import RunConfig
from agents.run_context import RunContextWrapper
from agents.run_internal.agent_bindings import bind_public_agent
from agents.run_internal.run_steps import ToolRunFunction
from agents.run_internal.tool_execution import execute_function_tool_calls
from agents.tool_context import ToolContext
from agents.tracing import function_span, trace
from tests.test_responses import get_function_tool_call
from tests.testing_processor import SPAN_PROCESSOR_TESTING
codex_tool_module = importlib.import_module("agents.extensions.experimental.codex.codex_tool")
class CodexMockState:
def __init__(self) -> None:
self.events: list[dict[str, Any]] = []
self.thread_id: str | None = "thread-1"
self.last_turn_options: Any = None
self.start_calls = 0
self.resume_calls = 0
self.last_resumed_thread_id: str | None = None
self.options: Any = None
class FakeThread:
def __init__(self, state: CodexMockState) -> None:
self._state = state
self.id: str | None = None
async def run_streamed(self, _input: Any, turn_options: Any = None) -> Any:
self._state.last_turn_options = turn_options
self.id = self._state.thread_id
async def event_stream() -> Any:
for event in self._state.events:
if event.get("type") == "raise_cancelled":
raise asyncio.CancelledError(event.get("message", "codex-cancelled"))
if event.get("type") == "wait_for_cancel":
started_event = cast(asyncio.Event | None, event.get("started_event"))
if started_event is not None:
started_event.set()
await asyncio.Future()
yield event
return SimpleNamespace(events=event_stream())
class FakeCodex:
def __init__(self, state: CodexMockState, options: Any = None) -> None:
self._state = state
self._state.options = options
def start_thread(self, _options: Any = None) -> FakeThread:
self._state.start_calls += 1
return FakeThread(self._state)
def resume_thread(self, _thread_id: str, _options: Any = None) -> FakeThread:
self._state.resume_calls += 1
self._state.last_resumed_thread_id = _thread_id
return FakeThread(self._state)
def test_codex_tool_kw_matches_codex_tool_options() -> None:
signature = inspect.signature(codex_tool)
kw_only = [
param.name
for param in signature.parameters.values()
if param.kind == inspect.Parameter.KEYWORD_ONLY
]
option_fields = [field.name for field in fields(CodexToolOptions)]
assert kw_only == option_fields
@pytest.mark.asyncio
async def test_codex_tool_streams_events_and_updates_usage() -> None:
state = CodexMockState()
state.events = [
{"type": "thread.started", "thread_id": "thread-1"},
{"type": "turn.started"},
{
"type": "item.started",
"item": {"id": "reason-1", "type": "reasoning", "text": "Initial reasoning"},
},
{
"type": "item.updated",
"item": {"id": "reason-1", "type": "reasoning", "text": "Refined reasoning"},
},
{
"type": "item.completed",
"item": {"id": "reason-1", "type": "reasoning", "text": "Final reasoning"},
},
{
"type": "item.started",
"item": {
"id": "cmd-1",
"type": "command_execution",
"command": "pytest",
"aggregated_output": "",
"status": "in_progress",
},
},
{
"type": "item.updated",
"item": {
"id": "cmd-1",
"type": "command_execution",
"command": "pytest",
"aggregated_output": "Running tests",
"status": "in_progress",
},
},
{
"type": "item.completed",
"item": {
"id": "cmd-1",
"type": "command_execution",
"command": "pytest",
"aggregated_output": "All good",
"exit_code": 0,
"status": "completed",
},
},
{
"type": "item.started",
"item": {
"id": "mcp-1",
"type": "mcp_tool_call",
"server": "gitmcp",
"tool": "search_codex_code",
"arguments": {"query": "foo"},
"status": "in_progress",
},
},
{
"type": "item.updated",
"item": {
"id": "mcp-1",
"type": "mcp_tool_call",
"server": "gitmcp",
"tool": "search_codex_code",
"arguments": {"query": "foo"},
"status": "in_progress",
},
},
{
"type": "item.completed",
"item": {
"id": "mcp-1",
"type": "mcp_tool_call",
"server": "gitmcp",
"tool": "search_codex_code",
"arguments": {"query": "foo"},
"status": "completed",
"result": {"content": [], "structured_content": None},
},
},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex finished."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 10, "cached_input_tokens": 1, "output_tokens": 5},
},
]
tool = codex_tool(CodexToolOptions(codex=cast(Codex, FakeCodex(state))))
input_json = '{"inputs": [{"type": "text", "text": "Diagnose failure", "path": ""}]}'
context = ToolContext(
context=None,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
with trace("codex-test"):
with function_span(tool.name):
result = await tool.on_invoke_tool(context, input_json)
assert isinstance(result, CodexToolResult)
assert result.thread_id == "thread-1"
assert result.response == "Codex finished."
assert result.usage == Usage(
input_tokens=10,
cached_input_tokens=1,
output_tokens=5,
)
assert context.usage.total_tokens == 15
assert context.usage.requests == 1
spans = SPAN_PROCESSOR_TESTING.get_ordered_spans()
function_span_obj = next(
span
for span in spans
if span.span_data.type == "function" and span.span_data.name == tool.name
)
custom_spans = [span for span in spans if span.span_data.type == "custom"]
assert len(custom_spans) == 1
for span in custom_spans:
assert span.parent_id == function_span_obj.span_id
command_span = next(
span for span in custom_spans if span.span_data.name == "Codex command execution"
)
assert command_span.span_data.data["command"] == "pytest"
assert command_span.span_data.data["status"] == "completed"
assert command_span.span_data.data["output"] == "All good"
assert command_span.span_data.data["exit_code"] == 0
@pytest.mark.asyncio
async def test_codex_tool_keeps_command_output_when_completed_missing_output() -> None:
state = CodexMockState()
state.events = [
{"type": "thread.started", "thread_id": "thread-1"},
{
"type": "item.started",
"item": {
"id": "cmd-1",
"type": "command_execution",
"command": "ls",
"aggregated_output": "",
"status": "in_progress",
},
},
{
"type": "item.updated",
"item": {
"id": "cmd-1",
"type": "command_execution",
"command": "ls",
"aggregated_output": "first output",
"status": "in_progress",
},
},
{
"type": "item.completed",
"item": {
"id": "cmd-1",
"type": "command_execution",
"command": "ls",
"exit_code": 0,
"status": "completed",
},
},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex finished."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
tool = codex_tool(CodexToolOptions(codex=cast(Codex, FakeCodex(state))))
input_json = '{"inputs": [{"type": "text", "text": "List files", "path": ""}]}'
context = ToolContext(
context=None,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
with trace("codex-test"):
with function_span(tool.name):
await tool.on_invoke_tool(context, input_json)
spans = SPAN_PROCESSOR_TESTING.get_ordered_spans()
command_span = next(span for span in spans if span.span_data.name == "Codex command execution")
assert command_span.span_data.data["output"] == "first output"
@pytest.mark.asyncio
async def test_codex_tool_defaults_to_openai_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
state = CodexMockState()
state.events = [
{"type": "thread.started", "thread_id": "thread-1"},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
monkeypatch.setenv("OPENAI_API_KEY", "openai-key")
monkeypatch.delenv("CODEX_API_KEY", raising=False)
class CaptureCodex(FakeCodex):
def __init__(self, options: Any = None) -> None:
super().__init__(state, options)
monkeypatch.setattr(codex_tool_module, "Codex", CaptureCodex)
tool = codex_tool()
input_json = '{"inputs": [{"type": "text", "text": "Check default api key", "path": ""}]}'
context = ToolContext(
context=None,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
await tool.on_invoke_tool(context, input_json)
assert state.options is not None
assert getattr(state.options, "api_key", None) == "openai-key"
@pytest.mark.asyncio
async def test_codex_tool_accepts_codex_options_dict(monkeypatch: pytest.MonkeyPatch) -> None:
state = CodexMockState()
state.events = [
{"type": "thread.started", "thread_id": "thread-1"},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
class CaptureCodex(FakeCodex):
def __init__(self, options: Any = None) -> None:
super().__init__(state, options)
monkeypatch.setattr(codex_tool_module, "Codex", CaptureCodex)
tool = codex_tool({"codex_options": {"api_key": "from-options"}})
input_json = '{"inputs": [{"type": "text", "text": "Check dict options", "path": ""}]}'
context = ToolContext(
context=None,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
await tool.on_invoke_tool(context, input_json)
assert state.options is not None
assert getattr(state.options, "api_key", None) == "from-options"
@pytest.mark.asyncio
async def test_codex_tool_accepts_output_schema_descriptor() -> None:
state = CodexMockState()
state.events = [
{"type": "thread.started", "thread_id": "thread-1"},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
descriptor = {
"title": "Summary",
"properties": [
{
"name": "summary",
"description": "Short summary",
"schema": {"type": "string", "description": "Summary field"},
}
],
}
tool = codex_tool(
CodexToolOptions(codex=cast(Codex, FakeCodex(state)), output_schema=descriptor)
)
input_json = '{"inputs": [{"type": "text", "text": "Check schema", "path": ""}]}'
context = ToolContext(
context=None,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
await tool.on_invoke_tool(context, input_json)
output_schema = state.last_turn_options.output_schema
assert output_schema["type"] == "object"
assert output_schema["additionalProperties"] is False
assert output_schema["properties"]["summary"]["type"] == "string"
assert output_schema["properties"]["summary"]["description"] == "Short summary"
assert output_schema["required"] == []
@pytest.mark.asyncio
async def test_codex_tool_accepts_dict_options() -> None:
state = CodexMockState()
state.events = [
{"type": "thread.started", "thread_id": "thread-1"},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
options_dict: dict[str, Any] = {
"codex": cast(Codex, FakeCodex(state)),
"sandbox_mode": "read-only",
}
tool = codex_tool(options_dict)
input_json = '{"inputs": [{"type": "text", "text": "Check dict options", "path": ""}]}'
context = ToolContext(
context=None,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
result = await tool.on_invoke_tool(context, input_json)
assert isinstance(result, CodexToolResult)
assert result.response == "Codex done."
@pytest.mark.asyncio
async def test_codex_tool_accepts_keyword_options(monkeypatch: pytest.MonkeyPatch) -> None:
state = CodexMockState()
state.events = [
{"type": "thread.started", "thread_id": "thread-1"},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
class CaptureCodex(FakeCodex):
def __init__(self, options: Any = None) -> None:
super().__init__(state, options)
monkeypatch.setattr(codex_tool_module, "Codex", CaptureCodex)
tool = codex_tool(name="codex_keyword", codex_options={"api_key": "from-kwargs"})
input_json = '{"inputs": [{"type": "text", "text": "Check keyword options", "path": ""}]}'
context = ToolContext(
context=None,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
await tool.on_invoke_tool(context, input_json)
assert tool.name == "codex_keyword"
assert state.options is not None
assert getattr(state.options, "api_key", None) == "from-kwargs"
def test_codex_tool_truncates_span_values() -> None:
value = {"payload": "x" * 200}
truncated = codex_tool_module._truncate_span_value(value, 40)
assert isinstance(truncated, dict)
assert truncated["truncated"] is True
assert truncated["original_length"] > 40
preview = truncated["preview"]
assert isinstance(preview, str)
assert len(preview) <= 40
def test_codex_tool_enforces_span_data_budget() -> None:
data = {
"command": "run",
"output": "x" * 5000,
"arguments": {"payload": "y" * 5000},
}
trimmed = codex_tool_module._enforce_span_data_budget(data, 512)
assert "command" in trimmed
assert trimmed["command"]
assert "output" in trimmed
assert "arguments" in trimmed
assert codex_tool_module._json_char_size(trimmed) <= 512
def test_codex_tool_keeps_output_preview_with_budget() -> None:
data = {"output": "x" * 1000}
trimmed = codex_tool_module._enforce_span_data_budget(data, 120)
assert "output" in trimmed
assert isinstance(trimmed["output"], str)
assert trimmed["output"]
assert codex_tool_module._json_char_size(trimmed) <= 120
def test_codex_tool_prioritizes_arguments_over_large_results() -> None:
data = {"arguments": {"foo": "bar"}, "result": "x" * 2000}
trimmed = codex_tool_module._enforce_span_data_budget(data, 200)
assert trimmed["arguments"] == codex_tool_module._stringify_span_value({"foo": "bar"})
assert "result" in trimmed
assert codex_tool_module._json_char_size(trimmed) <= 200
@pytest.mark.asyncio
async def test_codex_tool_passes_idle_timeout_seconds() -> None:
state = CodexMockState()
state.events = [
{"type": "thread.started", "thread_id": "thread-1"},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
tool = codex_tool(
CodexToolOptions(
codex=cast(Codex, FakeCodex(state)),
default_turn_options={"idle_timeout_seconds": 3.5},
)
)
input_json = '{"inputs": [{"type": "text", "text": "Check timeout option", "path": ""}]}'
context = ToolContext(
context=None,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
await tool.on_invoke_tool(context, input_json)
assert state.last_turn_options is not None
assert state.last_turn_options.idle_timeout_seconds == 3.5
@pytest.mark.asyncio
async def test_codex_tool_persists_session() -> None:
state = CodexMockState()
state.events = [
{"type": "thread.started", "thread_id": "thread-1"},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
tool = codex_tool(
CodexToolOptions(
codex=cast(Codex, FakeCodex(state)),
persist_session=True,
)
)
input_json = '{"inputs": [{"type": "text", "text": "First call", "path": ""}]}'
context = ToolContext(
context=None,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
await tool.on_invoke_tool(context, input_json)
await tool.on_invoke_tool(context, input_json)
assert state.start_calls == 1
assert state.resume_calls == 0
@pytest.mark.asyncio
async def test_codex_tool_accepts_thread_id_from_tool_input() -> None:
state = CodexMockState()
state.thread_id = "thread-from-input"
state.events = [
{"type": "thread.started", "thread_id": "thread-from-input"},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
tool = codex_tool(CodexToolOptions(codex=cast(Codex, FakeCodex(state))))
input_json = (
'{"inputs": [{"type": "text", "text": "Continue thread", "path": ""}], '
'"thread_id": "thread-xyz"}'
)
context = ToolContext(
context=None,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
result = await tool.on_invoke_tool(context, input_json)
assert isinstance(result, CodexToolResult)
assert state.resume_calls == 1
assert state.last_resumed_thread_id == "thread-xyz"
assert result.thread_id == "thread-from-input"
@pytest.mark.asyncio
async def test_codex_tool_uses_run_context_thread_id_and_persists_latest() -> None:
state = CodexMockState()
state.thread_id = "thread-next"
state.events = [
{"type": "thread.started", "thread_id": "thread-next"},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
tool = codex_tool(
CodexToolOptions(
codex=cast(Codex, FakeCodex(state)),
use_run_context_thread_id=True,
run_context_thread_id_key="codex_agent_thread_id",
)
)
input_json = '{"inputs": [{"type": "text", "text": "Continue thread", "path": ""}]}'
run_context = {"codex_agent_thread_id": "thread-prev"}
context = ToolContext(
context=run_context,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
result = await tool.on_invoke_tool(context, input_json)
assert isinstance(result, CodexToolResult)
assert state.resume_calls == 1
assert state.last_resumed_thread_id == "thread-prev"
assert run_context["codex_agent_thread_id"] == "thread-next"
assert result.thread_id == "thread-next"
@pytest.mark.asyncio
async def test_codex_tool_persists_thread_started_id_when_thread_object_id_is_none() -> None:
state = CodexMockState()
state.thread_id = None
state.events = [
{"type": "thread.started", "thread_id": "thread-next"},
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
tool = codex_tool(
CodexToolOptions(
codex=cast(Codex, FakeCodex(state)),
use_run_context_thread_id=True,
run_context_thread_id_key="codex_agent_thread_id",
)
)
input_json = '{"inputs": [{"type": "text", "text": "Continue thread", "path": ""}]}'
run_context: dict[str, str] = {}
context = ToolContext(
context=run_context,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
first_result = await tool.on_invoke_tool(context, input_json)
second_result = await tool.on_invoke_tool(context, input_json)
assert isinstance(first_result, CodexToolResult)
assert isinstance(second_result, CodexToolResult)
assert first_result.thread_id == "thread-next"
assert second_result.thread_id == "thread-next"
assert run_context["codex_agent_thread_id"] == "thread-next"
assert state.start_calls == 1
assert state.resume_calls == 1
assert state.last_resumed_thread_id == "thread-next"
@pytest.mark.asyncio
async def test_codex_tool_persists_thread_id_for_recoverable_turn_failure() -> None:
state = CodexMockState()
state.thread_id = None
state.events = [
{"type": "thread.started", "thread_id": "thread-next"},
{"type": "turn.failed", "error": {"message": "boom"}},
]
tool = codex_tool(
CodexToolOptions(
codex=cast(Codex, FakeCodex(state)),
use_run_context_thread_id=True,
run_context_thread_id_key="codex_agent_thread_id",
failure_error_function=lambda _ctx, _exc: "handled",
)
)
input_json = '{"inputs": [{"type": "text", "text": "Continue thread", "path": ""}]}'
run_context: dict[str, str] = {}
context = ToolContext(
context=run_context,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
first_result = await tool.on_invoke_tool(context, input_json)
second_result = await tool.on_invoke_tool(context, input_json)
assert first_result == "handled"
assert second_result == "handled"
assert run_context["codex_agent_thread_id"] == "thread-next"
assert state.start_calls == 1
assert state.resume_calls == 1
assert state.last_resumed_thread_id == "thread-next"
@pytest.mark.asyncio
async def test_codex_tool_persists_thread_id_for_raised_turn_failure() -> None:
state = CodexMockState()
state.thread_id = None
state.events = [
{"type": "thread.started", "thread_id": "thread-next"},
{"type": "turn.failed", "error": {"message": "boom"}},
]
tool = codex_tool(
CodexToolOptions(
codex=cast(Codex, FakeCodex(state)),
use_run_context_thread_id=True,
run_context_thread_id_key="codex_agent_thread_id",
failure_error_function=None,
)
)
input_json = '{"inputs": [{"type": "text", "text": "Continue thread", "path": ""}]}'
run_context: dict[str, str] = {}
context = ToolContext(
context=run_context,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
with pytest.raises(UserError, match="Codex turn failed: boom"):
await tool.on_invoke_tool(context, input_json)
assert run_context["codex_agent_thread_id"] == "thread-next"
with pytest.raises(UserError, match="Codex turn failed: boom"):
await tool.on_invoke_tool(context, input_json)
assert run_context["codex_agent_thread_id"] == "thread-next"
assert state.start_calls == 1
assert state.resume_calls == 1
assert state.last_resumed_thread_id == "thread-next"
@pytest.mark.asyncio
async def test_codex_tool_persists_thread_id_for_cancelled_turn() -> None:
state = CodexMockState()
state.thread_id = None
state.events = [
{"type": "thread.started", "thread_id": "thread-next"},
{"type": "raise_cancelled", "message": "codex-cancelled"},
]
tool = codex_tool(
CodexToolOptions(
codex=cast(Codex, FakeCodex(state)),
use_run_context_thread_id=True,
run_context_thread_id_key="codex_agent_thread_id",
)
)
input_json = '{"inputs": [{"type": "text", "text": "Continue thread", "path": ""}]}'
run_context: dict[str, str] = {}
context = ToolContext(
context=run_context,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=input_json,
)
with pytest.raises(asyncio.CancelledError, match="codex-cancelled"):
await tool.on_invoke_tool(context, input_json)
assert run_context["codex_agent_thread_id"] == "thread-next"
state.events = [
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
result = await tool.on_invoke_tool(context, input_json)
assert isinstance(result, CodexToolResult)
assert result.thread_id == "thread-next"
assert run_context["codex_agent_thread_id"] == "thread-next"
assert state.start_calls == 1
assert state.resume_calls == 1
assert state.last_resumed_thread_id == "thread-next"
@pytest.mark.asyncio
async def test_codex_tool_persists_thread_id_for_handled_parallel_cancellation() -> None:
state = CodexMockState()
state.thread_id = None
codex_thread_started = asyncio.Event()
state.events = [
{"type": "thread.started", "thread_id": "thread-next"},
{"type": "wait_for_cancel", "started_event": codex_thread_started},
]
codex_function_tool = codex_tool(
CodexToolOptions(
codex=cast(Codex, FakeCodex(state)),
use_run_context_thread_id=True,
run_context_thread_id_key="codex_agent_thread_id",
)
)
async def _error_tool() -> str:
await codex_thread_started.wait()
raise ValueError("boom")
error_tool = function_tool(
_error_tool,
name_override="error_tool",
failure_error_function=None,
)
agent = Agent(name="test", tools=[codex_function_tool, error_tool])
run_context: dict[str, str] = {}
context_wrapper = RunContextWrapper(run_context)
input_json = '{"inputs": [{"type": "text", "text": "Continue thread", "path": ""}]}'
tool_runs = [
ToolRunFunction(
tool_call=cast(
ResponseFunctionToolCall,
get_function_tool_call(codex_function_tool.name, input_json, call_id="1"),
),
function_tool=codex_function_tool,
),
ToolRunFunction(
tool_call=cast(
ResponseFunctionToolCall,
get_function_tool_call("error_tool", "{}", call_id="2"),
),
function_tool=error_tool,
),
]
with pytest.raises(UserError, match="Error running tool error_tool: boom"):
await execute_function_tool_calls(
bindings=bind_public_agent(agent),
tool_runs=tool_runs,
hooks=RunHooks(),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert run_context["codex_agent_thread_id"] == "thread-next"
assert state.start_calls == 1
assert state.resume_calls == 0
state.thread_id = "thread-next"
state.events = [
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
result = await codex_function_tool.on_invoke_tool(
ToolContext(
context=run_context,
tool_name=codex_function_tool.name,
tool_call_id="call-2",
tool_arguments=input_json,
),
input_json,
)
assert isinstance(result, CodexToolResult)
assert result.thread_id == "thread-next"
assert run_context["codex_agent_thread_id"] == "thread-next"
assert state.start_calls == 1
assert state.resume_calls == 1
assert state.last_resumed_thread_id == "thread-next"
@pytest.mark.asyncio
async def test_codex_tool_falls_back_to_call_thread_id_when_thread_object_id_is_none() -> None:
state = CodexMockState()
state.thread_id = None
state.events = [
{
"type": "item.completed",
"item": {"id": "agent-1", "type": "agent_message", "text": "Codex done."},
},
{
"type": "turn.completed",
"usage": {"input_tokens": 1, "cached_input_tokens": 0, "output_tokens": 1},
},
]
tool = codex_tool(
CodexToolOptions(
codex=cast(Codex, FakeCodex(state)),
parameters=codex_tool_module.CodexToolParameters,
use_run_context_thread_id=True,
)
)
first_input_json = (
'{"inputs": [{"type": "text", "text": "Continue thread", "path": ""}], '
'"thread_id": "thread-explicit"}'
)
second_input_json = '{"inputs": [{"type": "text", "text": "Continue thread", "path": ""}]}'
run_context: dict[str, str] = {}
context = ToolContext(
context=run_context,
tool_name=tool.name,
tool_call_id="call-1",
tool_arguments=first_input_json,
)
first_result = await tool.on_invoke_tool(context, first_input_json)
second_result = await tool.on_invoke_tool(context, second_input_json)
assert isinstance(first_result, CodexToolResult)
assert isinstance(second_result, CodexToolResult)
assert first_result.thread_id == "thread-explicit"
assert second_result.thread_id == "thread-explicit"
assert run_context["codex_thread_id"] == "thread-explicit"