-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathgen_schema.py
More file actions
1116 lines (957 loc) · 43.2 KB
/
Copy pathgen_schema.py
File metadata and controls
1116 lines (957 loc) · 43.2 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
from __future__ import annotations
import ast
import copy
import json
import re
import subprocess
import sys
import tempfile
import textwrap
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
SCHEMA_DIR = ROOT / "schema"
SCHEMA_JSON = SCHEMA_DIR / "schema.json"
VERSION_FILE = SCHEMA_DIR / "VERSION"
SCHEMA_OUT = ROOT / "src" / "acp" / "schema.py"
STDIO_TYPE_LITERAL = 'Literal["2#-datamodel-code-generator-#-object-#-special-#"]'
MODELS_TO_REMOVE = [
"AgentClientProtocol",
"AgentClientProtocol1",
"AgentClientProtocol2",
"AgentClientProtocol3",
"AgentClientProtocol4",
"AgentClientProtocol5",
"AgentClientProtocol6",
"AgentClientProtocol7",
]
# Map of numbered classes produced by datamodel-code-generator to descriptive names.
# Keep this in sync with the Rust/TypeScript SDK nomenclature.
RENAME_MAP: dict[str, str] = {
"AgentResponse1": "AgentResponseMessage",
"AgentResponse2": "AgentErrorMessage",
"ClientResponse1": "ClientResponseMessage",
"ClientResponse2": "ClientErrorMessage",
"ContentBlock1": "TextContentBlock",
"ContentBlock2": "ImageContentBlock",
"ContentBlock3": "AudioContentBlock",
"ContentBlock4": "ResourceContentBlock",
"ContentBlock5": "EmbeddedResourceContentBlock",
"McpServer1": "HttpMcpServer",
"McpServer2": "SseMcpServer",
"McpServer3": "AcpMcpServer",
"RequestPermissionOutcome1": "DeniedOutcome",
"RequestPermissionOutcome2": "AllowedOutcome",
"AuthMethod1": "EnvVarAuthMethod",
"AuthMethod2": "TerminalAuthMethod",
"SessionConfigOption1": "SessionConfigOptionSelect",
"SessionConfigOption2": "SessionConfigOptionBoolean",
"SetSessionConfigOptionRequest1": "SetSessionConfigOptionBooleanRequest",
"SetSessionConfigOptionRequest2": "SetSessionConfigOptionSelectRequest",
"SessionUpdate1": "UserMessageChunk",
"SessionUpdate2": "AgentMessageChunk",
"SessionUpdate3": "AgentThoughtChunk",
"SessionUpdate4": "ToolCallStart",
"SessionUpdate5": "ToolCallProgress",
"SessionUpdate6": "AgentPlanUpdate",
"SessionUpdate7": "AgentPlanContentUpdate",
"SessionUpdate8": "AgentPlanRemovedUpdate",
"SessionUpdate9": "AvailableCommandsUpdate",
"SessionUpdate10": "CurrentModeUpdate",
"SessionUpdate11": "ConfigOptionUpdate",
"SessionUpdate12": "SessionInfoUpdate",
"SessionUpdate13": "UsageUpdate",
"PlanUpdateContent1": "PlanUpdateItems",
"PlanUpdateContent2": "PlanUpdateFile",
"PlanUpdateContent3": "PlanUpdateMarkdown",
"ToolCallContent1": "ContentToolCallContent",
"ToolCallContent2": "FileEditToolCallContent",
"ToolCallContent3": "TerminalToolCallContent",
"CreateElicitationRequest1": "CreateFormSessionElicitationRequest",
"CreateElicitationRequest2": "CreateFormRequestElicitationRequest",
"CreateElicitationRequest3": "CreateUrlSessionElicitationRequest",
"CreateElicitationRequest4": "CreateUrlRequestElicitationRequest",
"CreateElicitationRequest5": "CreateOtherElicitationRequest",
"CreateElicitationResponse1": "AcceptElicitationResponse",
"CreateElicitationResponse2": "DeclineElicitationResponse",
"CreateElicitationResponse3": "CancelElicitationResponse",
"CreateElicitationResponse4": "OtherElicitationResponse",
"ElicitationFormMode1": "ElicitationFormSessionMode",
"ElicitationFormMode2": "ElicitationFormRequestMode",
"ElicitationPropertySchema1": "ElicitationStringPropertySchema",
"ElicitationPropertySchema2": "ElicitationNumberPropertySchema",
"ElicitationPropertySchema3": "ElicitationIntegerPropertySchema",
"ElicitationPropertySchema4": "ElicitationBooleanPropertySchema",
"ElicitationPropertySchema5": "ElicitationMultiSelectPropertySchema",
"ElicitationPropertySchema6": "ElicitationOtherPropertySchema",
"MultiSelectItems1": "StringMultiSelectItems",
"MultiSelectItems2": "OtherMultiSelectItems",
"ElicitationUrlMode1": "ElicitationUrlSessionMode",
"ElicitationUrlMode2": "ElicitationUrlRequestMode",
"NesSuggestion1": "NesEditSuggestionVariant",
"NesSuggestion2": "NesJumpSuggestionVariant",
"NesSuggestion3": "NesRenameSuggestionVariant",
"NesSuggestion4": "NesSearchAndReplaceSuggestionVariant",
}
# Extensible ("custom or future") unions: known const-tagged variants plus a
# catch-all member tagged `"title": "other"`. _normalize_catchall_unions strips the
# discriminator and the catch-all's `not` clause so datamodel-codegen produces a plain
# union; the exclusion is restored at runtime by a field_validator injected into the
# catch-all class, so a malformed known variant fails instead of silently parsing as
# custom (mirrors the TypeScript SDK's excludeKnownTags). Maps union def name ->
# catch-all class name; the set is asserted against the schema in
# _validate_schema_alignment.
EXTENSIBLE_UNIONS: dict[str, str] = {
"CreateElicitationRequest": "CreateOtherElicitationRequest",
"CreateElicitationResponse": "OtherElicitationResponse",
"ElicitationPropertySchema": "ElicitationOtherPropertySchema",
"MultiSelectItems": "OtherMultiSelectItems",
}
ENUM_LITERAL_MAP: dict[str, tuple[str, ...]] = {
"PermissionOptionKind": (
"allow_once",
"allow_always",
"reject_once",
"reject_always",
),
"PlanEntryPriority": ("high", "medium", "low"),
"PlanEntryStatus": ("pending", "in_progress", "completed"),
"StopReason": ("end_turn", "max_tokens", "max_turn_requests", "refusal", "cancelled"),
"ToolCallStatus": ("pending", "in_progress", "completed", "failed"),
"ToolKind": ("read", "edit", "delete", "move", "search", "execute", "think", "fetch", "switch_mode", "other"),
}
# datamodel-code-generator 0.64 promotes referenced string enums to Enum classes.
# Keep the existing Python API, where these schema types are plain strings; the
# selected public fields below are narrowed back to the named Literal aliases.
STRING_ENUM_TYPES = (
*ENUM_LITERAL_MAP,
"ElicitationSchemaType",
"NesDiagnosticSeverity",
"NesRejectReason",
"NesTriggerKind",
"PositionEncodingKind",
"Role",
"StringFormat",
"TextDocumentSyncKind",
)
# Preserve RootModel classes that existed in the generated public surface before
# 0.64; other unreferenced RootModels are intermediates left after collapsing.
PUBLIC_ROOT_MODELS = {
"AgentResponse",
"ClientResponse",
"ElicitationContentValue",
"ElicitationFormMode",
"ElicitationUrlMode",
}
FIELD_TYPE_OVERRIDES: tuple[tuple[str, str, str, bool], ...] = (
("PermissionOption", "kind", "PermissionOptionKind", False),
("PlanEntry", "priority", "PlanEntryPriority", False),
("PlanEntry", "status", "PlanEntryStatus", False),
("PromptResponse", "stop_reason", "StopReason", False),
("ToolCall", "kind", "ToolKind", True),
("ToolCall", "status", "ToolCallStatus", True),
("ToolCallUpdate", "kind", "ToolKind", True),
("ToolCallUpdate", "status", "ToolCallStatus", True),
)
@dataclass(frozen=True)
class FieldValidatorInjection:
"""A generated field validator that should be appended to one schema class."""
class_name: str
field_name: str
method_name: str
argument_name: str
return_type: str
comment_lines: tuple[str, ...]
body_lines: tuple[str, ...]
def render(self) -> str:
lines = [
f'@field_validator("{self.field_name}", mode="before")',
"@classmethod",
f"def {self.method_name}(cls, {self.argument_name}: Any) -> {self.return_type}:",
]
lines.extend(f" # {line}" for line in self.comment_lines)
lines.extend(f" {line}" for line in self.body_lines)
return "\n".join(lines)
DEFAULT_VALUE_OVERRIDES: tuple[tuple[str, str, str], ...] = (
("AgentCapabilities", "mcp_capabilities", "McpCapabilities()"),
("AgentCapabilities", "session_capabilities", "SessionCapabilities()"),
(
"AgentCapabilities",
"prompt_capabilities",
"PromptCapabilities()",
),
("ClientCapabilities", "fs", "FileSystemCapabilities()"),
("ClientCapabilities", "terminal", "False"),
(
"InitializeRequest",
"client_capabilities",
"ClientCapabilities()",
),
(
"InitializeResponse",
"agent_capabilities",
"AgentCapabilities()",
),
)
# Classes that need a field_validator injected after generation.
CLASS_VALIDATOR_INJECTIONS: tuple[FieldValidatorInjection, ...] = (
FieldValidatorInjection(
class_name="InitializeRequest",
field_name="protocol_version",
method_name="_coerce_protocol_version",
argument_name="value",
return_type="int",
comment_lines=(
'Some clients (e.g. Zed) send a date string like "2024-11-05" instead',
"of an integer. The Rust SDK treats legacy strings as version 0; this",
"SDK maps unparsable values to 1 so the connection is not rejected.",
"See: https://github.com/agentclientprotocol/rust-sdk/blob/main/crates/agent-client-protocol-schema/src/version.rs",
),
body_lines=(
"if isinstance(value, int):",
" return value",
"try:",
" return int(value)",
"except (TypeError, ValueError):",
" return 1",
),
),
)
@dataclass(frozen=True)
class _ProcessingStep:
"""A named transformation applied to the generated schema content."""
name: str
apply: Callable[[str], str]
def main() -> None:
generate_schema()
def generate_schema() -> None:
if not SCHEMA_JSON.exists():
print(
"Schema file missing. Ensure schema/schema.json exists (run gen_all.py --version to download).",
file=sys.stderr,
)
sys.exit(1)
with tempfile.TemporaryDirectory() as tmp_dir:
codegen_input = Path(tmp_dir) / "schema.codegen.json"
codegen_input.write_text(json.dumps(_preprocess_schema_for_codegen(_load_schema()), indent=2), encoding="utf-8")
cmd = [
sys.executable,
"-m",
"datamodel_code_generator",
"--input",
str(codegen_input),
"--input-file-type",
"jsonschema",
"--output",
str(SCHEMA_OUT),
"--target-python-version",
"3.12",
"--collapse-root-models",
"--output-model-type",
"pydantic_v2.BaseModel",
"--no-use-specialized-enum",
"--no-use-standard-collections",
"--no-use-union-operator",
"--type-overrides",
json.dumps(dict.fromkeys(STRING_ENUM_TYPES, "builtins.str")),
"--formatters",
"black",
"isort",
"--use-annotated",
"--use-field-description",
"--snake-case-field",
]
subprocess.check_call(cmd) # noqa: S603
warnings = postprocess_generated_schema(SCHEMA_OUT)
for warning in warnings:
print(f"Warning: {warning}", file=sys.stderr)
def _load_schema() -> dict[str, Any]:
return json.loads(SCHEMA_JSON.read_text(encoding="utf-8"))
COMBINATOR_KEYS = ("oneOf", "anyOf")
def _preprocess_schema_for_codegen(schema: dict[str, Any]) -> dict[str, Any]:
schema = _normalize_catchall_unions(schema)
defs = schema.get("$defs", {})
return _distribute_composed_object_schemas(schema, defs)
def _normalize_catchall_unions(node: Any) -> Any:
# ACP "custom or future" unions include a member tagged `"title": "other"` whose
# discriminator (type/mode/action) is a free-form string. datamodel-codegen cannot
# put that in a discriminated union, so it emits `#-special-#` placeholder literals.
# Drop the discriminator (the union is then validated structurally) and collapse the
# catch-all to a permissive object so unknown variants round-trip their raw payload.
if isinstance(node, list):
return [_normalize_catchall_unions(item) for item in node]
if not isinstance(node, dict):
return node
transformed = {key: _normalize_catchall_unions(value) for key, value in node.items()}
for combinator in COMBINATOR_KEYS:
members = transformed.get(combinator)
if not isinstance(members, list):
continue
if not any(isinstance(member, dict) and member.get("title") == "other" for member in members):
continue
transformed.pop("discriminator", None)
transformed[combinator] = [
_collapse_catchall_member(member) if isinstance(member, dict) and member.get("title") == "other" else member
for member in members
]
return transformed
def _collapse_catchall_member(member: dict[str, Any]) -> dict[str, Any]:
collapsed: dict[str, Any] = {"type": "object", "additionalProperties": True}
for key in ("title", "description", "properties", "required"):
if key in member:
collapsed[key] = member[key]
return collapsed
def _distribute_composed_object_schemas(node: Any, defs: dict[str, Any]) -> Any:
if isinstance(node, list):
return [_distribute_composed_object_schemas(item, defs) for item in node]
if not isinstance(node, dict):
return node
transformed = {key: _distribute_composed_object_schemas(value, defs) for key, value in node.items()}
for combinator in COMBINATOR_KEYS:
if combinator not in transformed or "properties" not in transformed:
continue
result = {combinator: _expand_composed_object_variants(transformed, defs)}
for key in ("title", "description", "discriminator"):
if key in transformed:
result[key] = transformed[key]
return result
return transformed
def _expand_composed_object_variants(node: dict[str, Any], defs: dict[str, Any]) -> list[Any]:
for combinator in COMBINATOR_KEYS:
if combinator not in node or "properties" not in node:
continue
common_schema = _without_combinators(node)
expanded: list[Any] = []
for option in node[combinator]:
for variant in _expand_allof_union_refs(option, defs):
expanded.append(_merge_object_schema(common_schema, variant) if isinstance(variant, dict) else variant)
return expanded
return _expand_allof_union_refs(node, defs)
def _expand_allof_union_refs(node: Any, defs: dict[str, Any]) -> list[Any]:
if not isinstance(node, dict):
return [node]
variants = [{key: copy.deepcopy(value) for key, value in node.items() if key != "allOf"}]
for item in node.get("allOf", []):
ref_name = _local_def_ref_name(item.get("$ref")) if isinstance(item, dict) else None
ref_schema = defs.get(ref_name) if ref_name else None
if isinstance(ref_schema, dict) and any(key in ref_schema for key in COMBINATOR_KEYS):
ref_variants = _expand_composed_object_variants(ref_schema, defs)
else:
ref_variants = [item]
variants = [
_merge_object_schema(variant, ref_variant) if isinstance(ref_variant, dict) else variant
for variant in variants
for ref_variant in ref_variants
]
return variants
def _without_combinators(node: dict[str, Any]) -> dict[str, Any]:
return {
key: copy.deepcopy(value)
for key, value in node.items()
if key not in COMBINATOR_KEYS and key != "discriminator"
}
def _local_def_ref_name(ref: Any) -> str | None:
if isinstance(ref, str) and ref.startswith("#/$defs/"):
return ref.rsplit("/", 1)[-1]
return None
def _pop_ref_as_allof(schema: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]:
schema = copy.deepcopy(schema)
if "$ref" not in schema:
return schema, []
return schema, [{"$ref": schema.pop("$ref")}]
def _merge_object_schema(left: dict[str, Any], right: dict[str, Any]) -> dict[str, Any]:
left, left_refs = _pop_ref_as_allof(left)
right, right_refs = _pop_ref_as_allof(right)
merged: dict[str, Any] = {}
for key in set(left) | set(right):
if key in COMBINATOR_KEYS or key in {"allOf", "discriminator"}:
continue
if key == "properties":
merged[key] = {**left.get(key, {}), **right.get(key, {})}
elif key == "required":
required = []
for item in left.get(key, []) + right.get(key, []):
if item not in required:
required.append(item)
if required:
merged[key] = required
elif key in right:
merged[key] = right[key]
else:
merged[key] = left[key]
all_of = left_refs + left.get("allOf", []) + right_refs + right.get("allOf", [])
if all_of:
merged["allOf"] = all_of
return merged
def _required_nullable_fields(schema: dict[str, Any]) -> dict[str, list[str]]:
defs = schema.get("$defs", {})
fields: dict[str, list[str]] = {}
for class_name, definition in defs.items():
if not isinstance(definition, dict):
continue
required = set(definition.get("required", []))
if not required:
continue
properties = definition.get("properties", {})
nullable_fields = [
_schema_field_name(property_name)
for property_name in sorted(required)
if _schema_allows_null(properties.get(property_name), defs)
]
if nullable_fields:
fields[class_name] = nullable_fields
return fields
def _schema_allows_null(node: Any, defs: dict[str, Any]) -> bool:
if not isinstance(node, dict):
return False
schema_type = node.get("type")
if schema_type == "null" or (isinstance(schema_type, list) and "null" in schema_type):
return True
for combinator in COMBINATOR_KEYS:
if any(_schema_allows_null(option, defs) for option in node.get(combinator, [])):
return True
ref_name = _local_def_ref_name(node.get("$ref"))
if ref_name is not None:
return _schema_allows_null(defs.get(ref_name), defs)
return any(_schema_allows_null(option, defs) for option in node.get("allOf", []))
def _schema_field_name(name: str) -> str:
if name.startswith("_"):
return "field" + name
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
def postprocess_generated_schema(output_path: Path) -> list[str]:
if not output_path.exists():
raise RuntimeError(f"Generated schema not found at {output_path}")
raw_content = output_path.read_text(encoding="utf-8")
header_block = _build_header_block()
content = _strip_existing_header(raw_content)
# Type overrides for builtins are rendered as imports in 0.64, but the
# annotations should continue to use Python's builtin `str` directly.
content = content.replace("from builtins import str\n", "")
content = _remove_unused_models(content)
content, leftover_classes = _rename_numbered_models(content)
processing_steps: tuple[_ProcessingStep, ...] = (
_ProcessingStep("apply field overrides", _apply_field_overrides),
_ProcessingStep("apply default overrides", _apply_default_overrides),
_ProcessingStep("restore required nullable fields", _restore_required_nullable_fields),
_ProcessingStep("ensure custom BaseModel", _ensure_custom_base_model),
_ProcessingStep("enable RootModel attribute docstrings", _enable_root_model_attribute_docstrings),
_ProcessingStep("inject field validators", _inject_field_validators),
_ProcessingStep("inject deserialize defaults", _inject_deserialize_defaults),
_ProcessingStep("inject schema aliases", _inject_schema_aliases),
)
for step in processing_steps:
content = step.apply(content)
missing_targets = _find_missing_targets(content)
content = _inject_enum_aliases(content)
content = _remove_unreferenced_root_models(content)
final_content = header_block + content.rstrip() + "\n"
if not final_content.endswith("\n"):
final_content += "\n"
output_path.write_text(final_content, encoding="utf-8")
warnings: list[str] = []
if leftover_classes:
warnings.append(
"Unrenamed schema models detected: "
+ ", ".join(leftover_classes)
+ ". Update RENAME_MAP in scripts/gen_schema.py."
)
if missing_targets:
warnings.append(
"Renamed schema targets not found after generation: "
+ ", ".join(sorted(missing_targets))
+ ". Check RENAME_MAP or upstream schema changes."
)
warnings.extend(_validate_schema_alignment())
return warnings
def _build_header_block() -> str:
header_lines = ["# Generated from schema/schema.json. Do not edit by hand."]
if VERSION_FILE.exists():
ref = VERSION_FILE.read_text(encoding="utf-8").strip()
if ref:
header_lines.append(f"# Schema ref: {ref}")
return "\n".join(header_lines) + "\n\n"
def _strip_existing_header(content: str) -> str:
existing_header = re.match(r"(#.*\n)+", content)
if existing_header:
return content[existing_header.end() :].lstrip("\n")
return content.lstrip("\n")
def _rename_numbered_models(content: str) -> tuple[str, list[str]]:
renamed = content
for old, new in sorted(RENAME_MAP.items(), key=lambda item: len(item[0]), reverse=True):
if re.search(rf"\b{re.escape(new)}\b", renamed) is not None:
renamed = re.sub(rf"\b{re.escape(new)}\b", f"_{new}", renamed)
pattern = re.compile(rf"\b{re.escape(old)}\b")
renamed = pattern.sub(new, renamed)
leftover_class_pattern = re.compile(r"^class (\w+\d+)\(", re.MULTILINE)
leftover_classes = sorted(set(leftover_class_pattern.findall(renamed)))
return renamed, leftover_classes
def _find_missing_targets(content: str) -> list[str]:
missing: list[str] = []
for new_name in RENAME_MAP.values():
pattern = re.compile(rf"^class {re.escape(new_name)}\(", re.MULTILINE)
if not pattern.search(content):
missing.append(new_name)
return missing
def _validate_schema_alignment() -> list[str]:
warnings: list[str] = []
if not SCHEMA_JSON.exists():
warnings.append("schema/schema.json missing; unable to validate enum aliases.")
return warnings
try:
schema_enums = _load_schema_enum_literals()
except json.JSONDecodeError as exc:
warnings.append(f"Failed to parse schema/schema.json: {exc}")
return warnings
for enum_name, expected_values in ENUM_LITERAL_MAP.items():
schema_values = schema_enums.get(enum_name)
if schema_values is None:
warnings.append(
f"Enum '{enum_name}' not found in schema.json; update ENUM_LITERAL_MAP or investigate schema changes."
)
continue
if tuple(schema_values) != expected_values:
warnings.append(
f"Enum mismatch for '{enum_name}': schema.json -> {schema_values}, generated aliases -> {expected_values}"
)
detected_unions = _detect_extensible_unions()
if detected_unions != set(EXTENSIBLE_UNIONS):
warnings.append(
f"Extensible union drift: schema defines {sorted(detected_unions)}, "
f"EXTENSIBLE_UNIONS lists {sorted(EXTENSIBLE_UNIONS)}. Update EXTENSIBLE_UNIONS, the "
"RENAME_MAP catch-all names, and the alias template together."
)
return warnings
def _detect_extensible_unions() -> set[str]:
defs = _load_schema().get("$defs", {})
detected: set[str] = set()
for name, definition in defs.items():
if not isinstance(definition, dict) or "discriminator" not in definition:
continue
members = definition.get("anyOf") or definition.get("oneOf") or []
if any(isinstance(member, dict) and member.get("title") == "other" for member in members):
detected.add(name)
return detected
def _load_schema_enum_literals() -> dict[str, tuple[str, ...]]:
schema_data = json.loads(SCHEMA_JSON.read_text(encoding="utf-8"))
defs = schema_data.get("$defs", {})
enum_literals: dict[str, tuple[str, ...]] = {}
for name, definition in defs.items():
values: list[str] = []
if "enum" in definition:
values = [str(item) for item in definition["enum"]]
elif "oneOf" in definition:
values = [
str(option["const"])
for option in definition.get("oneOf", [])
if isinstance(option, dict) and "const" in option
]
if values:
enum_literals[name] = tuple(values)
return enum_literals
def _ensure_custom_base_model(content: str) -> str:
if "class BaseModel(_BaseModel):" in content:
return content
lines = content.splitlines()
for idx, line in enumerate(lines):
if not line.startswith("from pydantic import "):
continue
imports = [part.strip() for part in line[len("from pydantic import ") :].split(",")]
has_alias = any(part == "BaseModel as _BaseModel" for part in imports)
has_config = any(part == "ConfigDict" for part in imports)
new_imports = []
for part in imports:
if part == "BaseModel":
new_imports.append("BaseModel as _BaseModel")
has_alias = True
else:
new_imports.append(part)
if not has_alias:
new_imports.append("BaseModel as _BaseModel")
if not has_config:
new_imports.append("ConfigDict")
lines[idx] = "from pydantic import " + ", ".join(new_imports)
to_insert = textwrap.dedent("""\
class BaseModel(_BaseModel):
model_config = ConfigDict(populate_by_name=True, use_attribute_docstrings=True)
def __getattr__(self, item: str) -> Any:
if item.lower() != item:
snake_cased = "".join("_" + c.lower() if c.isupper() and i > 0 else c.lower() for i, c in enumerate(item))
return getattr(self, snake_cased)
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{item}'")
""")
insert_idx = idx + 1
lines.insert(insert_idx, "")
for offset, line in enumerate(to_insert.splitlines(), 1):
lines.insert(insert_idx + offset, line)
break
return "\n".join(lines) + "\n"
def _enable_root_model_attribute_docstrings(content: str) -> str:
lines = content.splitlines(keepends=True)
tree = ast.parse(content)
insertion_points = [
node.body[0].lineno - 1
for node in tree.body
if isinstance(node, ast.ClassDef)
and node.body
and any(
isinstance(base, ast.Subscript) and isinstance(base.value, ast.Name) and base.value.id == "RootModel"
for base in node.bases
)
]
for line_index in reversed(insertion_points):
lines.insert(line_index, " model_config = ConfigDict(use_attribute_docstrings=True)\n\n")
return "".join(lines)
def _ensure_pydantic_import(content: str, name: str) -> str:
"""Add *name* to the ``from pydantic import ...`` line if not already present."""
lines = content.splitlines()
for idx, line in enumerate(lines):
if not line.startswith("from pydantic import "):
continue
imports = [part.strip() for part in line[len("from pydantic import ") :].split(",")]
if name not in imports:
imports.append(name)
lines[idx] = "from pydantic import " + ", ".join(imports)
return "\n".join(lines) + "\n"
return content
def _extensible_union_excluded_tags(union_def: dict[str, Any], discriminator: str) -> tuple[str, ...]:
members = union_def.get("anyOf") or union_def.get("oneOf") or []
other = next((member for member in members if isinstance(member, dict) and member.get("title") == "other"), None)
if other is None:
return ()
tags: list[str] = []
for excluded in other.get("not", {}).get("anyOf", []):
const = excluded.get("properties", {}).get(discriminator, {}).get("const")
if isinstance(const, str) and const not in tags:
tags.append(const)
return tuple(tags)
def _catchall_exclusion_injections() -> list[FieldValidatorInjection]:
defs = _load_schema().get("$defs", {})
injections: list[FieldValidatorInjection] = []
for union_name, catchall_class in EXTENSIBLE_UNIONS.items():
union_def = defs.get(union_name)
if not isinstance(union_def, dict):
continue
discriminator = union_def.get("discriminator", {}).get("propertyName")
if not discriminator:
continue
tags = _extensible_union_excluded_tags(union_def, discriminator)
if not tags:
continue
field = _schema_field_name(discriminator)
injections.append(
FieldValidatorInjection(
class_name=catchall_class,
field_name=field,
method_name=f"_reject_known_{field}",
argument_name="value",
return_type="Any",
comment_lines=(
"Restore the schema's `not` clause dropped for codegen: reject the known",
"variants' discriminator values so a malformed known variant fails instead",
"of silently parsing as this catch-all.",
),
body_lines=(
f"if value in {tags!r}:",
f' raise ValueError("{field} value is reserved by a known variant")',
"return value",
),
)
)
return injections
def _inject_field_validators(content: str) -> str:
"""Inject field_validator methods for CLASS_VALIDATOR_INJECTIONS and catch-all exclusions."""
for injection in (*CLASS_VALIDATOR_INJECTIONS, *_catchall_exclusion_injections()):
content = _ensure_pydantic_import(content, "field_validator")
class_pattern = re.compile(
rf"(class {injection.class_name}\(BaseModel\):)(.*?)(?=\nclass |\Z)",
re.DOTALL,
)
def _append_validator(
match: re.Match[str],
_injection: FieldValidatorInjection = injection,
) -> str:
header, block = match.group(1), match.group(2)
indented = "\n" + textwrap.indent(_injection.render(), " ")
return header + block + indented + "\n"
content, count = class_pattern.subn(_append_validator, content, count=1)
if count == 0:
print(
f"Warning: class {injection.class_name} not found for validator injection",
file=sys.stderr,
)
return content
def _inject_deserialize_defaults(content: str) -> str:
defs = _load_schema().get("$defs", {})
# `_meta` carries x-deserialize-default-on-error on almost every model; handle it once
# on the shared BaseModel with check_fields=False so every subclass inherits the salvage.
meta_validator = (
'@field_validator("field_meta", mode="wrap", check_fields=False)\n'
"@classmethod\n"
"def _salvage_meta_on_error(cls, value: Any, handler: Any) -> Any:\n"
" return salvage_on_error(value, handler, lambda: None)\n"
)
content, count = _append_class_method(content, r"class BaseModel\(_BaseModel\):", meta_validator)
if count == 0:
print("Warning: custom BaseModel not found for _meta salvage injection", file=sys.stderr)
for class_name, definition in defs.items():
if not isinstance(definition, dict):
continue
salvage_groups, skip_fields = _deserialize_field_specs(definition)
methods: list[str] = []
for index, (fallback, fields) in enumerate(sorted(salvage_groups.items())):
arguments = ", ".join(f'"{field}"' for field in sorted(fields))
methods.append(
f'@field_validator({arguments}, mode="wrap")\n'
"@classmethod\n"
f"def _salvage_on_error_{index}(cls, value: Any, handler: Any) -> Any:\n"
f" return salvage_on_error(value, handler, {fallback})\n"
)
for index, field in enumerate(sorted(skip_fields)):
methods.append(
f'@field_validator("{field}", mode="wrap")\n'
"@classmethod\n"
f"def _skip_invalid_items_{index}(cls, value: Any, handler: Any) -> Any:\n"
" return skip_invalid_items(value, handler)\n"
)
# A plain object $def renders as `class Name(BaseModel)` (or `_Name` after a
# collision rename). A union $def has no class of its own; its common properties
# distribute to the member variant classes, so target those instead.
targets = [rf"class _?{re.escape(class_name)}\(BaseModel\):"]
members = _union_member_classes(class_name)
if members:
targets = [rf"class {re.escape(member)}\(\w+\):" for member in members]
for method in methods:
for target in targets:
content, count = _append_class_method(content, target, method)
if count == 0:
print(f"Warning: no class matched {target!r} for deserialize injection", file=sys.stderr)
content = _ensure_pydantic_import(content, "field_validator")
return _ensure_deserialize_import(content)
def _union_member_classes(union_name: str) -> list[str]:
return [new for old, new in RENAME_MAP.items() if re.fullmatch(rf"{re.escape(union_name)}\d+", old)]
def _deserialize_field_specs(definition: dict[str, Any]) -> tuple[dict[str, list[str]], list[str]]:
"""Return ({fallback_expr: [field, ...]}, [skip_field, ...]) for a $def. `_meta` is handled
on the shared BaseModel and excluded here."""
required = set(definition.get("required", []))
salvage: dict[str, list[str]] = {}
skip: list[str] = []
for prop_name, prop in definition.get("properties", {}).items():
if not isinstance(prop, dict) or prop_name == "_meta":
continue
field = _schema_field_name(prop_name)
if prop.get("x-deserialize-skip-invalid-items"):
skip.append(field)
elif prop.get("x-deserialize-default-on-error"):
salvage.setdefault(_fallback_expression(prop, prop_name in required), []).append(field)
return salvage, skip
def _fallback_expression(prop: dict[str, Any], is_required: bool) -> str:
if "default" in prop:
return f"lambda: {prop['default']!r}"
if _is_array_schema(prop) and (is_required or not _schema_allows_null(prop, {})):
return "lambda: []"
return "lambda: None"
def _is_array_schema(prop: dict[str, Any]) -> bool:
prop_type = prop.get("type")
if prop_type == "array" or (isinstance(prop_type, list) and "array" in prop_type):
return True
return "items" in prop
def _append_class_method(content: str, header_pattern: str, method_text: str) -> tuple[str, int]:
pattern = re.compile(rf"({header_pattern})(.*?)(?=\nclass |\Z)", re.DOTALL)
def _append(match: re.Match[str]) -> str:
indented = "\n" + textwrap.indent(method_text, " ")
return match.group(1) + match.group(2) + indented + "\n"
return pattern.subn(_append, content, count=1)
def _ensure_deserialize_import(content: str) -> str:
# Absolute import (not relative): gen_signature.py loads schema.py as a standalone
# module with no package context, where `from ._deserialize` cannot resolve.
statement = "from acp._deserialize import salvage_on_error, skip_invalid_items"
if statement in content:
return content
lines = content.splitlines()
for idx, line in enumerate(lines):
if line.startswith("from pydantic import "):
lines.insert(idx + 1, statement)
return "\n".join(lines) + "\n"
return content
def _inject_schema_aliases(content: str) -> str:
if "CreateElicitationRequest = Union[" in content:
return content
aliases = textwrap.dedent("""\
ElicitationMode = Union[
ElicitationFormSessionMode,
ElicitationFormRequestMode,
ElicitationUrlSessionMode,
ElicitationUrlRequestMode,
]
CreateFormElicitationRequest = Union[
CreateFormSessionElicitationRequest,
CreateFormRequestElicitationRequest,
]
CreateUrlElicitationRequest = Union[
CreateUrlSessionElicitationRequest,
CreateUrlRequestElicitationRequest,
]
CreateElicitationRequest = Union[
CreateFormElicitationRequest,
CreateUrlElicitationRequest,
CreateOtherElicitationRequest,
]
CreateElicitationResponse = Union[
AcceptElicitationResponse,
DeclineElicitationResponse,
CancelElicitationResponse,
OtherElicitationResponse,
]
""")
pattern = re.compile(
r"^(class CreateFormRequestElicitationRequest\([\s\S]*?\):[\s\S]*?)(?=^class \w+\(|\Z)",
re.MULTILINE,
)
content, count = pattern.subn(lambda match: match.group(1).rstrip() + "\n\n" + aliases + "\n", content, count=1)
if count == 0:
print("Warning: failed to insert schema aliases", file=sys.stderr)
return content
def _restore_required_nullable_fields(content: str, schema: dict[str, Any] | None = None) -> str:
schema = _load_schema() if schema is None else schema
for class_name, field_names in _required_nullable_fields(schema).items():
class_pattern = re.compile(
rf"(class {re.escape(class_name)}\([^)]*\):)(.*?)(?=\nclass |\Z)",
re.DOTALL,
)
def restore_block(match: re.Match[str], _field_names: list[str] = field_names) -> str:
header, block = match.group(1), match.group(2)
for field_name in _field_names:
field_patterns = (
re.compile(rf"(\n\s+{re.escape(field_name)}:[^\n]*?)\s*=\s*None(?=\n)"),
re.compile(rf"(\n\s+{re.escape(field_name)}:[^\n]*\[\s*\n[\s\S]*?\n\s+\]\s*)=\s*None"),
)
for field_pattern in field_patterns:
block, count = field_pattern.subn(r"\1", block, count=1)
if count:
break
return header + block
content = class_pattern.sub(restore_block, content, count=1)
return content
def _apply_field_overrides(content: str) -> str:
for class_name, field_name, new_type, optional in FIELD_TYPE_OVERRIDES:
old_type = "Optional[str]" if optional else "str"
replacement_type = f"Optional[{new_type}]" if optional else new_type
pattern = re.compile(
rf"(class {re.escape(class_name)}\(BaseModel\):.*?\n\s+{re.escape(field_name)}:\s+"
rf"(?:Annotated\[\s*)?){re.escape(old_type)}(?=\s*(?:,|=|\n))",
re.DOTALL,
)
content, count = pattern.subn(rf"\g<1>{replacement_type}", content, count=1)
if count == 0:
print(
f"Warning: failed to apply type override for {class_name}.{field_name} -> {new_type}",
file=sys.stderr,
)
return content
def _apply_default_overrides(content: str) -> str: