Skip to content

schema_reference

Class info

Classes

Name Children Inherits
Conformance
aclientp.schema_reference
``conformance.toml``: renames and known differences of a pinned reference.
    EnumDef
    aclientp.schema_reference
    A string enum of the upstream schema.
      FieldInfo
      aclientp.schema_reference
      How a model field behaves on the wire.
        Finding
        aclientp.schema_reference
        One difference between the models and the reference.
          OurSchema
          aclientp.schema_reference
          Models and module-level aliases (unions, ``Literal`` enums) of a model package.
            Reference
            aclientp.schema_reference
            A pinned upstream schema release.
              ReferenceChanges
              aclientp.schema_reference
              What changed in a reference implementation since its pinned commit.
                ReferenceImplementation
                aclientp.schema_reference
                An upstream implementation pinned by commit (``schema/references.toml``).
                  Report
                  aclientp.schema_reference
                  Findings of a check, split against the known differences.
                    Shape
                    aclientp.schema_reference
                    An object shape of the upstream schema: a named definition or a union variant.
                      UpstreamCommit
                      aclientp.schema_reference
                      A commit of a reference implementation.
                        UpstreamSchema
                        aclientp.schema_reference
                        The parts of an upstream schema the checks compare.

                          🛈 DocStrings

                          Pinned upstream ACP schema references: syncing and conformance checks.

                          The hand-written models in :mod:aclientp.schema follow the upstream ACP JSON schema (agentclientprotocol/agent-client-protocol). Instead of generating code, the repository pins one upstream schema release per protocol version and checks the models against it:

                          • schema/v{N}/VERSION: upstream git tag, e.g. schema-v1.33.0
                          • schema/v{N}/schema.unstable.json and meta.unstable.json: the vendored upstream files of that tag (the unstable schema is a superset of the stable one)
                          • schema/v{N}/conformance.toml: renames and known, documented differences

                          Commands (uv run python -m aclientp.schema_reference <command>):

                          • latest: show the pinned and the newest upstream tag
                          • sync [--tag TAG] [--dry-run]: download a tag (default: newest), print the schema changelog against the pinned one, and update the pin
                          • check: compare the models with the pinned schema
                          • refs [--update NAME [--commit SHA]]: show what changed in the pinned reference implementations (schema/references.toml) since their pinned commit, or move a pin

                          CONSTRAINT_KEYS module-attribute

                          CONSTRAINT_KEYS = {
                              "minimum": "ge",
                              "maximum": "le",
                              "exclusiveMinimum": "gt",
                              "exclusiveMaximum": "lt",
                              "minLength": "min_length",
                              "maxLength": "max_length",
                              "minItems": "min_length",
                              "maxItems": "max_length",
                          }
                          

                          JSON schema keywords and the pydantic constraints they correspond to.

                          METHOD_GROUPS module-attribute

                          METHOD_GROUPS = {
                              "agentMethods": "AgentMethod",
                              "clientMethods": "ClientMethod",
                              "protocolMethods": "ProtocolMethod",
                              "proxyMethods": "ProxyMethod",
                          }
                          

                          meta.unstable.json method groups and the Literal aliases mirroring them.

                          MISSING_KINDS module-attribute

                          MISSING_KINDS = ('missing-shape:', 'missing-enum:', 'missing-method:')
                          

                          Finding kinds that allow_missing accepts.

                          MODEL_PACKAGES module-attribute

                          MODEL_PACKAGES: dict[int, str] = {1: 'aclientp.schema', 2: 'aclientp.schema.v2'}
                          

                          Package holding the hand-written models of each protocol version.

                          Conformance dataclass

                          conformance.toml: renames and known differences of a pinned reference.

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class Conformance:
                              """``conformance.toml``: renames and known differences of a pinned reference."""
                          
                              renames: dict[str, str] = field(default_factory=dict)
                              """Upstream definition name to our model name."""
                          
                              known: dict[str, str] = field(default_factory=dict)
                              """Finding id to the reason the difference is accepted."""
                          
                              check_nullability: bool = False
                              """Compare which fields accept ``null``. For model packages that send ``None`` as
                              ``null`` and leave out ``MISSING`` fields (v2), not for ``exclude_none`` ones (v1)."""
                          
                              check_parse_nullability: bool = False
                              """Report fields where upstream allows ``null`` but the model rejects ``None``
                              (valid messages fail to parse). Implied by ``check_nullability``; for packages
                              that never send ``null`` (v1)."""
                          
                              check_constraints: bool = False
                              """Compare numeric and length constraints (``minimum``, ``minItems``, ...)."""
                          
                              allow_missing: bool = False
                              """Accept upstream shapes, enums and methods without a counterpart yet, while a
                              model package is being written. Fields of the shapes that exist are still checked."""
                          
                              @classmethod
                              def load(cls, path: UPath) -> Conformance:
                                  """Read ``conformance.toml``; a missing file means no renames or differences."""
                                  if not path.exists():
                                      return cls()
                                  data = tomllib.loads(path.read_text("utf-8"))
                                  return cls(
                                      dict(data.get("renames", {})),
                                      dict(data.get("known", {})),
                                      bool(data.get("check_nullability", False)),
                                      bool(data.get("check_parse_nullability", False)),
                                      bool(data.get("check_constraints", False)),
                                      bool(data.get("allow_missing", False)),
                                  )
                          

                          allow_missing class-attribute instance-attribute

                          allow_missing: bool = False
                          

                          Accept upstream shapes, enums and methods without a counterpart yet, while a model package is being written. Fields of the shapes that exist are still checked.

                          check_constraints class-attribute instance-attribute

                          check_constraints: bool = False
                          

                          Compare numeric and length constraints (minimum, minItems, ...).

                          check_nullability class-attribute instance-attribute

                          check_nullability: bool = False
                          

                          Compare which fields accept null. For model packages that send None as null and leave out MISSING fields (v2), not for exclude_none ones (v1).

                          check_parse_nullability class-attribute instance-attribute

                          check_parse_nullability: bool = False
                          

                          Report fields where upstream allows null but the model rejects None (valid messages fail to parse). Implied by check_nullability; for packages that never send null (v1).

                          known class-attribute instance-attribute

                          known: dict[str, str] = field(default_factory=dict)
                          

                          Finding id to the reason the difference is accepted.

                          renames class-attribute instance-attribute

                          renames: dict[str, str] = field(default_factory=dict)
                          

                          Upstream definition name to our model name.

                          load classmethod

                          load(path: UPath) -> Conformance
                          

                          Read conformance.toml; a missing file means no renames or differences.

                          Source code in src/aclientp/schema_reference.py
                          @classmethod
                          def load(cls, path: UPath) -> Conformance:
                              """Read ``conformance.toml``; a missing file means no renames or differences."""
                              if not path.exists():
                                  return cls()
                              data = tomllib.loads(path.read_text("utf-8"))
                              return cls(
                                  dict(data.get("renames", {})),
                                  dict(data.get("known", {})),
                                  bool(data.get("check_nullability", False)),
                                  bool(data.get("check_parse_nullability", False)),
                                  bool(data.get("check_constraints", False)),
                                  bool(data.get("allow_missing", False)),
                              )
                          

                          EnumDef dataclass

                          A string enum of the upstream schema.

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class EnumDef:
                              """A string enum of the upstream schema."""
                          
                              name: str
                              values: frozenset[str]
                              open: bool
                              """Whether other strings are allowed too."""
                          

                          open instance-attribute

                          open: bool
                          

                          Whether other strings are allowed too.

                          FieldInfo dataclass

                          How a model field behaves on the wire.

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class FieldInfo:
                              """How a model field behaves on the wire."""
                          
                              required: bool
                              """The field must be present when parsing."""
                          
                              omittable: bool
                              """The field can be left out when serializing: optional with a ``None`` or
                              ``MISSING`` default."""
                          
                              accepts_none: bool
                              """The annotation allows ``None`` (sent as ``null`` unless excluded)."""
                          
                              constraints: dict[str, float]
                              """Numeric and length constraints, e.g. ``{"ge": 1}``."""
                          

                          accepts_none instance-attribute

                          accepts_none: bool
                          

                          The annotation allows None (sent as null unless excluded).

                          constraints instance-attribute

                          constraints: dict[str, float]
                          

                          Numeric and length constraints, e.g. {"ge": 1}.

                          omittable instance-attribute

                          omittable: bool
                          

                          The field can be left out when serializing: optional with a None or MISSING default.

                          required instance-attribute

                          required: bool
                          

                          The field must be present when parsing.

                          Finding dataclass

                          One difference between the models and the reference.

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class Finding:
                              """One difference between the models and the reference."""
                          
                              id: str
                              """Stable id, e.g. ``missing-field:ToolCallUpdate.name``; key in ``conformance.toml``."""
                          
                              detail: str
                          

                          id instance-attribute

                          id: str
                          

                          Stable id, e.g. missing-field:ToolCallUpdate.name; key in conformance.toml.

                          OurSchema dataclass

                          Models and module-level aliases (unions, Literal enums) of a model package.

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class OurSchema:
                              """Models and module-level aliases (unions, ``Literal`` enums) of a model package."""
                          
                              models: dict[str, type[BaseModel]]
                              aliases: dict[str, object]
                          
                              @classmethod
                              def load(cls, package_name: str) -> OurSchema:
                                  """Collect models and aliases from the direct modules of ``package_name``."""
                                  package = importlib.import_module(package_name)
                                  models: dict[str, type[BaseModel]] = {}
                                  aliases: dict[str, object] = {}
                                  for info in pkgutil.iter_modules(package.__path__):
                                      if info.ispkg:
                                          continue
                                      module = importlib.import_module(f"{package_name}.{info.name}")
                                      for name, obj in vars(module).items():
                                          if inspect.isclass(obj):
                                              if issubclass(obj, BaseModel) and obj.__module__ == module.__name__:
                                                  models[name] = obj
                                          elif not name.startswith("_") and _is_type_alias(obj):
                                              aliases.setdefault(name, obj)
                                  return cls(models, aliases)
                          
                              def union_members(self, name: str) -> list[type[BaseModel]]:
                                  """Models of the union alias ``name`` (empty if there is none)."""
                                  alias = self.aliases.get(name)
                                  return [] if alias is None else [m for m in _flatten(alias) if _is_model(m)]
                          
                              def literal_values(self, name: str) -> tuple[frozenset[str], bool] | None:
                                  """Values of the ``Literal`` alias ``name``, and whether it also allows ``str``."""
                                  alias = self.aliases.get(name)
                                  if alias is None:
                                      return None
                                  members = list(_flatten(alias))
                                  values = {arg for m in members if get_origin(m) is Literal for arg in get_args(m)}
                                  if not values:
                                      return None
                                  return frozenset(str(v) for v in values), str in members
                          

                          literal_values

                          literal_values(name: str) -> tuple[frozenset[str], bool] | None
                          

                          Values of the Literal alias name, and whether it also allows str.

                          Source code in src/aclientp/schema_reference.py
                          def literal_values(self, name: str) -> tuple[frozenset[str], bool] | None:
                              """Values of the ``Literal`` alias ``name``, and whether it also allows ``str``."""
                              alias = self.aliases.get(name)
                              if alias is None:
                                  return None
                              members = list(_flatten(alias))
                              values = {arg for m in members if get_origin(m) is Literal for arg in get_args(m)}
                              if not values:
                                  return None
                              return frozenset(str(v) for v in values), str in members
                          

                          load classmethod

                          load(package_name: str) -> OurSchema
                          

                          Collect models and aliases from the direct modules of package_name.

                          Source code in src/aclientp/schema_reference.py
                          @classmethod
                          def load(cls, package_name: str) -> OurSchema:
                              """Collect models and aliases from the direct modules of ``package_name``."""
                              package = importlib.import_module(package_name)
                              models: dict[str, type[BaseModel]] = {}
                              aliases: dict[str, object] = {}
                              for info in pkgutil.iter_modules(package.__path__):
                                  if info.ispkg:
                                      continue
                                  module = importlib.import_module(f"{package_name}.{info.name}")
                                  for name, obj in vars(module).items():
                                      if inspect.isclass(obj):
                                          if issubclass(obj, BaseModel) and obj.__module__ == module.__name__:
                                              models[name] = obj
                                      elif not name.startswith("_") and _is_type_alias(obj):
                                          aliases.setdefault(name, obj)
                              return cls(models, aliases)
                          

                          union_members

                          union_members(name: str) -> list[type[BaseModel]]
                          

                          Models of the union alias name (empty if there is none).

                          Source code in src/aclientp/schema_reference.py
                          def union_members(self, name: str) -> list[type[BaseModel]]:
                              """Models of the union alias ``name`` (empty if there is none)."""
                              alias = self.aliases.get(name)
                              return [] if alias is None else [m for m in _flatten(alias) if _is_model(m)]
                          

                          Reference dataclass

                          A pinned upstream schema release.

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class Reference:
                              """A pinned upstream schema release."""
                          
                              protocol_version: int
                              tag: str
                              schema: JSON
                              meta: JSON
                              directory: UPath
                          
                              @classmethod
                              def load(cls, protocol_version: int, root: UPath = REFERENCE_ROOT) -> Reference:
                                  """Load the pinned reference of ``protocol_version``."""
                                  directory = root / f"v{protocol_version}"
                                  tag = (directory / "VERSION").read_text("utf-8").strip()
                                  schema = json.loads((directory / "schema.unstable.json").read_text("utf-8"))
                                  meta = json.loads((directory / "meta.unstable.json").read_text("utf-8"))
                                  return cls(protocol_version, tag, schema, meta, directory)
                          
                              @property
                              def parsed(self) -> UpstreamSchema:
                                  return UpstreamSchema.parse(self.schema, self.meta)
                          

                          load classmethod

                          load(protocol_version: int, root: UPath = REFERENCE_ROOT) -> Reference
                          

                          Load the pinned reference of protocol_version.

                          Source code in src/aclientp/schema_reference.py
                          @classmethod
                          def load(cls, protocol_version: int, root: UPath = REFERENCE_ROOT) -> Reference:
                              """Load the pinned reference of ``protocol_version``."""
                              directory = root / f"v{protocol_version}"
                              tag = (directory / "VERSION").read_text("utf-8").strip()
                              schema = json.loads((directory / "schema.unstable.json").read_text("utf-8"))
                              meta = json.loads((directory / "meta.unstable.json").read_text("utf-8"))
                              return cls(protocol_version, tag, schema, meta, directory)
                          

                          ReferenceChanges dataclass

                          What changed in a reference implementation since its pinned commit.

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class ReferenceChanges:
                              """What changed in a reference implementation since its pinned commit."""
                          
                              reference: ReferenceImplementation
                              head: UpstreamCommit
                              commits: list[UpstreamCommit]
                              """Commits since the pin that touched the reference's paths, newest first."""
                          
                              files: list[str]
                              """Files under the reference's paths that differ between the pin and the head."""
                          
                              @property
                              def compare_url(self) -> str:
                                  repo, pin, head = self.reference.repo, self.reference.commit, self.head.sha
                                  return f"https://github.com/{repo}/compare/{pin[:12]}...{head[:12]}"
                          

                          commits instance-attribute

                          commits: list[UpstreamCommit]
                          

                          Commits since the pin that touched the reference's paths, newest first.

                          files instance-attribute

                          files: list[str]
                          

                          Files under the reference's paths that differ between the pin and the head.

                          ReferenceImplementation dataclass

                          An upstream implementation pinned by commit (schema/references.toml).

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class ReferenceImplementation:
                              """An upstream implementation pinned by commit (``schema/references.toml``)."""
                          
                              name: str
                              repo: str
                              commit: str
                              paths: tuple[str, ...]
                              """Paths in the repository whose changes are of interest."""
                          
                              description: str = ""
                          

                          paths instance-attribute

                          paths: tuple[str, ...]
                          

                          Paths in the repository whose changes are of interest.

                          Report dataclass

                          Findings of a check, split against the known differences.

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class Report:
                              """Findings of a check, split against the known differences."""
                          
                              new: list[Finding]
                              """Differences not listed in ``conformance.toml``."""
                          
                              stale: dict[str, str]
                              """Listed differences that no longer occur."""
                          
                              @property
                              def ok(self) -> bool:
                                  return not self.new and not self.stale
                          

                          new instance-attribute

                          new: list[Finding]
                          

                          Differences not listed in conformance.toml.

                          stale instance-attribute

                          stale: dict[str, str]
                          

                          Listed differences that no longer occur.

                          Shape dataclass

                          An object shape of the upstream schema: a named definition or a union variant.

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class Shape:
                              """An object shape of the upstream schema: a named definition or a union variant."""
                          
                              key: str
                              """``Name`` for a definition, ``Union[prop=value]`` for a tagged union variant."""
                          
                              properties: frozenset[str]
                              """Wire names of all properties, including inherited (``allOf``) ones."""
                          
                              required: frozenset[str]
                              """Wire names of required properties."""
                          
                              union: str | None = None
                              """Name of the union a variant belongs to."""
                          
                              discriminator: tuple[str, str] | None = None
                              """``(property, value)`` that selects a variant."""
                          
                              bases: frozenset[str] = frozenset()
                              """Definitions this shape inherits via ``allOf``."""
                          
                              nullable: frozenset[str] = frozenset()
                              """Wire names of properties that accept ``null``."""
                          
                              constraints: Mapping[str, Mapping[str, float]] = field(default_factory=dict)
                              """Numeric and length constraints per property, as pydantic names (``ge``, ...)."""
                          
                              branch_of: str | None = None
                              """For a variant made from a tagged branch inside an object definition: that
                              definition. Our side models such an object either as one model of the same name,
                              or as a union of the same name whose members are the branches."""
                          

                          bases class-attribute instance-attribute

                          bases: frozenset[str] = frozenset()
                          

                          Definitions this shape inherits via allOf.

                          branch_of class-attribute instance-attribute

                          branch_of: str | None = None
                          

                          For a variant made from a tagged branch inside an object definition: that definition. Our side models such an object either as one model of the same name, or as a union of the same name whose members are the branches.

                          constraints class-attribute instance-attribute

                          constraints: Mapping[str, Mapping[str, float]] = field(default_factory=dict)
                          

                          Numeric and length constraints per property, as pydantic names (ge, ...).

                          discriminator class-attribute instance-attribute

                          discriminator: tuple[str, str] | None = None
                          

                          (property, value) that selects a variant.

                          key instance-attribute

                          key: str
                          

                          Name for a definition, Union[prop=value] for a tagged union variant.

                          nullable class-attribute instance-attribute

                          nullable: frozenset[str] = frozenset()
                          

                          Wire names of properties that accept null.

                          properties instance-attribute

                          properties: frozenset[str]
                          

                          Wire names of all properties, including inherited (allOf) ones.

                          required instance-attribute

                          required: frozenset[str]
                          

                          Wire names of required properties.

                          union class-attribute instance-attribute

                          union: str | None = None
                          

                          Name of the union a variant belongs to.

                          UpstreamCommit dataclass

                          A commit of a reference implementation.

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class UpstreamCommit:
                              """A commit of a reference implementation."""
                          
                              sha: str
                              date: str
                              subject: str
                          

                          UpstreamSchema dataclass

                          The parts of an upstream schema the checks compare.

                          Source code in src/aclientp/schema_reference.py
                          @dataclass(frozen=True)
                          class UpstreamSchema:
                              """The parts of an upstream schema the checks compare."""
                          
                              shapes: dict[str, Shape]
                              enums: dict[str, EnumDef]
                              union_members: dict[str, frozenset[str]]
                              """Union name to the keys of its members (variants and referenced definitions)."""
                          
                              methods: dict[str, frozenset[str]]
                              """``meta.unstable.json`` method group to method names."""
                          
                              @classmethod
                              def parse(cls, schema: JSON, meta: JSON) -> UpstreamSchema:
                                  """Extract shapes, enums, unions and methods from the upstream files."""
                                  defs: dict[str, JSON] = schema["$defs"]
                                  shapes: dict[str, Shape] = {}
                                  enums: dict[str, EnumDef] = {}
                                  unions: dict[str, frozenset[str]] = {}
                                  for name, node in defs.items():
                                      variants = node.get("oneOf") or node.get("anyOf")
                                      if variants is not None and "properties" not in node:
                                          if enum := _parse_enum(name, variants):
                                              enums[name] = enum
                                              continue
                                          members: set[str] = set()
                                          for variant in variants:
                                              if ref := variant.get("$ref"):
                                                  members.add(_ref_name(ref))
                                              elif shape := _parse_variant(name, variant, defs):
                                                  shapes[shape.key] = shape
                                                  members.add(shape.key)
                                              elif (parts := variant.get("allOf")) and len(parts) == 1 and "$ref" in parts[0]:
                                                  # Untagged variant, e.g. ``{"title": "stdio", "allOf": [{"$ref": ...}]}``
                                                  members.add(_ref_name(parts[0]["$ref"]))
                                          unions[name] = frozenset(members)
                                      elif "enum" in node:
                                          enums[name] = EnumDef(name, frozenset(node["enum"]), open=False)
                                      elif _is_object(node, defs):
                                          collected = _collect(node, defs)
                                          shapes[name] = Shape(
                                              name,
                                              collected.properties,
                                              collected.required,
                                              bases=collected.bases,
                                              nullable=collected.nullable,
                                              constraints=collected.constraints,
                                          )
                                          branches = [
                                              branch
                                              for part in node.get("oneOf", []) + node.get("anyOf", [])
                                              if (branch := _parse_branch(name, node, part, defs))
                                          ]
                                          for branch in branches:
                                              shapes[branch.key] = branch
                                          if branches:
                                              unions[name] = frozenset(branch.key for branch in branches)
                                  methods = {
                                      group: frozenset(meta[group].values()) for group in METHOD_GROUPS if group in meta
                                  }
                                  return cls(shapes, enums, unions, methods)
                          
                              @property
                              def inlined_bases(self) -> frozenset[str]:
                                  """Definitions that only serve as ``allOf`` bases of union variants."""
                                  used_as_base = {
                                      base for shape in self.shapes.values() if shape.union for base in shape.bases
                                  }
                                  referenced = {member for members in self.union_members.values() for member in members}
                                  return frozenset(used_as_base - referenced)
                          

                          inlined_bases property

                          inlined_bases: frozenset[str]
                          

                          Definitions that only serve as allOf bases of union variants.

                          methods instance-attribute

                          methods: dict[str, frozenset[str]]
                          

                          meta.unstable.json method group to method names.

                          union_members instance-attribute

                          union_members: dict[str, frozenset[str]]
                          

                          Union name to the keys of its members (variants and referenced definitions).

                          parse classmethod

                          parse(schema: JSON, meta: JSON) -> UpstreamSchema
                          

                          Extract shapes, enums, unions and methods from the upstream files.

                          Source code in src/aclientp/schema_reference.py
                          @classmethod
                          def parse(cls, schema: JSON, meta: JSON) -> UpstreamSchema:
                              """Extract shapes, enums, unions and methods from the upstream files."""
                              defs: dict[str, JSON] = schema["$defs"]
                              shapes: dict[str, Shape] = {}
                              enums: dict[str, EnumDef] = {}
                              unions: dict[str, frozenset[str]] = {}
                              for name, node in defs.items():
                                  variants = node.get("oneOf") or node.get("anyOf")
                                  if variants is not None and "properties" not in node:
                                      if enum := _parse_enum(name, variants):
                                          enums[name] = enum
                                          continue
                                      members: set[str] = set()
                                      for variant in variants:
                                          if ref := variant.get("$ref"):
                                              members.add(_ref_name(ref))
                                          elif shape := _parse_variant(name, variant, defs):
                                              shapes[shape.key] = shape
                                              members.add(shape.key)
                                          elif (parts := variant.get("allOf")) and len(parts) == 1 and "$ref" in parts[0]:
                                              # Untagged variant, e.g. ``{"title": "stdio", "allOf": [{"$ref": ...}]}``
                                              members.add(_ref_name(parts[0]["$ref"]))
                                      unions[name] = frozenset(members)
                                  elif "enum" in node:
                                      enums[name] = EnumDef(name, frozenset(node["enum"]), open=False)
                                  elif _is_object(node, defs):
                                      collected = _collect(node, defs)
                                      shapes[name] = Shape(
                                          name,
                                          collected.properties,
                                          collected.required,
                                          bases=collected.bases,
                                          nullable=collected.nullable,
                                          constraints=collected.constraints,
                                      )
                                      branches = [
                                          branch
                                          for part in node.get("oneOf", []) + node.get("anyOf", [])
                                          if (branch := _parse_branch(name, node, part, defs))
                                      ]
                                      for branch in branches:
                                          shapes[branch.key] = branch
                                      if branches:
                                          unions[name] = frozenset(branch.key for branch in branches)
                              methods = {
                                  group: frozenset(meta[group].values()) for group in METHOD_GROUPS if group in meta
                              }
                              return cls(shapes, enums, unions, methods)
                          

                          changelog

                          changelog(old: UpstreamSchema, new: UpstreamSchema) -> list[str]
                          

                          Human-readable changes between two upstream schemas.

                          Source code in src/aclientp/schema_reference.py
                          def changelog(old: UpstreamSchema, new: UpstreamSchema) -> list[str]:
                              """Human-readable changes between two upstream schemas."""
                              lines: list[str] = []
                              lines.extend(_diff_keys("shape", old.shapes, new.shapes))
                              for key in sorted(old.shapes.keys() & new.shapes.keys()):
                                  before, after = old.shapes[key], new.shapes[key]
                                  lines.extend(f"+ field {key}.{p}" for p in sorted(after.properties - before.properties))
                                  lines.extend(f"- field {key}.{p}" for p in sorted(before.properties - after.properties))
                                  common = before.properties & after.properties
                                  lines.extend(
                                      f"~ field {key}.{p} is now required"
                                      for p in sorted((after.required - before.required) & common)
                                  )
                                  lines.extend(
                                      f"~ field {key}.{p} is now optional"
                                      for p in sorted((before.required - after.required) & common)
                                  )
                              lines.extend(_diff_keys("enum", old.enums, new.enums))
                              for name in sorted(old.enums.keys() & new.enums.keys()):
                                  before_values, after_values = old.enums[name].values, new.enums[name].values
                                  lines.extend(f"+ enum value {name}.{v}" for v in sorted(after_values - before_values))
                                  lines.extend(f"- enum value {name}.{v}" for v in sorted(before_values - after_values))
                              lines.extend(_diff_keys("union", old.union_members, new.union_members))
                              for name in sorted(old.union_members.keys() & new.union_members.keys()):
                                  before_members, after_members = old.union_members[name], new.union_members[name]
                                  lines.extend(f"+ union member {name}: {m}" for m in sorted(after_members - before_members))
                                  lines.extend(f"- union member {name}: {m}" for m in sorted(before_members - after_members))
                              for group in METHOD_GROUPS:
                                  before_methods = old.methods.get(group, frozenset())
                                  after_methods = new.methods.get(group, frozenset())
                                  lines.extend(f"+ method {group}: {m}" for m in sorted(after_methods - before_methods))
                                  lines.extend(f"- method {group}: {m}" for m in sorted(before_methods - after_methods))
                              return lines
                          

                          check

                          check(
                              upstream: UpstreamSchema,
                              ours: OurSchema,
                              renames: Mapping[str, str],
                              *,
                              check_nullability: bool = False,
                              check_parse_nullability: bool = False,
                              check_constraints: bool = False,
                          ) -> list[Finding]
                          

                          Compare the models with the upstream schema.

                          renames maps upstream definition names (shapes, unions, enums) to ours.

                          Source code in src/aclientp/schema_reference.py
                          def check(
                              upstream: UpstreamSchema,
                              ours: OurSchema,
                              renames: Mapping[str, str],
                              *,
                              check_nullability: bool = False,
                              check_parse_nullability: bool = False,
                              check_constraints: bool = False,
                          ) -> list[Finding]:
                              """Compare the models with the upstream schema.
                          
                              ``renames`` maps upstream definition names (shapes, unions, enums) to ours.
                              """
                              findings: list[Finding] = []
                              matched = _match_shapes(upstream, ours, renames)
                              inlined = upstream.inlined_bases
                              # Discriminators that variants add to the definitions they inherit from.
                              added_tags: dict[str, set[str]] = {}
                              for shape in upstream.shapes.values():
                                  if shape.discriminator:
                                      for base in shape.bases:
                                          added_tags.setdefault(base, set()).add(shape.discriminator[0])
                              for key, shape in sorted(upstream.shapes.items()):
                                  if shape.branch_of and shape.branch_of in matched:
                                      continue  # the object is one model on our side, compared as a whole
                                  model = matched.get(key)
                                  if model is None:
                                      if key not in inlined and key not in upstream.union_members:
                                          findings.append(Finding(f"missing-shape:{key}", "no matching model"))
                                      continue
                                  tags = added_tags.get(key, set())
                                  findings.extend(
                                      _compare_fields(
                                          key,
                                          shape,
                                          model,
                                          tags,
                                          check_nullability,
                                          check_constraints,
                                          check_parse_nullability=check_parse_nullability,
                                      )
                                  )
                              findings.extend(_check_enums(upstream, ours, renames))
                              findings.extend(_check_methods(upstream, ours))
                              return findings
                          

                          download

                          download(protocol_version: int, tag: str) -> dict[str, str]
                          

                          Download the reference files of tag, verbatim.

                          Source code in src/aclientp/schema_reference.py
                          def download(protocol_version: int, tag: str) -> dict[str, str]:
                              """Download the reference files of ``tag``, verbatim."""
                              import httpx2
                          
                              base = f"https://raw.githubusercontent.com/{REPO}/{tag}/schema/v{protocol_version}"
                              files: dict[str, str] = {}
                              with httpx2.Client(timeout=60) as client:
                                  for name in REFERENCE_FILES:
                                      response = client.get(f"{base}/{name}")
                                      response.raise_for_status()
                                      files[name] = response.text
                              return files
                          

                          load_references

                          load_references(path: UPath = REFERENCES_FILE) -> list[ReferenceImplementation]
                          

                          Read the pinned reference implementations.

                          Source code in src/aclientp/schema_reference.py
                          def load_references(path: UPath = REFERENCES_FILE) -> list[ReferenceImplementation]:
                              """Read the pinned reference implementations."""
                              data = tomllib.loads(path.read_text("utf-8"))
                              return [
                                  ReferenceImplementation(
                                      name=name,
                                      repo=entry["repo"],
                                      commit=entry["commit"],
                                      paths=tuple(entry.get("paths", ())),
                                      description=entry.get("description", ""),
                                  )
                                  for name, entry in data.items()
                              ]
                          

                          main

                          main(argv: list[str] | None = None) -> int
                          

                          Entry point of python -m aclientp.schema_reference.

                          Source code in src/aclientp/schema_reference.py
                          def main(argv: list[str] | None = None) -> int:
                              """Entry point of ``python -m aclientp.schema_reference``."""
                              parser = argparse.ArgumentParser(
                                  prog="python -m aclientp.schema_reference", description=__doc__
                              )
                              parser.add_argument("--protocol", type=int, default=1, choices=(1, 2))
                              commands = parser.add_subparsers(dest="command", required=True)
                              commands.add_parser("latest", help="show the pinned and the newest upstream tag")
                              sync = commands.add_parser("sync", help="update the pinned reference")
                              sync.add_argument("--tag", help="upstream tag (default: newest)")
                              sync.add_argument("--dry-run", action="store_true", help="only print the changelog")
                              commands.add_parser("check", help="compare the models with the pinned reference")
                              refs = commands.add_parser("refs", help="changes in the pinned reference implementations")
                              refs.add_argument("--update", metavar="NAME", help="move the pin of this reference")
                              refs.add_argument("--commit", help="commit to pin (default: the current upstream head)")
                              args = parser.parse_args(argv)
                              version: int = args.protocol
                          
                              if args.command == "refs":
                                  return _refs_command(args.update, args.commit)
                          
                              if args.command == "latest":
                                  pinned = Reference.load(version).tag
                                  newest = upstream_tags(version)[-1]
                                  print(f"pinned: {pinned}\nnewest: {newest}" + (" (up to date)" if pinned == newest else ""))
                                  return 0
                              if args.command == "sync":
                                  tag: str = args.tag or upstream_tags(version)[-1]
                                  files = download(version, tag)
                                  if (REFERENCE_ROOT / f"v{version}" / "VERSION").exists():
                                      current = Reference.load(version)
                                      print(f"{current.tag} -> {tag}")
                                      new = parse_files(files)
                                      for line in changelog(current.parsed, new) or ["(no changes)"]:
                                          print(f"  {line}")
                                  else:
                                      print(f"no pinned reference yet -> {tag}")
                                  if not args.dry_run:
                                      write_reference(version, tag, files, REFERENCE_ROOT)
                                      print(f"pinned {tag}; run `check` to see what the models need")
                                  return 0
                              if version not in MODEL_PACKAGES:
                                  print(f"no models for ACP v{version} yet", file=sys.stderr)
                                  return 1
                              report = run_check(version)
                              _print_report(version, report)
                              return 0 if report.ok else 1
                          

                          parse_files

                          parse_files(files: Mapping[str, str]) -> UpstreamSchema
                          

                          Parse downloaded reference files.

                          Source code in src/aclientp/schema_reference.py
                          def parse_files(files: Mapping[str, str]) -> UpstreamSchema:
                              """Parse downloaded reference files."""
                              return UpstreamSchema.parse(
                                  json.loads(files["schema.unstable.json"]), json.loads(files["meta.unstable.json"])
                              )
                          

                          reference_changes

                          reference_changes(reference: ReferenceImplementation) -> ReferenceChanges
                          

                          Fetch the changes of reference since its pinned commit.

                          Source code in src/aclientp/schema_reference.py
                          def reference_changes(reference: ReferenceImplementation) -> ReferenceChanges:
                              """Fetch the changes of ``reference`` since its pinned commit."""
                              repo = f"repos/{reference.repo}"
                              head = _commit(_github(f"{repo}/commits/HEAD"))
                              pinned = _commit(_github(f"{repo}/commits/{reference.commit}"))
                              compare = _github(f"{repo}/compare/{reference.commit}...{head.sha}")
                              files = sorted(
                                  entry["filename"]
                                  for entry in compare.get("files", [])
                                  if any(_under(entry["filename"], path) for path in reference.paths)
                              )
                              seen: dict[str, UpstreamCommit] = {}
                              for path in reference.paths:
                                  for data in _github(f"{repo}/commits", path=path, since=f"{pinned.date}T00:00:00Z"):
                                      commit = _commit(data)
                                      if commit.sha != reference.commit:
                                          seen.setdefault(commit.sha, commit)
                              in_range = {entry["sha"] for entry in compare.get("commits", [])}
                              commits = sorted(
                                  (c for c in seen.values() if c.sha in in_range), key=lambda c: c.date, reverse=True
                              )
                              return ReferenceChanges(reference, head, commits, files)
                          

                          run_check

                          run_check(protocol_version: int, root: UPath = REFERENCE_ROOT) -> Report
                          

                          Check the models of protocol_version against its pinned reference.

                          Source code in src/aclientp/schema_reference.py
                          def run_check(protocol_version: int, root: UPath = REFERENCE_ROOT) -> Report:
                              """Check the models of ``protocol_version`` against its pinned reference."""
                              reference = Reference.load(protocol_version, root)
                              conformance = Conformance.load(reference.directory / "conformance.toml")
                              ours = OurSchema.load(MODEL_PACKAGES[protocol_version])
                              findings = check(
                                  reference.parsed,
                                  ours,
                                  conformance.renames,
                                  check_nullability=conformance.check_nullability,
                                  check_parse_nullability=conformance.check_parse_nullability,
                                  check_constraints=conformance.check_constraints,
                              )
                              if conformance.allow_missing:
                                  findings = [f for f in findings if not f.id.startswith(MISSING_KINDS)]
                              return split_known(findings, conformance.known)
                          

                          split_known

                          split_known(findings: Iterable[Finding], known: Mapping[str, str]) -> Report
                          

                          Split findings into undocumented ones, and find stale known differences.

                          Source code in src/aclientp/schema_reference.py
                          def split_known(findings: Iterable[Finding], known: Mapping[str, str]) -> Report:
                              """Split findings into undocumented ones, and find stale known differences."""
                              findings = list(findings)
                              ids = {f.id for f in findings}
                              return Report(
                                  new=[f for f in findings if f.id not in known],
                                  stale={k: v for k, v in known.items() if k not in ids},
                              )
                          

                          tag_sort_key

                          tag_sort_key(tag: str) -> tuple[tuple[int, ...], int, str, int]
                          

                          Sort key of an upstream schema tag such as schema-v2.0.0-alpha.17.

                          A release sorts after its pre-releases (2.0.0-alpha.17 < 2.0.0).

                          Source code in src/aclientp/schema_reference.py
                          def tag_sort_key(tag: str) -> tuple[tuple[int, ...], int, str, int]:
                              """Sort key of an upstream schema tag such as ``schema-v2.0.0-alpha.17``.
                          
                              A release sorts after its pre-releases (``2.0.0-alpha.17`` < ``2.0.0``).
                              """
                              release, _, pre = tag.removeprefix("schema-v").partition("-")
                              numbers = tuple(int(part) for part in release.split("."))
                              if not pre:
                                  return numbers, 1, "", 0
                              label, _, number = pre.partition(".")
                              return numbers, 0, label, int(number or 0)
                          

                          update_reference

                          update_reference(name: str, commit: str, path: UPath = REFERENCES_FILE) -> None
                          

                          Move the pin of reference name to commit, keeping the file's layout.

                          Source code in src/aclientp/schema_reference.py
                          def update_reference(name: str, commit: str, path: UPath = REFERENCES_FILE) -> None:
                              """Move the pin of reference ``name`` to ``commit``, keeping the file's layout."""
                              lines = path.read_text("utf-8").splitlines(keepends=True)
                              section: str | None = None
                              for index, line in enumerate(lines):
                                  stripped = line.strip()
                                  if stripped.startswith("[") and stripped.endswith("]"):
                                      section = stripped[1:-1]
                                  elif section == name and stripped.startswith("commit"):
                                      lines[index] = f'commit = "{commit}"\n'
                                      path.write_text("".join(lines), encoding="utf-8")
                                      return
                              msg = f"no reference named {name!r} in {path}"
                              raise KeyError(msg)
                          

                          upstream_tags

                          upstream_tags(protocol_version: int) -> list[str]
                          

                          Upstream schema tags of protocol_version, oldest first.

                          Source code in src/aclientp/schema_reference.py
                          def upstream_tags(protocol_version: int) -> list[str]:
                              """Upstream schema tags of ``protocol_version``, oldest first."""
                              import httpx2
                          
                              url = f"https://api.github.com/repos/{REPO}/git/matching-refs/tags/schema-v{protocol_version}."
                              response = httpx2.get(url, headers={"Accept": "application/vnd.github+json"}, timeout=30)
                              response.raise_for_status()
                              tags = [ref["ref"].removeprefix("refs/tags/") for ref in response.json()]
                              return sorted(tags, key=tag_sort_key)
                          

                          wire_fields

                          wire_fields(model: type[BaseModel]) -> dict[str, FieldInfo]
                          

                          Wire name and behaviour of each serialized field of model.

                          Source code in src/aclientp/schema_reference.py
                          def wire_fields(model: type[BaseModel]) -> dict[str, FieldInfo]:
                              """Wire name and behaviour of each serialized field of ``model``."""
                              if any(isinstance(info.annotation, ForwardRef) for info in model.model_fields.values()):
                                  # Annotations stay unresolved until the model is rebuilt (first validation).
                                  model.model_rebuild(force=True)
                              return {
                                  (info.alias or name): FieldInfo(
                                      required=info.is_required(),
                                      omittable=not info.is_required()
                                      and (info.default is None or info.default is MISSING)
                                      and info.default_factory is None,
                                      accepts_none=any(member in (type(None), Any) for member in _flatten(info.annotation)),
                                      constraints=_field_constraints(info),
                                  )
                                  for name, info in model.model_fields.items()
                                  if not info.exclude
                              }
                          

                          write_reference

                          write_reference(protocol_version: int, tag: str, files: Mapping[str, str], root: UPath) -> None
                          

                          Store downloaded reference files, unchanged, as the pin of protocol_version.

                          Keeping upstream's bytes means a git diff between pins is upstream's diff.

                          Source code in src/aclientp/schema_reference.py
                          def write_reference(protocol_version: int, tag: str, files: Mapping[str, str], root: UPath) -> None:
                              """Store downloaded reference files, unchanged, as the pin of ``protocol_version``.
                          
                              Keeping upstream's bytes means a ``git diff`` between pins is upstream's diff.
                              """
                              directory = root / f"v{protocol_version}"
                              directory.mkdir(parents=True, exist_ok=True)
                              for name in REFERENCE_FILES:
                                  (directory / name).write_text(files[name], encoding="utf-8")
                              (directory / "VERSION").write_text(tag + "\n", encoding="utf-8")