forked from openai/codex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate_sdk_artifacts.py
More file actions
executable file
·1369 lines (1168 loc) · 48.8 KB
/
Copy pathupdate_sdk_artifacts.py
File metadata and controls
executable file
·1369 lines (1168 loc) · 48.8 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
#!/usr/bin/env python3
import argparse
import importlib
import importlib.metadata
import json
import platform
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import types
import typing
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Sequence, get_args, get_origin
SDK_DISTRIBUTION_NAME = "openai-codex"
RUNTIME_DISTRIBUTION_NAME = "openai-codex-cli-bin"
RUNTIME_PACKAGE_ROOT = Path("src") / "codex_cli_bin"
CODEX_PACKAGE_METADATA = "codex-package.json"
def repo_root() -> Path:
return Path(__file__).resolve().parents[3]
def sdk_root() -> Path:
return repo_root() / "sdk" / "python"
def python_runtime_root() -> Path:
return repo_root() / "sdk" / "python-runtime"
def sdk_pyproject_path() -> Path:
"""Return the SDK pyproject file that owns package pins and versions."""
return sdk_root() / "pyproject.toml"
def schema_bundle_path(schema_dir: Path) -> Path:
"""Return the aggregate v2 schema bundle emitted by the runtime binary."""
return schema_dir / "codex_app_server_protocol.v2.schemas.json"
def _is_windows() -> bool:
return platform.system().lower().startswith("win")
def runtime_binary_name() -> str:
return "codex.exe" if _is_windows() else "codex"
def staged_runtime_package_root(root: Path) -> Path:
return root / RUNTIME_PACKAGE_ROOT
def run(cmd: list[str], cwd: Path) -> None:
subprocess.run(cmd, cwd=str(cwd), check=True)
def run_python_module(module: str, args: list[str], cwd: Path) -> None:
run([sys.executable, "-m", module, *args], cwd)
def current_sdk_version() -> str:
match = re.search(
r'^version = "([^"]+)"$',
sdk_pyproject_path().read_text(),
flags=re.MULTILINE,
)
if match is None:
raise RuntimeError("Could not determine Python SDK version from pyproject.toml")
return match.group(1)
def pinned_runtime_version() -> str:
"""Read the exact runtime package pin used for schema generation."""
pyproject_text = sdk_pyproject_path().read_text()
match = re.search(r"(?ms)^dependencies = \[(.*?)\]$", pyproject_text)
if match is None:
raise RuntimeError("Could not find dependencies array in sdk/python/pyproject.toml")
pins = re.findall(
rf'"{re.escape(RUNTIME_DISTRIBUTION_NAME)}==([^"]+)"',
match.group(1),
)
if len(pins) != 1:
raise RuntimeError(
f"Expected exactly one {RUNTIME_DISTRIBUTION_NAME} dependency pin "
"in sdk/python/pyproject.toml"
)
return normalize_codex_version(pins[0])
def pinned_runtime_codex_path() -> Path:
"""Return the bundled Codex binary from the installed pinned runtime wheel."""
expected_version = pinned_runtime_version()
try:
installed_version = importlib.metadata.version(RUNTIME_DISTRIBUTION_NAME)
except importlib.metadata.PackageNotFoundError as exc:
raise RuntimeError(
f"Install {RUNTIME_DISTRIBUTION_NAME}=={expected_version} before "
"generating Python SDK types."
) from exc
normalized_installed_version = normalize_codex_version(installed_version)
if normalized_installed_version != expected_version:
raise RuntimeError(
f"Expected {RUNTIME_DISTRIBUTION_NAME}=={expected_version}, "
f"but found {installed_version}."
)
try:
from codex_cli_bin import bundled_codex_path
except ImportError as exc:
raise RuntimeError(
f"Installed {RUNTIME_DISTRIBUTION_NAME} package does not expose bundled_codex_path."
) from exc
codex_path = bundled_codex_path()
if not codex_path.exists():
raise RuntimeError(f"Pinned Codex runtime binary not found at {codex_path}.")
return codex_path
def normalize_codex_version(version: str) -> str:
normalized = version.strip()
if normalized.startswith("rust-v"):
normalized = normalized.removeprefix("rust-v")
elif normalized.startswith("v"):
normalized = normalized.removeprefix("v")
normalized = re.sub(r"-alpha\.?([0-9]+)$", r"a\1", normalized)
normalized = re.sub(r"-beta\.?([0-9]+)$", r"b\1", normalized)
normalized = re.sub(r"-rc\.?([0-9]+)$", r"rc\1", normalized)
if not re.fullmatch(r"[0-9]+(?:\.[0-9]+)*(?:(?:a|b|rc)[0-9]+)?", normalized):
raise RuntimeError(f"Could not normalize Codex version {version!r} to a PEP 440 version")
return normalized
def _copy_package_tree(src: Path, dst: Path) -> None:
if dst.exists():
if dst.is_dir():
shutil.rmtree(dst)
else:
dst.unlink()
shutil.copytree(
src,
dst,
ignore=shutil.ignore_patterns(
".venv",
".venv2",
".pytest_cache",
"__pycache__",
"build",
"dist",
"*.pyc",
),
)
def _rewrite_project_version(pyproject_text: str, version: str) -> str:
updated, count = re.subn(
r'^version = "[^"]+"$',
f'version = "{version}"',
pyproject_text,
count=1,
flags=re.MULTILINE,
)
if count != 1:
raise RuntimeError("Could not rewrite project version in pyproject.toml")
return updated
def _rewrite_runtime_platform_tag(pyproject_text: str, platform_tag: str) -> str:
section = "[tool.hatch.build.targets.wheel.hooks.custom]"
section_index = pyproject_text.find(section)
if section_index == -1:
raise RuntimeError("Could not find runtime wheel custom hook config")
next_section_index = pyproject_text.find("\n[", section_index + len(section))
if next_section_index == -1:
section_text = pyproject_text[section_index:]
tail = ""
else:
section_text = pyproject_text[section_index:next_section_index]
tail = pyproject_text[next_section_index:]
updated_section, count = re.subn(
r'^platform-tag = "[^"]*"$',
f'platform-tag = "{platform_tag}"',
section_text,
count=1,
flags=re.MULTILINE,
)
if count == 0:
updated_section = section_text.rstrip() + f'\nplatform-tag = "{platform_tag}"\n'
return pyproject_text[:section_index] + updated_section + tail
def _rewrite_project_name(pyproject_text: str, name: str) -> str:
updated, count = re.subn(
r'^name = "[^"]+"$',
f'name = "{name}"',
pyproject_text,
count=1,
flags=re.MULTILINE,
)
if count != 1:
raise RuntimeError("Could not rewrite project name in pyproject.toml")
return updated
def stage_python_sdk_package(staging_dir: Path, sdk_version: str) -> Path:
package_version = normalize_codex_version(sdk_version)
_copy_package_tree(sdk_root(), staging_dir)
sdk_bin_dir = staging_dir / "src" / "openai_codex" / "bin"
if sdk_bin_dir.exists():
shutil.rmtree(sdk_bin_dir)
pyproject_path = staging_dir / "pyproject.toml"
pyproject_text = pyproject_path.read_text()
pyproject_text = _rewrite_project_name(pyproject_text, SDK_DISTRIBUTION_NAME)
pyproject_text = _rewrite_project_version(pyproject_text, package_version)
pyproject_path.write_text(pyproject_text)
return staging_dir
def stage_python_runtime_package(
staging_dir: Path,
codex_version: str,
package_archive: Path,
platform_tag: str | None = None,
) -> Path:
package_version = normalize_codex_version(codex_version)
_copy_package_tree(python_runtime_root(), staging_dir)
pyproject_path = staging_dir / "pyproject.toml"
pyproject_text = pyproject_path.read_text()
pyproject_text = _rewrite_project_name(pyproject_text, RUNTIME_DISTRIBUTION_NAME)
pyproject_text = _rewrite_project_version(pyproject_text, package_version)
if platform_tag is not None:
pyproject_text = _rewrite_runtime_platform_tag(pyproject_text, platform_tag)
pyproject_path.write_text(pyproject_text)
_extract_codex_package_archive(package_archive, staged_runtime_package_root(staging_dir))
return staging_dir
def _extract_codex_package_archive(package_archive: Path, runtime_package_root: Path) -> None:
if not package_archive.name.endswith(".tar.gz"):
raise RuntimeError(f"Expected a .tar.gz Codex package archive: {package_archive}")
runtime_package_root.mkdir(parents=True, exist_ok=True)
with tarfile.open(package_archive, "r:gz") as archive:
try:
archive.extractall(runtime_package_root, filter="data")
except TypeError:
archive.extractall(runtime_package_root)
_validate_codex_package_layout(runtime_package_root, package_archive)
def _validate_codex_package_layout(package_dir: Path, package_archive: Path) -> None:
missing_entries = []
if not (package_dir / CODEX_PACKAGE_METADATA).is_file():
missing_entries.append(CODEX_PACKAGE_METADATA)
for entry in ("bin", "codex-resources", "codex-path"):
if not (package_dir / entry).is_dir():
missing_entries.append(entry)
package_binary = package_dir / "bin" / runtime_binary_name()
if not package_binary.is_file():
missing_entries.append(str(Path("bin") / runtime_binary_name()))
if missing_entries:
missing = ", ".join(missing_entries)
raise RuntimeError(f"Missing Codex package layout entries in {package_archive}: {missing}")
def _flatten_string_enum_one_of(definition: dict[str, Any]) -> bool:
branches = definition.get("oneOf")
if not isinstance(branches, list) or not branches:
return False
enum_values: list[str] = []
for branch in branches:
if not isinstance(branch, dict):
return False
if branch.get("type") != "string":
return False
enum = branch.get("enum")
if not isinstance(enum, list) or len(enum) != 1 or not isinstance(enum[0], str):
return False
extra_keys = set(branch) - {"type", "enum", "description", "title"}
if extra_keys:
return False
enum_values.append(enum[0])
description = definition.get("description")
title = definition.get("title")
definition.clear()
definition["type"] = "string"
definition["enum"] = enum_values
if isinstance(description, str):
definition["description"] = description
if isinstance(title, str):
definition["title"] = title
return True
DISCRIMINATOR_KEYS = ("type", "method", "mode", "state", "status", "role", "reason")
def _to_pascal_case(value: str) -> str:
parts = re.split(r"[^0-9A-Za-z]+", value)
compact = "".join(part[:1].upper() + part[1:] for part in parts if part)
return compact or "Value"
def _string_literal(value: Any) -> str | None:
if not isinstance(value, dict):
return None
const = value.get("const")
if isinstance(const, str):
return const
enum = value.get("enum")
if isinstance(enum, list) and enum and len(enum) == 1 and isinstance(enum[0], str):
return enum[0]
return None
def _enum_literals(value: Any) -> list[str] | None:
if not isinstance(value, dict):
return None
enum = value.get("enum")
if not isinstance(enum, list) or not enum or not all(isinstance(item, str) for item in enum):
return None
return list(enum)
def _literal_from_property(props: dict[str, Any], key: str) -> str | None:
return _string_literal(props.get(key))
def _variant_definition_name(base: str, variant: dict[str, Any]) -> str | None:
# datamodel-code-generator invents numbered helper names for inline union
# branches unless they carry a stable, unique title up front. We derive
# those titles from the branch discriminator or other identifying shape.
props = variant.get("properties")
if isinstance(props, dict):
for key in DISCRIMINATOR_KEYS:
literal = _literal_from_property(props, key)
if literal is None:
continue
pascal = _to_pascal_case(literal)
if base == "ClientRequest":
return f"{pascal}Request"
if base == "ServerRequest":
return f"{pascal}ServerRequest"
if base == "ClientNotification":
return f"{pascal}ClientNotification"
if base == "ServerNotification":
return f"{pascal}ServerNotification"
if base == "EventMsg":
return f"{pascal}EventMsg"
return f"{pascal}{base}"
if len(props) == 1:
key = next(iter(props))
pascal = _string_literal(props[key])
return f"{_to_pascal_case(pascal or key)}{base}"
required = variant.get("required")
if isinstance(required, list) and len(required) == 1 and isinstance(required[0], str):
return f"{_to_pascal_case(required[0])}{base}"
enum_literals = _enum_literals(variant)
if enum_literals is not None:
if len(enum_literals) == 1:
return f"{_to_pascal_case(enum_literals[0])}{base}"
return f"{base}Value"
return None
def _variant_collision_key(base: str, variant: dict[str, Any], generated_name: str) -> str:
parts = [f"base={base}", f"generated={generated_name}"]
props = variant.get("properties")
if isinstance(props, dict):
for key in DISCRIMINATOR_KEYS:
literal = _literal_from_property(props, key)
if literal is not None:
parts.append(f"{key}={literal}")
if len(props) == 1:
parts.append(f"only_property={next(iter(props))}")
required = variant.get("required")
if isinstance(required, list) and len(required) == 1 and isinstance(required[0], str):
parts.append(f"required_only={required[0]}")
enum_literals = _enum_literals(variant)
if enum_literals is not None:
parts.append(f"enum={'|'.join(enum_literals)}")
return "|".join(parts)
def _set_discriminator_titles(props: dict[str, Any], owner: str) -> None:
for key in DISCRIMINATOR_KEYS:
prop = props.get(key)
if not isinstance(prop, dict):
continue
if _string_literal(prop) is None or "title" in prop:
continue
prop["title"] = f"{owner}{_to_pascal_case(key)}"
def _annotate_variant_list(variants: list[Any], base: str | None) -> None:
seen = {
variant["title"]
for variant in variants
if isinstance(variant, dict) and isinstance(variant.get("title"), str)
}
for variant in variants:
if not isinstance(variant, dict):
continue
variant_name = variant.get("title")
generated_name = _variant_definition_name(base, variant) if base else None
if generated_name is not None and (
not isinstance(variant_name, str)
or "/" in variant_name
or variant_name != generated_name
):
# Titles like `Thread/startedNotification` sanitize poorly in
# Python, and envelope titles like `ErrorNotification` collide
# with their payload model names. Rewrite them before codegen so
# we get `ThreadStartedServerNotification` instead of `...1`.
if generated_name in seen and variant_name != generated_name:
raise RuntimeError(
"Variant title naming collision detected: "
f"{_variant_collision_key(base or '<root>', variant, generated_name)}"
)
variant["title"] = generated_name
seen.add(generated_name)
variant_name = generated_name
if isinstance(variant_name, str):
props = variant.get("properties")
if isinstance(props, dict):
_set_discriminator_titles(props, variant_name)
_annotate_schema(variant, base)
def _annotate_schema(value: Any, base: str | None = None) -> None:
if isinstance(value, list):
for item in value:
_annotate_schema(item, base)
return
if not isinstance(value, dict):
return
owner = value.get("title")
props = value.get("properties")
if isinstance(owner, str) and isinstance(props, dict):
_set_discriminator_titles(props, owner)
one_of = value.get("oneOf")
if isinstance(one_of, list):
# Walk nested unions recursively so every inline branch gets the same
# title normalization treatment before we hand the bundle to Python
# codegen.
_annotate_variant_list(one_of, base)
any_of = value.get("anyOf")
if isinstance(any_of, list):
_annotate_variant_list(any_of, base)
definitions = value.get("definitions")
if isinstance(definitions, dict):
for name, schema in definitions.items():
_annotate_schema(schema, name if isinstance(name, str) else base)
defs = value.get("$defs")
if isinstance(defs, dict):
for name, schema in defs.items():
_annotate_schema(schema, name if isinstance(name, str) else base)
for key, child in value.items():
if key in {"oneOf", "anyOf", "definitions", "$defs"}:
continue
_annotate_schema(child, base)
def _make_chatgpt_account_email_nullable(schema: dict[str, Any]) -> None:
definitions = schema.get("definitions")
if not isinstance(definitions, dict):
raise RuntimeError("Schema bundle is missing definitions")
account = definitions.get("Account")
if not isinstance(account, dict):
raise RuntimeError("Schema bundle is missing the Account definition")
for variant in account.get("oneOf", []):
if not isinstance(variant, dict):
continue
properties = variant.get("properties")
if not isinstance(properties, dict):
continue
account_type = properties.get("type")
if not isinstance(account_type, dict) or account_type.get("enum") != ["chatgpt"]:
continue
email = properties.get("email")
if not isinstance(email, dict):
raise RuntimeError("ChatGPT account schema is missing email")
email["type"] = ["string", "null"]
return
raise RuntimeError("Schema bundle is missing the ChatGPT account variant")
def generate_schema_from_pinned_runtime(schema_dir: Path) -> Path:
"""Generate app-server schemas by invoking the installed pinned runtime binary."""
codex_path = pinned_runtime_codex_path()
if schema_dir.exists():
shutil.rmtree(schema_dir)
schema_dir.mkdir(parents=True)
run(
[
str(codex_path),
"app-server",
"generate-json-schema",
"--out",
str(schema_dir),
],
cwd=sdk_root(),
)
return schema_dir
def _normalized_schema_bundle_text(schema_dir: Path) -> str:
"""Normalize the schema bundle before feeding it to the Python type generator."""
schema = json.loads(schema_bundle_path(schema_dir).read_text())
_make_chatgpt_account_email_nullable(schema)
definitions = schema.get("definitions", {})
if isinstance(definitions, dict):
for definition in definitions.values():
if isinstance(definition, dict):
_flatten_string_enum_one_of(definition)
# Normalize the schema into something datamodel-code-generator can map to
# stable class names instead of anonymous numbered helpers.
_annotate_schema(schema)
return json.dumps(schema, indent=2, sort_keys=True) + "\n"
def generate_v2_all(schema_dir: Path) -> None:
"""Regenerate the Pydantic v2 protocol model module from runtime schemas."""
out_path = sdk_root() / "src" / "openai_codex" / "generated" / "v2_all.py"
out_dir = out_path.parent
old_package_dir = out_dir / "v2_all"
if old_package_dir.exists():
shutil.rmtree(old_package_dir)
out_dir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as td:
normalized_bundle = Path(td) / schema_bundle_path(schema_dir).name
normalized_bundle.write_text(_normalized_schema_bundle_text(schema_dir))
run_python_module(
"datamodel_code_generator",
[
"--input",
str(normalized_bundle),
"--input-file-type",
"jsonschema",
"--output",
str(out_path),
"--output-model-type",
"pydantic_v2.BaseModel",
"--target-python-version",
"3.11",
"--use-standard-collections",
"--enum-field-as-literal",
"one",
"--field-constraints",
"--use-default-kwarg",
"--snake-case-field",
"--allow-population-by-field-name",
# Once the schema prepass has assigned stable titles, tell the
# generator to prefer those titles as the emitted class names.
"--use-title-as-name",
"--use-annotated",
"--use-union-operator",
"--disable-timestamp",
# Keep the generated file formatted deterministically so the
# checked-in artifact only changes when the schema does.
"--formatters",
"ruff-format",
],
cwd=sdk_root(),
)
_require_nullable_chatgpt_account_email(out_path)
_normalize_generated_timestamps(out_path)
def _require_nullable_chatgpt_account_email(out_path: Path) -> None:
"""Preserve required-but-nullable email semantics in the generated SDK model."""
source = out_path.read_text()
class_start = source.find("class ChatgptAccount(BaseModel):")
if class_start == -1:
raise RuntimeError("Generated SDK is missing ChatgptAccount")
class_end = source.find("\n\nclass ", class_start)
if class_end == -1:
class_end = len(source)
class_source = source[class_start:class_end]
nullable_with_default = " email: str | None = None"
if class_source.count(nullable_with_default) != 1:
raise RuntimeError(
"Generated ChatgptAccount email did not have the expected nullable shape"
)
class_source = class_source.replace(
nullable_with_default,
" email: str | None",
1,
)
out_path.write_text(source[:class_start] + class_source + source[class_end:])
def _notification_specs(schema_dir: Path) -> list[tuple[str, str]]:
"""Map each server notification method to its generated payload model class."""
server_notifications = json.loads((schema_dir / "ServerNotification.json").read_text())
one_of = server_notifications.get("oneOf", [])
generated_source = (sdk_root() / "src" / "openai_codex" / "generated" / "v2_all.py").read_text()
specs: list[tuple[str, str]] = []
for variant in one_of:
props = variant.get("properties", {})
method_meta = props.get("method", {})
params_meta = props.get("params", {})
methods = method_meta.get("enum", [])
if len(methods) != 1:
continue
method = methods[0]
if not isinstance(method, str):
continue
ref = params_meta.get("$ref")
if not isinstance(ref, str) or not ref.startswith("#/definitions/"):
continue
class_name = ref.split("/")[-1]
if (
f"class {class_name}(" not in generated_source
and f"{class_name} =" not in generated_source
):
# Skip schema variants that are not emitted into the generated v2 surface.
continue
specs.append((method, class_name))
specs.sort()
return specs
def _notification_turn_id_specs(
schema_dir: Path,
specs: list[tuple[str, str]],
) -> tuple[list[str], list[str]]:
"""Classify notification payloads by where their turn id is carried."""
server_notifications = json.loads((schema_dir / "ServerNotification.json").read_text())
definitions = server_notifications.get("definitions", {})
if not isinstance(definitions, dict):
return ([], [])
direct: list[str] = []
nested: list[str] = []
for _, class_name in specs:
definition = definitions.get(class_name)
if not isinstance(definition, dict):
continue
props = definition.get("properties", {})
if not isinstance(props, dict):
continue
if "turnId" in props:
direct.append(class_name)
continue
turn = props.get("turn")
if isinstance(turn, dict) and turn.get("$ref") == "#/definitions/Turn":
nested.append(class_name)
return (sorted(set(direct)), sorted(set(nested)))
def _type_tuple_source(class_names: list[str]) -> str:
"""Render a generated tuple literal for notification payload classes."""
if not class_names:
return "()"
if len(class_names) == 1:
return f"({class_names[0]},)"
return "(\n" + "".join(f" {class_name},\n" for class_name in class_names) + ")"
def generate_notification_registry(schema_dir: Path) -> None:
"""Regenerate notification dispatch metadata from the runtime notification schema."""
out = sdk_root() / "src" / "openai_codex" / "generated" / "notification_registry.py"
specs = _notification_specs(schema_dir)
class_names = sorted({class_name for _, class_name in specs})
direct_turn_id_types, nested_turn_types = _notification_turn_id_specs(
schema_dir,
specs,
)
lines = [
"# Auto-generated by scripts/update_sdk_artifacts.py",
"# DO NOT EDIT MANUALLY.",
"",
"from __future__ import annotations",
"",
"from pydantic import BaseModel",
"",
]
for class_name in class_names:
lines.append(f"from .v2_all import {class_name}")
lines.extend(
[
"",
"NOTIFICATION_MODELS: dict[str, type[BaseModel]] = {",
]
)
for method, class_name in specs:
lines.append(f' "{method}": {class_name},')
lines.extend(
[
"}",
"",
"DIRECT_TURN_ID_NOTIFICATION_TYPES: tuple[type[BaseModel], ...] = "
f"{_type_tuple_source(direct_turn_id_types)}",
"",
"NESTED_TURN_NOTIFICATION_TYPES: tuple[type[BaseModel], ...] = "
f"{_type_tuple_source(nested_turn_types)}",
"",
"",
"def notification_turn_id(payload: BaseModel) -> str | None:",
' """Return the turn id carried by generated notification payload metadata."""',
" if isinstance(payload, DIRECT_TURN_ID_NOTIFICATION_TYPES):",
" return payload.turn_id if isinstance(payload.turn_id, str) else None",
" if isinstance(payload, NESTED_TURN_NOTIFICATION_TYPES):",
" return payload.turn.id",
" return None",
"",
]
)
out.write_text("\n".join(lines))
def _normalize_generated_timestamps(root: Path) -> None:
timestamp_re = re.compile(r"^#\s+timestamp:\s+.+$", flags=re.MULTILINE)
py_files = [root] if root.is_file() else sorted(root.rglob("*.py"))
for py_file in py_files:
content = py_file.read_text()
normalized = timestamp_re.sub("# timestamp: <normalized>", content)
if normalized != content:
py_file.write_text(normalized)
FIELD_ANNOTATION_OVERRIDES: dict[str, str] = {
# Keep public API typed without falling back to `Any`.
"config": "JsonObject",
"output_schema": "JsonObject",
}
@dataclass(slots=True)
class PublicFieldSpec:
wire_name: str
py_name: str
annotation: str
required: bool
@dataclass(frozen=True)
class CliOps:
generate_types: Callable[[], None]
stage_python_sdk_package: Callable[[Path, str], Path]
stage_python_runtime_package: Callable[[Path, str, Path, str | None], Path]
current_sdk_version: Callable[[], str]
def _annotation_to_source(annotation: Any) -> str:
origin = get_origin(annotation)
if origin is typing.Annotated:
return _annotation_to_source(get_args(annotation)[0])
if origin in (typing.Union, types.UnionType):
parts: list[str] = []
for arg in get_args(annotation):
rendered = _annotation_to_source(arg)
if rendered not in parts:
parts.append(rendered)
return " | ".join(parts)
if origin is list:
args = get_args(annotation)
item = _annotation_to_source(args[0]) if args else "Any"
return f"list[{item}]"
if origin is dict:
args = get_args(annotation)
key = _annotation_to_source(args[0]) if args else "str"
val = _annotation_to_source(args[1]) if len(args) > 1 else "Any"
return f"dict[{key}, {val}]"
if annotation is Any or annotation is typing.Any:
return "Any"
if annotation is None or annotation is type(None):
return "None"
if isinstance(annotation, type):
if annotation.__module__ == "builtins":
return annotation.__name__
return annotation.__name__
return repr(annotation)
def _camel_to_snake(name: str) -> str:
head = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", head).lower()
def _load_public_fields(
module_name: str, class_name: str, *, exclude: set[str] | None = None
) -> list[PublicFieldSpec]:
"""Load generated model fields used to render the ergonomic public methods."""
exclude = exclude or set()
if module_name == "openai_codex.generated.v2_all":
module = _load_generated_v2_all_module()
else:
module = importlib.import_module(module_name)
model = getattr(module, class_name)
fields: list[PublicFieldSpec] = []
for name, field in model.model_fields.items():
if name in exclude:
continue
required = field.is_required()
annotation = _annotation_to_source(field.annotation)
override = FIELD_ANNOTATION_OVERRIDES.get(name)
if override is not None:
annotation = override if required else f"{override} | None"
fields.append(
PublicFieldSpec(
wire_name=name,
py_name=name,
annotation=annotation,
required=required,
)
)
return fields
def _load_generated_v2_all_module() -> types.ModuleType:
"""Import the freshly generated v2_all module without importing package init."""
module_name = "_openai_codex_generated_v2_all_for_artifacts"
sys.modules.pop(module_name, None)
module_path = sdk_root() / "src" / "openai_codex" / "generated" / "v2_all.py"
spec = importlib.util.spec_from_file_location(module_name, module_path)
if spec is None or spec.loader is None:
raise RuntimeError(f"Failed to load generated module from {module_path}")
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module
def _kw_signature_lines(fields: list[PublicFieldSpec]) -> list[str]:
lines: list[str] = []
for field in fields:
default = "" if field.required else " = None"
lines.append(f" {field.py_name}: {field.annotation}{default},")
return lines
def _approval_mode_start_signature_lines() -> list[str]:
"""Return the approval mode kwarg for new threads."""
return [" approval_mode: ApprovalMode = ApprovalMode.auto_review,"]
def _approval_mode_override_signature_lines() -> list[str]:
"""Return the optional approval mode kwarg for override-style helpers."""
return [" approval_mode: ApprovalMode | None = None,"]
def _approval_mode_assignment_line(helper_name: str, *, indent: str = " ") -> str:
"""Return the local mapping from public mode to app-server params."""
return f"{indent}approval_policy, approvals_reviewer = {helper_name}(approval_mode)"
def _approval_mode_model_arg_lines(*, indent: str = " ") -> list[str]:
"""Return app-server approval params derived from ApprovalMode."""
return [
f"{indent}approval_policy=approval_policy,",
f"{indent}approvals_reviewer=approvals_reviewer,",
]
def _model_arg_lines(fields: list[PublicFieldSpec], *, indent: str = " ") -> list[str]:
lines: list[str] = []
for field in fields:
arg = field.py_name
if field.wire_name == "sandbox":
arg = "_sandbox_mode(sandbox)"
elif field.wire_name == "sandbox_policy":
arg = "_sandbox_policy(sandbox)"
lines.append(f"{indent}{field.wire_name}={arg},")
return lines
def _replace_public_sandbox_field(
fields: list[PublicFieldSpec], *, wire_name: str
) -> list[PublicFieldSpec]:
"""Expose stable wire sandbox settings through one public enum parameter."""
public_fields: list[PublicFieldSpec] = []
replaced = False
for field in fields:
if field.wire_name != wire_name:
public_fields.append(field)
continue
if replaced:
raise RuntimeError(f"Found more than one generated sandbox field named {wire_name}")
public_fields.append(
PublicFieldSpec(
wire_name=wire_name,
py_name="sandbox",
annotation="Sandbox | None",
required=False,
)
)
replaced = True
if not replaced:
raise RuntimeError(f"Could not find generated sandbox field named {wire_name}")
return public_fields
def _replace_generated_block(source: str, block_name: str, body: str) -> str:
start_tag = f" # BEGIN GENERATED: {block_name}"
end_tag = f" # END GENERATED: {block_name}"
pattern = re.compile(rf"(?s){re.escape(start_tag)}\n.*?\n{re.escape(end_tag)}")
replacement = f"{start_tag}\n{body.rstrip()}\n{end_tag}"
updated, count = pattern.subn(replacement, source, count=1)
if count != 1:
raise RuntimeError(f"Could not update generated block: {block_name}")
return updated
def _render_codex_block(
thread_start_fields: list[PublicFieldSpec],
thread_list_fields: list[PublicFieldSpec],
resume_fields: list[PublicFieldSpec],
fork_fields: list[PublicFieldSpec],
) -> str:
lines = [
" def thread_start(",
" self,",
" *,",
*_approval_mode_start_signature_lines(),
*_kw_signature_lines(thread_start_fields),
" ) -> Thread:",
' """Create a new Codex conversation thread."""',
_approval_mode_assignment_line("_approval_mode_settings"),
" params = ThreadStartParams(",
*_approval_mode_model_arg_lines(),
*_model_arg_lines(thread_start_fields),
" )",
" started = self._client.thread_start(params)",
" return Thread(self._client, started.thread.id)",
"",
" def thread_list(",
" self,",
" *,",
*_kw_signature_lines(thread_list_fields),
" ) -> ThreadListResponse:",
' """List saved conversation threads."""',
" params = ThreadListParams(",
*_model_arg_lines(thread_list_fields),
" )",
" return self._client.thread_list(params)",
"",
" def thread_resume(",
" self,",
" thread_id: str,",
" *,",
*_approval_mode_override_signature_lines(),
*_kw_signature_lines(resume_fields),
" ) -> Thread:",