codex_headers.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. """Codex request identity helpers shared by agent client builders.
  2. Leaf module with no dependency on the large auxiliary-client router, so a
  3. long-lived process can import a newly added client builder without resolving a
  4. new symbol from an older cached ``auxiliary_client`` module.
  5. """
  6. from __future__ import annotations
  7. import base64
  8. import json
  9. from typing import Any, Dict
  10. from urllib.parse import urlparse
  11. CODEX_AUX_BASE_URL = "https://chatgpt.com/backend-api/codex"
  12. def is_official_codex_base_url(base_url: str) -> bool:
  13. """Identify OpenAI's Codex endpoint without matching custom proxies."""
  14. try:
  15. parsed = urlparse(base_url)
  16. path = parsed.path.rstrip("/")
  17. return (
  18. parsed.scheme == "https"
  19. and parsed.hostname == "chatgpt.com"
  20. and parsed.port in (None, 443)
  21. and (path == "/backend-api/codex" or path.startswith("/backend-api/codex/"))
  22. )
  23. except (TypeError, ValueError):
  24. return False
  25. def codex_cloudflare_headers(access_token: str, *, base_url: str = CODEX_AUX_BASE_URL) -> dict[str, str]:
  26. """Identity and account headers for chatgpt.com/backend-api/codex.
  27. OpenAI requires third-party harnesses to identify themselves: the official
  28. endpoint gets Hermes' originator and version, custom endpoints keep the
  29. codex_cli_rs compatibility identity. The account headers come from the
  30. OAuth JWT (see :func:`codex_account_headers`).
  31. """
  32. if is_official_codex_base_url(base_url):
  33. from hermes_cli.version_info import get_version_info
  34. headers = {
  35. "User-Agent": f"HermesAgent/{get_version_info().base_version}",
  36. "originator": "hermes-agent",
  37. }
  38. else:
  39. headers = {"User-Agent": "codex_cli_rs/0.0.0 (Hermes Agent)", "originator": "codex_cli_rs"}
  40. headers.update(codex_account_headers(access_token))
  41. return headers
  42. def codex_account_headers(access_token: str) -> dict[str, str]:
  43. """Workspace headers the Codex backend derives from the OAuth JWT.
  44. ``ChatGPT-Account-ID`` (canonical casing, from codex-rs ``auth.rs``) comes from
  45. ``chatgpt_account_id``; ``x-openai-internal-codex-residency`` from
  46. ``chatgpt_data_residency`` (fallback ``chatgpt_compute_residency``) — without
  47. it residency-enforced workspaces answer 401 "Workspace is not authorized in
  48. this region". A malformed token drops the headers rather than raising, so it
  49. surfaces as a 401 instead of a crash at client construction.
  50. """
  51. headers: dict[str, str] = {}
  52. if not isinstance(access_token, str) or not access_token.strip():
  53. return headers
  54. try:
  55. parts = access_token.split(".")
  56. if len(parts) < 2:
  57. return headers
  58. payload_b64 = parts[1] + "=" * (-len(parts[1]) % 4)
  59. auth = json.loads(base64.urlsafe_b64decode(payload_b64)).get("https://api.openai.com/auth", {})
  60. acct_id = auth.get("chatgpt_account_id")
  61. if isinstance(acct_id, str) and acct_id:
  62. headers["ChatGPT-Account-ID"] = acct_id
  63. residency = auth.get("chatgpt_data_residency") or auth.get("chatgpt_compute_residency")
  64. if isinstance(residency, str) and residency.strip():
  65. headers["x-openai-internal-codex-residency"] = residency.strip()
  66. except Exception:
  67. pass
  68. return headers
  69. def codex_request_compression_hooks(base_url: str, *, async_mode: bool = False) -> dict[str, list] | None:
  70. """httpx ``event_hooks`` that zstd-compress Responses request bodies for the official Codex backend.
  71. Parity with the official Codex client (zstd on ``/responses`` with ChatGPT auth, default since
  72. openai/codex#10102). Lossless transport encoding: tokens and prompt caching are unchanged. Uses the
  73. stdlib codec (Python 3.14+); without it, or for any other endpoint/proxy, bodies stay raw JSON.
  74. """
  75. if not is_official_codex_base_url(base_url):
  76. return None
  77. try:
  78. from compression import zstd
  79. import httpx
  80. except ImportError:
  81. return None
  82. def compress(request: httpx.Request) -> None:
  83. if (request.method != "POST" or not request.url.path.endswith("/responses")
  84. or "content-encoding" in request.headers):
  85. return
  86. body = zstd.compress(request.read())
  87. request.stream = httpx.ByteStream(body)
  88. request._content = body
  89. request.headers["Content-Encoding"] = "zstd"
  90. request.headers["Content-Length"] = str(len(body))
  91. if not async_mode:
  92. return {"request": [compress]}
  93. async def compress_async(request: httpx.Request) -> None:
  94. compress(request)
  95. return {"request": [compress_async]}
  96. def apply_required_codex_headers(client_kwargs: dict[str, Any], *, access_token: str, base_url: str) -> None:
  97. """Keep required Codex identity after user/provider header overrides."""
  98. if not is_official_codex_base_url(base_url):
  99. return
  100. required = codex_cloudflare_headers(access_token, base_url=base_url)
  101. required_names = {name.lower() for name in required}
  102. existing = client_kwargs.get("default_headers") or {}
  103. client_kwargs["default_headers"] = {
  104. **{name: value for name, value in existing.items() if str(name).lower() not in required_names},
  105. **required,
  106. }