gpt in affine
runner nix smoke / nix label and flake smoke (push) Failing after 1m12s

This commit is contained in:
2026-11-01 11:21:28 +00:00
parent e935abd0c3
commit 50c4efc09b
30 changed files with 4280 additions and 336 deletions
@@ -0,0 +1,617 @@
#!/usr/bin/env python3
"""Secure local ChatGPT OAuth enrollment and model discovery."""
import argparse
import base64
import contextlib
import fcntl
import hashlib
import hmac
import ipaddress
import json
import os
import re
import secrets
import stat
import sys
import tempfile
import threading
import time
import uuid
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from socketserver import ThreadingMixIn
from urllib.parse import parse_qs, urlencode, urlsplit
import jwt
import requests
# The installed wrapper executes this file directly; keep lazy gateway imports
# on the same module instance so expected AppError exceptions remain catchable.
sys.modules.setdefault("affine_chatgpt", sys.modules[__name__])
ISSUER = "https://auth.openai.com"
DISCOVERY_URL = ISSUER + "/.well-known/openid-configuration"
AUTHORIZE_URL = ISSUER + "/api/accounts/authorize"
TOKEN_URL = ISSUER + "/api/accounts/oauth/token"
JWKS_URL = ISSUER + "/.well-known/jwks.json"
RESOURCE = "https://api.openai.com/v1"
MODELS_URL = RESOURCE + "/models"
RESPONSES_URL = RESOURCE + "/responses"
DYNAMIC_CLIENT = "dynamic_agent_client"
AGENT_NAME = "Hearth AFFiNE ChatGPT connector"
SCOPES = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct"
REQUIRED_SCOPE = "chatgpt.tokens.use.direct"
HTTP_TIMEOUT = 15
SOCKET_TIMEOUT = 5
MAX_CALLBACK = 8192
CLIENT_RE = re.compile(r"^[A-Za-z0-9._~-]{1,256}$")
class AppError(Exception):
"""Expected failure with a non-sensitive stable error code."""
def new_session():
session = requests.Session()
session.trust_env = False
return session
def utc_now():
return datetime.now(timezone.utc).isoformat()
def default_state_dir():
return Path.home() / ".local" / "state" / "affine-chatgpt"
def secure_dir(path):
path = Path(path).expanduser()
try:
info = path.lstat()
except FileNotFoundError:
path.mkdir(parents=True, mode=0o700)
info = path.lstat()
if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode):
raise AppError("unsafe_state_dir")
os.chmod(path, 0o700)
return path
def _regular_nofollow(path):
try:
info = Path(path).lstat()
except FileNotFoundError:
return False
if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode):
raise AppError("unsafe_state_file")
if info.st_mode & 0o077:
raise AppError("unsafe_state_file")
return True
def read_json(path):
if not _regular_nofollow(path):
return None
try:
with open(path, "r", encoding="utf-8") as stream:
return json.load(stream)
except (ValueError, TypeError):
raise AppError("invalid_state") from None
def atomic_json(path, value):
path = Path(path)
secure_dir(path.parent)
_regular_nofollow(path)
descriptor, temporary = tempfile.mkstemp(prefix=".tmp-", dir=path.parent)
try:
os.fchmod(descriptor, 0o600)
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
descriptor = -1
json.dump(value, stream, sort_keys=True, separators=(",", ":"))
stream.write("\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
os.chmod(path, 0o600)
directory_descriptor = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory_descriptor)
finally:
os.close(directory_descriptor)
finally:
if descriptor >= 0:
os.close(descriptor)
with contextlib.suppress(FileNotFoundError):
os.unlink(temporary)
def host_id(state_dir, supplied=None):
target = secure_dir(state_dir) / "host.json"
saved = read_json(target)
if saved is not None:
if not isinstance(saved, dict):
raise AppError("invalid_state")
saved_value = saved.get("host_id")
if not isinstance(saved_value, str):
raise AppError("invalid_state")
value = saved_value
elif supplied:
source = Path(supplied).expanduser()
if not _regular_nofollow(source) or source.stat().st_mode & 0o077:
raise AppError("unsafe_host_id_file")
try:
value = source.read_text(encoding="ascii").strip()
except OSError:
raise AppError("invalid_host_id") from None
else:
value = "urn:uuid:" + str(uuid.uuid4())
try:
if not value.startswith("urn:uuid:"):
raise ValueError
parsed = uuid.UUID(value.removeprefix("urn:uuid:"))
if parsed.version != 4:
raise ValueError
except (ValueError, AttributeError):
raise AppError("invalid_host_id") from None
value = "urn:uuid:" + str(parsed)
if saved is None:
atomic_json(target, {"host_id": value})
return value
def pkce_challenge(verifier):
digest = hashlib.sha256(verifier.encode("ascii")).digest()
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
def _safe_response(response, expected=200):
if response.is_redirect or response.status_code != expected:
raise AppError("oauth_http_error")
try:
value = response.json()
except (requests.RequestException, ValueError):
raise AppError("oauth_response_invalid") from None
if not isinstance(value, dict):
raise AppError("oauth_response_invalid")
return value
def _request(session, method, url, **kwargs):
if url not in {DISCOVERY_URL, TOKEN_URL, JWKS_URL, MODELS_URL, RESPONSES_URL}:
raise AppError("endpoint_not_allowed")
kwargs.update(timeout=HTTP_TIMEOUT, allow_redirects=False)
try:
return session.request(method, url, **kwargs)
except requests.RequestException:
raise AppError("network_error") from None
def check_discovery(session):
data = _safe_response(_request(session, "GET", DISCOVERY_URL))
if (
data.get("issuer") != ISSUER
or data.get("authorization_endpoint") != AUTHORIZE_URL
or data.get("token_endpoint") != TOKEN_URL
or data.get("jwks_uri") != JWKS_URL
):
raise AppError("discovery_mismatch")
def fetch_jwks(session):
data = _safe_response(_request(session, "GET", JWKS_URL))
if not isinstance(data.get("keys"), list):
raise AppError("jwks_invalid")
return data
def validate_id_token(encoded, client_id, nonce, session, now=None):
try:
header = jwt.get_unverified_header(encoded)
except jwt.PyJWTError:
raise AppError("id_token_invalid") from None
kid = header.get("kid")
if header.get("alg") != "RS256" or not isinstance(kid, str) or not kid:
raise AppError("id_token_invalid")
try:
key_set = jwt.PyJWKSet.from_dict(fetch_jwks(session))
key = next(item.key for item in key_set.keys if item.key_id == kid)
claims = jwt.decode(
encoded,
key,
algorithms=["RS256"],
audience=client_id,
issuer=ISSUER,
options={"require": ["iss", "aud", "exp", "iat", "nonce", "sub"]},
leeway=0,
)
except (jwt.PyJWTError, StopIteration, ValueError, TypeError):
raise AppError("id_token_invalid") from None
if now is not None and claims.get("exp", 0) <= now:
raise AppError("id_token_invalid")
if not hmac.compare_digest(str(claims["nonce"]), nonce):
raise AppError("id_token_invalid")
if not isinstance(claims["sub"], str) or not claims["sub"]:
raise AppError("id_token_invalid")
return claims
def validate_token_response(data):
required = ("access_token", "refresh_token", "id_token", "scope")
if any(not isinstance(data.get(field), str) or not data[field] for field in required):
raise AppError("token_response_invalid")
if data.get("token_type") != "Bearer" or isinstance(data.get("expires_in"), bool):
raise AppError("token_response_invalid")
if not isinstance(data.get("expires_in"), int) or data["expires_in"] <= 0:
raise AppError("token_response_invalid")
scopes = sorted(set(data["scope"].split()))
if REQUIRED_SCOPE not in scopes:
raise AppError("scope_missing")
return scopes
class CallbackAttempt:
def __init__(self, state, client_id, deadline):
self.state = state
self.client_id = client_id
self.deadline = deadline
self.result = None
self.consumed = False
self.lock = threading.Lock()
def process(self, raw_query, host, expected_host, now=None):
now = time.monotonic() if now is None else now
if len(raw_query) > MAX_CALLBACK or host != expected_host or now > self.deadline:
raise AppError("callback_invalid")
try:
values = parse_qs(raw_query, keep_blank_values=True, strict_parsing=True)
except ValueError:
raise AppError("callback_invalid") from None
allowed = {"state", "code", "scope", "client_id", "error", "error_description"}
if not values or set(values) - allowed or any(len(items) != 1 for items in values.values()):
raise AppError("callback_invalid")
if any(len(items[0]) > 4096 for items in values.values()):
raise AppError("callback_invalid")
returned_state = values.get("state", [""])[0]
if not hmac.compare_digest(returned_state, self.state):
raise AppError("state_mismatch")
with self.lock:
if self.consumed:
raise AppError("callback_replayed")
if "error" in values:
if "code" in values or not values["error"][0]:
raise AppError("callback_invalid")
self.consumed = True
self.result = {"denied": True}
return self.result
code = values.get("code", [""])[0]
if not code:
raise AppError("callback_invalid")
supplied = values.get("client_id", [None])[0]
if self.client_id == DYNAMIC_CLIENT:
if not supplied or supplied == DYNAMIC_CLIENT or not CLIENT_RE.fullmatch(supplied):
raise AppError("client_id_invalid")
issued = supplied
else:
if supplied is not None and supplied != self.client_id:
raise AppError("client_id_mismatch")
issued = self.client_id
self.consumed = True
self.result = {"denied": False, "code": code, "client_id": issued}
return self.result
class LoopbackHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
block_on_close = False
def handle_error(self, request, client_address):
return
def get_request(self):
request, address = super().get_request()
request.settimeout(SOCKET_TIMEOUT)
return request, address
def callback_handler(attempt, expected_host):
class Handler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def _reply(self, status, text):
body = (text + "\n").encode("utf-8")
try:
self.send_response(status)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Referrer-Policy", "no-referrer")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
except OSError:
return
def do_GET(self):
split = urlsplit(self.path)
if split.path != "/auth/callback" or split.fragment or len(self.path) > MAX_CALLBACK:
self._reply(404, "Not found")
return
try:
result = attempt.process(split.query, self.headers.get("Host", ""), expected_host)
except AppError:
self._reply(400, "Invalid callback. Return to the terminal and retry if needed.")
return
if result["denied"]:
self._reply(200, "Authorization declined. You may close this page.")
else:
self._reply(200, "Authorization received. You may close this page.")
return Handler
def credentials_path(state_dir):
return secure_dir(state_dir) / "credentials.json"
def credentials_valid(value):
strings = (
"issuer",
"subject",
"client_id",
"host_id",
"access_token",
"refresh_token",
"id_token",
"token_type",
"saved_at",
)
return bool(
isinstance(value, dict)
and all(isinstance(value.get(field), str) and value[field] for field in strings)
and value["issuer"] == ISSUER
and value["token_type"] == "Bearer"
and isinstance(value.get("scopes"), list)
and REQUIRED_SCOPE in value["scopes"]
and not isinstance(value.get("expires_at"), bool)
and isinstance(value.get("expires_at"), (int, float))
)
def read_credentials(directory):
value = read_json(credentials_path(directory))
if value is not None and not credentials_valid(value):
raise AppError("invalid_state")
return value
@contextlib.contextmanager
def credential_lock(state_dir):
directory = secure_dir(state_dir)
lock_path = directory / "credentials.lock"
_regular_nofollow(lock_path)
descriptor = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
try:
os.fchmod(descriptor, 0o600)
fcntl.flock(descriptor, fcntl.LOCK_EX)
yield directory
finally:
os.close(descriptor)
def exchange_code(session, code, verifier, redirect_uri, client_id):
response = _request(
session,
"POST",
TOKEN_URL,
data={
"grant_type": "authorization_code",
"client_id": client_id,
"code": code,
"code_verifier": verifier,
"redirect_uri": redirect_uri,
"resource": RESOURCE,
},
)
return _safe_response(response)
def login(args, session=None):
session = session or new_session()
with credential_lock(args.state_dir) as directory:
host = host_id(directory, args.host_id_file)
old = read_credentials(directory)
requested_client = old["client_id"] if old else DYNAMIC_CLIENT
verifier = secrets.token_urlsafe(64)
state = secrets.token_urlsafe(32)
nonce = secrets.token_urlsafe(32)
server = LoopbackHTTPServer(("127.0.0.1", args.port), BaseHTTPRequestHandler)
port = server.server_address[1]
expected_host = f"127.0.0.1:{port}"
redirect_uri = f"http://{expected_host}/auth/callback"
attempt = CallbackAttempt(state, requested_client, time.monotonic() + args.timeout)
server.RequestHandlerClass = callback_handler(attempt, expected_host)
server.timeout = min(1, args.timeout)
query = {
"client_id": requested_client,
"ext_agent_host_id": host,
"response_type": "code",
"redirect_uri": redirect_uri,
"scope": SCOPES,
"resource": RESOURCE,
"state": state,
"nonce": nonce,
"code_challenge_method": "S256",
"code_challenge": pkce_challenge(verifier),
}
if requested_client == DYNAMIC_CLIENT:
query["agent_name_hint"] = AGENT_NAME
print(AUTHORIZE_URL + "?" + urlencode(query), flush=True)
try:
while attempt.result is None and time.monotonic() <= attempt.deadline:
server.handle_request()
finally:
server.server_close()
if attempt.result is None:
raise AppError("callback_timeout")
if attempt.result["denied"]:
raise AppError("authorization_denied")
check_discovery(session)
issued = attempt.result["client_id"]
token = exchange_code(session, attempt.result["code"], verifier, redirect_uri, issued)
scopes = validate_token_response(token)
claims = validate_id_token(token["id_token"], issued, nonce, session)
if old and old["subject"] != claims["sub"]:
raise AppError("account_mismatch")
now = time.time()
saved = {
"issuer": ISSUER,
"subject": claims["sub"],
"client_id": issued,
"host_id": host,
"access_token": token["access_token"],
"refresh_token": token["refresh_token"],
"id_token": token["id_token"],
"token_type": "Bearer",
"scopes": scopes,
"saved_at": utc_now(),
"expires_at": now + token["expires_in"],
}
atomic_json(credentials_path(directory), saved)
print(json.dumps({"authorized": True}))
def status(args):
directory = secure_dir(args.state_dir)
host_data = read_json(directory / "host.json")
if host_data is not None and (
not isinstance(host_data, dict) or not isinstance(host_data.get("host_id"), str)
):
raise AppError("invalid_state")
creds = read_credentials(directory)
authorized = credentials_valid(creds)
result = {
"authorized": authorized,
"access_token_expired": not isinstance(creds, dict)
or not isinstance(creds.get("expires_at"), (int, float))
or creds.get("expires_at", 0) <= time.time(),
}
if host_data and isinstance(host_data.get("host_id"), str):
result["host_id"] = host_data["host_id"]
print(json.dumps(result, sort_keys=True))
def refresh(session, path, creds):
response = _request(
session,
"POST",
TOKEN_URL,
data={
"grant_type": "refresh_token",
"client_id": creds["client_id"],
"refresh_token": creds["refresh_token"],
"resource": RESOURCE,
},
)
data = _safe_response(response)
scopes = validate_token_response({**data, "id_token": data.get("id_token", creds.get("id_token"))})
if data["refresh_token"] == creds["refresh_token"]:
raise AppError("refresh_not_rotated")
updated = dict(creds)
updated.update(
access_token=data["access_token"],
refresh_token=data["refresh_token"],
token_type="Bearer",
scopes=scopes,
saved_at=utc_now(),
expires_at=time.time() + data["expires_in"],
)
atomic_json(path, updated)
return updated
def models(args, session=None):
session = session or new_session()
with credential_lock(args.state_dir) as directory:
path = credentials_path(directory)
creds = read_credentials(directory)
if not isinstance(creds, dict):
raise AppError("not_authorized")
if creds.get("expires_at", 0) <= time.time() + 120:
creds = refresh(session, path, creds)
response = _request(
session,
"GET",
MODELS_URL,
headers={"Authorization": "Bearer " + creds["access_token"]},
)
data = _safe_response(response)
entries = data.get("models")
if not isinstance(entries, list):
raise AppError("models_response_invalid")
visible = []
for item in entries:
if (
isinstance(item, dict)
and item.get("visibility") == "list"
and isinstance(item.get("slug"), str)
and isinstance(item.get("display_name"), str)
):
visible.append({"slug": item["slug"], "display_name": item["display_name"]})
print(json.dumps(visible, separators=(",", ":")))
def parser():
result = argparse.ArgumentParser(prog="affine-chatgpt")
result.add_argument("--state-dir", type=Path, default=default_state_dir())
commands = result.add_subparsers(dest="command", required=True)
login_parser = commands.add_parser("login")
login_parser.add_argument("--port", type=int, default=1455)
login_parser.add_argument("--timeout", type=int, default=900)
login_parser.add_argument("--host-id-file", type=Path)
commands.add_parser("status")
commands.add_parser("models")
serve_parser = commands.add_parser("serve")
serve_parser.add_argument("--host", default="127.0.0.1")
serve_parser.add_argument("--port", type=int, default=3012)
serve_parser.add_argument("--gateway-key-file", type=Path, required=True)
return result
def main(argv=None):
args = parser().parse_args(argv)
try:
if args.command == "login":
if not 0 <= args.port <= 65535 or args.timeout <= 0:
raise AppError("invalid_argument")
login(args)
elif args.command == "status":
status(args)
elif args.command == "models":
models(args)
else:
if not 0 <= args.port <= 65535:
raise AppError("invalid_argument")
try:
ipaddress.ip_address(args.host)
except ValueError:
raise AppError("invalid_argument") from None
from affine_gateway import serve
serve(args)
except AppError as error:
print(f"error: {error}", file=sys.stderr)
return 1
except OSError:
print("error: local_io_error", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,612 @@
"""Minimal OpenAI Responses-compatible gateway for AFFiNE."""
import hmac
import json
import os
import re
import socket
import stat
import threading
import time
from typing import cast
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
from urllib.parse import urlsplit
import requests
import affine_chatgpt as auth
MAX_BODY = 2 * 1024 * 1024
MAX_EVENT = 8 * 1024 * 1024
CONNECT_TIMEOUT = 15
READ_TIMEOUT = 90
SOCKET_TIMEOUT = 95
HEADER_TIMEOUT = 10
CATALOG_TTL = 300
MAX_CONCURRENT = 16
MAX_CONNECTIONS = 32
NAMESPACE = "affine"
NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,128}$")
NAMESPACE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
SAFE_UPSTREAM_CODES = {
"invalid_request_error",
"model_not_found",
"rate_limit_exceeded",
"server_error",
"insufficient_quota",
}
IGNORED_FIELDS = {
"max_output_tokens",
"max_tool_calls",
"metadata",
"moderation",
"multi_agent",
"prompt_cache_retention",
"safety_identifier",
"temperature",
"top_logprobs",
"top_p",
"truncation",
"user",
}
REJECTED_FIELDS = {"background", "conversation", "previous_response_id", "prompt"}
class GatewayError(Exception):
"""Expected client/upstream failure safe for public output."""
def __init__(self, status, code):
super().__init__(code)
self.status = status
self.code = code
def read_gateway_key(path):
try:
info = path.lstat()
except OSError:
raise auth.AppError("invalid_gateway_key") from None
if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
raise auth.AppError("invalid_gateway_key")
try:
descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(descriptor, "r", encoding="utf-8") as stream:
value = stream.read(4097).strip()
except (OSError, UnicodeError):
raise auth.AppError("invalid_gateway_key") from None
if len(value) < 32 or len(value) > 4096 or "\n" in value or "\r" in value:
raise auth.AppError("invalid_gateway_key")
return value
def new_session():
session = requests.Session()
session.trust_env = False
return session
def _response_json(response, code):
if response.is_redirect:
raise GatewayError(response.status_code, "upstream_redirect")
try:
value = response.json()
except (requests.RequestException, ValueError):
raise GatewayError(502, code) from None
if not isinstance(value, dict):
raise GatewayError(502, code)
return value
class Provider:
def __init__(self, state_dir, session=None, now=time.time):
self.state_dir = state_dir
self.session = session or new_session()
self.now = now
self.catalog = None
self.catalog_at = 0
self.lock = threading.Lock()
def credentials(self):
with auth.credential_lock(self.state_dir) as directory:
path = auth.credentials_path(directory)
creds = auth.read_credentials(directory)
if not isinstance(creds, dict):
raise auth.AppError("not_authorized")
if creds.get("expires_at", 0) <= self.now() + 120:
creds = auth.refresh(self.session, path, creds)
return creds
def ready(self):
self.credentials()
def models(self):
with self.lock:
if self.catalog is not None and self.now() - self.catalog_at < CATALOG_TTL:
return list(self.catalog)
creds = self.credentials()
response = auth._request(
self.session,
"GET",
auth.MODELS_URL,
headers={"Authorization": "Bearer " + creds["access_token"]},
)
if response.is_redirect or response.status_code != 200:
raise GatewayError(response.status_code, "upstream_models_error")
data = _response_json(response, "upstream_models_invalid")
entries = data.get("models")
if not isinstance(entries, list):
raise GatewayError(502, "upstream_models_invalid")
catalog = []
for item in entries:
if (
isinstance(item, dict)
and item.get("visibility") == "list"
and isinstance(item.get("slug"), str)
and item["slug"]
and isinstance(item.get("display_name"), str)
):
catalog.append((item["slug"], item["display_name"]))
self.catalog = catalog
self.catalog_at = self.now()
return list(catalog)
def response(self, body):
if auth.RESPONSES_URL != "https://api.openai.com/v1/responses":
raise GatewayError(500, "endpoint_not_allowed")
creds = self.credentials()
try:
return self.session.request(
"POST",
auth.RESPONSES_URL,
headers={
"Authorization": "Bearer " + creds["access_token"],
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
json=body,
stream=True,
timeout=(CONNECT_TIMEOUT, READ_TIMEOUT),
allow_redirects=False,
)
except requests.RequestException:
raise GatewayError(502, "upstream_network_error") from None
def _copy_keys(value, allowed):
return {key: value[key] for key in allowed if key in value}
def _normalize_content(content, role):
if isinstance(content, str):
return [{"type": "output_text" if role == "assistant" else "input_text", "text": content}]
if not isinstance(content, list) or not content:
raise GatewayError(400, "invalid_input")
result = []
for part in content:
if not isinstance(part, dict) or part.get("type") not in {"input_text", "output_text"}:
raise GatewayError(400, "unsupported_media")
if not isinstance(part.get("text"), str):
raise GatewayError(400, "invalid_input")
result.append({"type": part["type"], "text": part["text"]})
return result
def _normalize_item(item):
if not isinstance(item, dict):
raise GatewayError(400, "invalid_input")
item_type = item.get("type")
if item_type in (None, "message"):
role = item.get("role")
if role == "system":
role = "developer"
if role not in {"user", "assistant", "developer"}:
raise GatewayError(400, "invalid_input")
return {
"type": "message",
"role": role,
"content": _normalize_content(item.get("content"), role),
}
if item_type == "function_call":
result = _copy_keys(item, {"id", "call_id", "name", "arguments", "namespace", "status"})
if not all(isinstance(result.get(key), str) and result[key] for key in ("call_id", "name", "arguments")):
raise GatewayError(400, "invalid_input")
result["type"] = item_type
return result
if item_type == "function_call_output":
result = _copy_keys(item, {"id", "call_id", "output", "status"})
if not isinstance(result.get("call_id"), str) or not result["call_id"] or not isinstance(result.get("output"), str):
raise GatewayError(400, "invalid_input")
result["type"] = item_type
return result
if item_type == "reasoning":
result = _copy_keys(item, {"id", "summary", "content", "encrypted_content", "status"})
if not any(key in result for key in ("summary", "content", "encrypted_content")):
raise GatewayError(400, "invalid_input")
result["type"] = item_type
return result
raise GatewayError(400, "unsupported_input_type")
def _normalize_inner_tool(tool):
if not isinstance(tool, dict) or tool.get("type") not in {"function", "custom"}:
raise GatewayError(400, "unsupported_tool")
name = tool.get("name")
if not isinstance(name, str) or not NAME_RE.fullmatch(name):
raise GatewayError(400, "invalid_tool")
if tool["type"] == "function":
allowed = {"type", "name", "description", "parameters", "strict"}
else:
allowed = {"type", "name", "description", "format"}
if set(tool) - allowed:
raise GatewayError(400, "unsupported_tool_field")
return _copy_keys(tool, allowed)
def _normalize_tools(tools):
if not isinstance(tools, list) or not tools:
raise GatewayError(400, "invalid_tools")
if all(isinstance(tool, dict) and tool.get("type") in {"function", "custom"} for tool in tools):
return [{
"type": "namespace",
"name": NAMESPACE,
"description": "Functions provided and executed by AFFiNE.",
"tools": [_normalize_inner_tool(tool) for tool in tools],
}]
result = []
for namespace in tools:
if not isinstance(namespace, dict) or set(namespace) - {"type", "name", "description", "tools"}:
raise GatewayError(400, "unsupported_tool")
name = namespace.get("name")
nested = namespace.get("tools")
if namespace.get("type") != "namespace" or not isinstance(name, str) or not NAMESPACE_RE.fullmatch(name):
raise GatewayError(400, "unsupported_tool")
if not isinstance(namespace.get("description"), str) or not isinstance(nested, list) or not nested:
raise GatewayError(400, "invalid_tools")
result.append({
"type": "namespace",
"name": name,
"description": namespace["description"],
"tools": [_normalize_inner_tool(tool) for tool in nested],
})
return result
def _normalize_choice(choice, had_flat_tools):
if isinstance(choice, str) and choice in {"auto", "none", "required"}:
return choice
if not isinstance(choice, dict):
raise GatewayError(400, "unsupported_tool_choice")
result = dict(choice)
if result.get("type") in {"function", "custom"} and had_flat_tools:
if set(result) - {"type", "name"} or not isinstance(result.get("name"), str):
raise GatewayError(400, "unsupported_tool_choice")
result["namespace"] = NAMESPACE
return result
if result.get("type") in {"function", "custom"}:
if set(result) - {"type", "name", "namespace"}:
raise GatewayError(400, "unsupported_tool_choice")
return result
raise GatewayError(400, "unsupported_tool_choice")
def normalize_request(value, eligible):
if not isinstance(value, dict):
raise GatewayError(400, "invalid_json")
allowed = {"model", "input", "instructions", "tools", "tool_choice", "store", "stream"}
unknown = set(value) - allowed - IGNORED_FIELDS - REJECTED_FIELDS
if set(value) & REJECTED_FIELDS:
raise GatewayError(400, "unsupported_parameter")
if unknown:
raise GatewayError(400, "unsupported_parameter")
if "stream" in value and not isinstance(value["stream"], bool):
raise GatewayError(400, "invalid_stream")
if "store" in value and not isinstance(value["store"], bool):
raise GatewayError(400, "invalid_store")
model = value.get("model")
if not isinstance(model, str) or model not in eligible:
raise GatewayError(400, "model_not_available")
incoming = value.get("input")
if not isinstance(incoming, list) or not incoming:
raise GatewayError(400, "invalid_input")
result = {
"model": model,
"input": [_normalize_item(item) for item in incoming],
"store": False,
"stream": True,
}
if "instructions" in value:
if not isinstance(value["instructions"], str):
raise GatewayError(400, "invalid_instructions")
result["instructions"] = value["instructions"]
if "tools" in value:
flat = all(isinstance(tool, dict) and tool.get("type") in {"function", "custom"} for tool in value["tools"]) if isinstance(value["tools"], list) else False
result["tools"] = _normalize_tools(value["tools"])
if "tool_choice" in value:
result["tool_choice"] = _normalize_choice(value["tool_choice"], flat)
elif "tool_choice" in value:
raise GatewayError(400, "unsupported_tool_choice")
return result
def _events(response):
buffer = b""
try:
for chunk in response.iter_content(chunk_size=16384):
if not chunk:
continue
buffer += chunk
if len(buffer) > MAX_EVENT:
raise GatewayError(502, "upstream_stream_invalid")
while True:
positions = [(buffer.find(b"\n\n"), 2), (buffer.find(b"\r\n\r\n"), 4)]
positions = [(position, size) for position, size in positions if position >= 0]
if not positions:
break
position, size = min(positions)
raw, buffer = buffer[: position + size], buffer[position + size :]
yield raw, _event_data(raw)
if buffer.strip():
raise GatewayError(502, "upstream_stream_interrupted")
except requests.RequestException:
raise GatewayError(502, "upstream_stream_interrupted") from None
def _event_data(raw):
data = []
for line in raw.replace(b"\r\n", b"\n").split(b"\n"):
if line.startswith(b"data:"):
data.append(line[5:].lstrip())
if not data or b"\n".join(data) == b"[DONE]":
return None
try:
value = json.loads(b"\n".join(data))
except (ValueError, UnicodeError):
raise GatewayError(502, "upstream_stream_invalid") from None
if not isinstance(value, dict) or not isinstance(value.get("type"), str):
raise GatewayError(502, "upstream_stream_invalid")
return value
def _upstream_error(response):
code = "upstream_http_error"
try:
value = response.json()
candidate = value.get("error", {}).get("code")
if candidate in SAFE_UPSTREAM_CODES:
code = candidate
except (requests.RequestException, ValueError, AttributeError):
return GatewayError(response.status_code, code)
return GatewayError(response.status_code, code)
class GatewayServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
block_on_close = False
def __init__(
self,
address,
provider,
key,
max_concurrent=MAX_CONCURRENT,
max_connections=MAX_CONNECTIONS,
):
self.provider = provider
self.gateway_key = key
self.capacity = threading.BoundedSemaphore(max_concurrent)
self.connection_capacity = threading.BoundedSemaphore(max_connections)
super().__init__(address, GatewayHandler)
def get_request(self):
request, address = super().get_request()
request.settimeout(HEADER_TIMEOUT)
return request, address
def process_request(self, request, client_address):
if not self.connection_capacity.acquire(blocking=False):
self.shutdown_request(request)
return
try:
super().process_request(request, client_address)
except BaseException:
self.connection_capacity.release()
raise
def process_request_thread(self, request, client_address):
try:
super().process_request_thread(request, client_address)
finally:
self.connection_capacity.release()
def handle_error(self, request, client_address):
return
class GatewayHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, format, *args):
return
@property
def gateway(self):
return cast(GatewayServer, self.server)
def _authorized(self):
value = self.headers.get("Authorization", "")
prefix = "Bearer "
supplied = value[len(prefix) :] if value.startswith(prefix) else ""
return hmac.compare_digest(supplied.encode(), self.gateway.gateway_key.encode())
def _json(self, status, value):
body = json.dumps(value, separators=(",", ":")).encode()
try:
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Cache-Control", "no-store")
self.send_header("Connection", "close")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
self.close_connection = True
except OSError:
return
def _error(self, error):
self.close_connection = True
self._json(error.status, {"error": {"message": "Gateway request failed.", "type": "gateway_error", "code": error.code}})
def _enter(self):
if not self.gateway.capacity.acquire(blocking=False):
self._error(GatewayError(503, "gateway_busy"))
return False
return True
def do_GET(self):
self.connection.settimeout(SOCKET_TIMEOUT)
if not self._enter():
return
try:
target = urlsplit(self.path)
if target.query or target.fragment:
self._error(GatewayError(404, "not_found"))
return
path = target.path
if path == "/healthz":
self._json(200, {"status": "ready"})
return
if not self._authorized():
self._error(GatewayError(401, "unauthorized"))
return
if path != "/v1/models":
self._error(GatewayError(404, "not_found"))
return
data = [{"id": slug, "object": "model", "created": 0, "owned_by": "openai"} for slug, _name in self.gateway.provider.models()]
self._json(200, {"object": "list", "data": data})
except GatewayError as error:
self._error(error)
except (auth.AppError, OSError):
self._error(GatewayError(503, "credentials_unavailable"))
finally:
self.gateway.capacity.release()
def do_POST(self):
self.connection.settimeout(SOCKET_TIMEOUT)
if not self._enter():
return
upstream = None
try:
if not self._authorized():
raise GatewayError(401, "unauthorized")
target = urlsplit(self.path)
if target.path != "/v1/responses" or target.query or target.fragment:
raise GatewayError(404, "not_found")
if self.headers.get("Transfer-Encoding") is not None:
raise GatewayError(400, "unsupported_transfer_encoding")
content_type = self.headers.get("Content-Type", "").lower().replace(" ", "")
if content_type not in {"application/json", "application/json;charset=utf-8"}:
raise GatewayError(415, "unsupported_content_type")
lengths = self.headers.get_all("Content-Length", [])
if len(lengths) != 1:
raise GatewayError(400, "invalid_content_length")
raw_length = lengths[0]
try:
length = int(raw_length) if raw_length is not None else -1
except ValueError:
length = -1
if length < 0:
raise GatewayError(411, "content_length_required")
if length > MAX_BODY:
raise GatewayError(413, "request_too_large")
try:
value = json.loads(self.rfile.read(length))
except (ValueError, UnicodeError):
raise GatewayError(400, "invalid_json") from None
eligible = {slug for slug, _name in self.gateway.provider.models()}
body = normalize_request(value, eligible)
wants_stream = value.get("stream") is True
upstream = self.gateway.provider.response(body)
if upstream.is_redirect or upstream.status_code != 200:
raise _upstream_error(upstream)
media_type = upstream.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
if media_type and media_type != "text/event-stream":
raise GatewayError(502, "upstream_content_type_invalid")
if wants_stream:
self._stream(upstream)
else:
self._aggregate(upstream)
except GatewayError as error:
self._error(error)
except (auth.AppError, OSError):
self._error(GatewayError(503, "credentials_unavailable"))
finally:
if upstream is not None:
upstream.close()
self.gateway.capacity.release()
def _stream(self, upstream):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-store")
self.send_header("Connection", "close")
self.end_headers()
terminal = False
try:
for raw, event in _events(upstream):
self.wfile.write(raw)
self.wfile.flush()
if event and event["type"] in {"response.completed", "response.failed", "response.incomplete", "error"}:
terminal = True
if not terminal:
raise GatewayError(502, "upstream_stream_interrupted")
except (GatewayError, OSError):
if not terminal:
safe = b'event: error\ndata: {"type":"error","code":"upstream_stream_interrupted","message":"Gateway stream interrupted."}\n\n'
try:
self.wfile.write(safe)
self.wfile.flush()
except OSError:
return
finally:
self.close_connection = True
def _aggregate(self, upstream):
completed = None
terminal_error = None
output_items = {}
for _raw, event in _events(upstream):
if event is None:
continue
if event["type"] == "response.output_item.done":
index = event.get("output_index")
item = event.get("item")
if isinstance(index, int) and not isinstance(index, bool) and 0 <= index < 1024 and isinstance(item, dict):
output_items[index] = item
else:
terminal_error = "upstream_response_invalid"
elif event["type"] == "response.completed":
response = event.get("response")
if isinstance(response, dict) and response.get("status") == "completed" and isinstance(response.get("output"), list):
completed = response
else:
terminal_error = "upstream_response_invalid"
elif event["type"] in {"response.failed", "response.incomplete", "error"}:
terminal_error = "upstream_response_failed"
if terminal_error or completed is None:
raise GatewayError(502, terminal_error or "upstream_stream_interrupted")
if not completed["output"] and output_items:
completed = {**completed, "output": [output_items[index] for index in sorted(output_items)]}
self._json(200, completed)
def serve(args):
key = read_gateway_key(args.gateway_key_file)
provider = Provider(args.state_dir)
provider.ready()
server = GatewayServer((args.host, args.port), provider, key)
try:
server.serve_forever(poll_interval=0.25)
finally:
server.server_close()