enzo-agent 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- enzo/__init__.py +5 -0
- enzo/__main__.py +22 -0
- enzo/_release.json +25 -0
- enzo/accounts/__init__.py +5 -0
- enzo/accounts/chatgpt.py +524 -0
- enzo/accounts/check.py +76 -0
- enzo/accounts/service.py +259 -0
- enzo/accounts/store.py +176 -0
- enzo/accounts/vault.py +145 -0
- enzo/agent/__init__.py +1 -0
- enzo/agent/approvals.py +47 -0
- enzo/agent/history.py +71 -0
- enzo/agent/loop.py +398 -0
- enzo/agent/prompt.py +61 -0
- enzo/agent/service.py +218 -0
- enzo/agent/system_prompt.md +19 -0
- enzo/brain/__init__.py +62 -0
- enzo/brain/adapters/__init__.py +1 -0
- enzo/brain/adapters/anthropic_brain.py +323 -0
- enzo/brain/adapters/openai_brain.py +451 -0
- enzo/brain/brains.toml +150 -0
- enzo/brain/config.py +98 -0
- enzo/brain/errors.py +55 -0
- enzo/brain/factory.py +88 -0
- enzo/brain/fake.py +142 -0
- enzo/brain/models.py +205 -0
- enzo/brain/pricing.py +62 -0
- enzo/brain/provider.py +86 -0
- enzo/brain/router.py +454 -0
- enzo/brain/toolcall.py +46 -0
- enzo/brain/transport.py +42 -0
- enzo/bundled_db.py +29 -0
- enzo/cli.py +238 -0
- enzo/config.py +41 -0
- enzo/connectors/__init__.py +1 -0
- enzo/connectors/github.py +326 -0
- enzo/connectors/mcp.py +221 -0
- enzo/gateway/__init__.py +1 -0
- enzo/gateway/app.py +220 -0
- enzo/gateway/chatgpt.py +128 -0
- enzo/gateway/connections.py +171 -0
- enzo/gateway/conversations.py +268 -0
- enzo/gateway/usage.py +101 -0
- enzo/launcher.py +194 -0
- enzo/migrations/README +1 -0
- enzo/migrations/env.py +99 -0
- enzo/migrations/script.py.mako +28 -0
- enzo/migrations/versions/0001_transcripts_and_ledgers.py +160 -0
- enzo/migrations/versions/0002_brain_call_billing.py +31 -0
- enzo/migrations/versions/0003_approval_call_and_card.py +32 -0
- enzo/paths.py +34 -0
- enzo/store/__init__.py +1 -0
- enzo/store/migrate.py +18 -0
- enzo/store/repository.py +261 -0
- enzo/store/schema.py +143 -0
- enzo/tools/__init__.py +13 -0
- enzo/tools/fence.py +17 -0
- enzo/tools/files.py +305 -0
- enzo/tools/registry.py +289 -0
- enzo/tools/web.py +290 -0
- enzo/tui.py +138 -0
- enzo/webapp/assets/index-D0QtGysA.css +1 -0
- enzo/webapp/assets/index-OyFhUMrC.js +11 -0
- enzo/webapp/index.html +13 -0
- enzo_agent-0.1.0.dist-info/METADATA +91 -0
- enzo_agent-0.1.0.dist-info/RECORD +69 -0
- enzo_agent-0.1.0.dist-info/WHEEL +4 -0
- enzo_agent-0.1.0.dist-info/entry_points.txt +4 -0
- enzo_agent-0.1.0.dist-info/licenses/LICENSE +201 -0
enzo/__init__.py
ADDED
enzo/__main__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""``enzo-server`` entry point: run the gateway with uvicorn."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
import uvicorn
|
|
6
|
+
|
|
7
|
+
from enzo.accounts.vault import generate_key
|
|
8
|
+
from enzo.config import Settings
|
|
9
|
+
from enzo.gateway.app import create_app
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main() -> None:
|
|
13
|
+
if "--new-vault-key" in sys.argv:
|
|
14
|
+
# A fresh key for the encrypted vault; store it as ENZO_VAULT_KEY, never in the repo.
|
|
15
|
+
print(generate_key())
|
|
16
|
+
return
|
|
17
|
+
settings = Settings()
|
|
18
|
+
uvicorn.run(create_app(settings), host=settings.host, port=settings.port)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
if __name__ == "__main__":
|
|
22
|
+
main()
|
enzo/_release.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": "0.1.0",
|
|
3
|
+
"tui": {
|
|
4
|
+
"darwin-arm64": {
|
|
5
|
+
"name": "enzo-tui-darwin-arm64",
|
|
6
|
+
"sha256": "a8eb089e6740935b7505244e06f86dc4e794ed7af827de799b5d5f4705e11b93",
|
|
7
|
+
"size": 102531216
|
|
8
|
+
},
|
|
9
|
+
"darwin-x64": {
|
|
10
|
+
"name": "enzo-tui-darwin-x64",
|
|
11
|
+
"sha256": "e5aed160b5298f5511281e41a9197615bfa4bc83c9902882919a612e641b2297",
|
|
12
|
+
"size": 113093968
|
|
13
|
+
},
|
|
14
|
+
"linux-x64": {
|
|
15
|
+
"name": "enzo-tui-linux-x64",
|
|
16
|
+
"sha256": "b51d082758238ed9ad20e4484ba1e08e3d9726b8175bc75a83d98ebe8f136507",
|
|
17
|
+
"size": 133916848
|
|
18
|
+
},
|
|
19
|
+
"linux-arm64": {
|
|
20
|
+
"name": "enzo-tui-linux-arm64",
|
|
21
|
+
"sha256": "fce3f99552ea0c39955fc5a7983285e4f466fc4786187ed5f3a26af1837e4760",
|
|
22
|
+
"size": 131779576
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"""Bring your own account: users connect their own provider credentials (decided 2026-11-17).
|
|
2
|
+
|
|
3
|
+
Secrets live only in a vault (spec §11.2): the OS keychain, or an AES-GCM encrypted file whose key
|
|
4
|
+
comes from ENZO_VAULT_KEY. Never plaintext, never the database, logs or transcripts.
|
|
5
|
+
"""
|
enzo/accounts/chatgpt.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
"""Sign in with ChatGPT: the user's ChatGPT plan pays for GPT replies, no API key (ADR 0013).
|
|
2
|
+
|
|
3
|
+
OpenAI's documented flow for open-source, locally hosted apps ("ChatGPT plan usage",
|
|
4
|
+
developers.openai.com/siwc, read 2026-11-18):
|
|
5
|
+
|
|
6
|
+
1. A stable, opaque host id (``urn:uuid:…``) per installation, chosen before the first sign-in.
|
|
7
|
+
2. Authorization code + PKCE + OpenID Connect in the system browser. The callback is the gateway
|
|
8
|
+
itself, ``http://127.0.0.1:<port>/auth/callback``. The first sign-in registers a client
|
|
9
|
+
(``client_id=dynamic_agent_client``) and the callback returns the issued client id, which every
|
|
10
|
+
later sign-in reuses.
|
|
11
|
+
3. The code is exchanged, the ID token verified (signature against OpenAI's JWKS, issuer,
|
|
12
|
+
audience, expiry, nonce), and the granted scopes must include ``chatgpt.tokens.use.direct``.
|
|
13
|
+
4. Tokens live in the vault. Access tokens last an hour and are renewed shortly before expiry, one
|
|
14
|
+
renewal at a time, because refresh tokens rotate.
|
|
15
|
+
5. Replies use the public Responses API with the access token (``OpenAIBrain`` in plan mode).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import base64
|
|
20
|
+
import hashlib
|
|
21
|
+
import logging
|
|
22
|
+
import re
|
|
23
|
+
import secrets
|
|
24
|
+
import time
|
|
25
|
+
import uuid
|
|
26
|
+
from collections.abc import Callable, Mapping
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from datetime import UTC, datetime, timedelta
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any, Literal
|
|
31
|
+
from urllib.parse import quote, urlencode
|
|
32
|
+
|
|
33
|
+
import httpx2
|
|
34
|
+
import jwt
|
|
35
|
+
from pydantic import BaseModel, ConfigDict, SecretStr, ValidationError
|
|
36
|
+
|
|
37
|
+
from enzo.accounts.store import ChatGPTCredential, CredentialStore
|
|
38
|
+
from enzo.accounts.vault import write_private
|
|
39
|
+
from enzo.brain.errors import (
|
|
40
|
+
AuthError,
|
|
41
|
+
ProviderConnectionError,
|
|
42
|
+
ProviderServerError,
|
|
43
|
+
ProviderTimeoutError,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
log = logging.getLogger("enzo.accounts.chatgpt")
|
|
47
|
+
|
|
48
|
+
#: The account a ChatGPT sign-in connects: GPT models, paid by the plan instead of a key.
|
|
49
|
+
PROVIDER = "openai"
|
|
50
|
+
ISSUER = "https://auth.openai.com"
|
|
51
|
+
AUTHORIZE_URL = f"{ISSUER}/api/accounts/authorize"
|
|
52
|
+
TOKEN_URL = f"{ISSUER}/api/accounts/oauth/token"
|
|
53
|
+
DISCOVERY_URL = f"{ISSUER}/.well-known/openid-configuration"
|
|
54
|
+
RESOURCE = "https://api.openai.com/v1"
|
|
55
|
+
MODELS_URL = f"{RESOURCE}/models"
|
|
56
|
+
PLAN_SCOPE = "chatgpt.tokens.use.direct"
|
|
57
|
+
SCOPES = ("openid", "profile", "email", "offline_access", "resource.invoke", PLAN_SCOPE)
|
|
58
|
+
DYNAMIC_CLIENT = "dynamic_agent_client"
|
|
59
|
+
AGENT_NAME = "Enzo"
|
|
60
|
+
CALLBACK_PATH = "/auth/callback"
|
|
61
|
+
USAGE_URL = "https://chatgpt.com/settings/usage"
|
|
62
|
+
#: An unfinished sign-in is forgotten after this long.
|
|
63
|
+
ATTEMPT_TTL_S = 10 * 60
|
|
64
|
+
#: Renew this long before the access token expires, so no request carries a dying token.
|
|
65
|
+
REFRESH_MARGIN = timedelta(minutes=2)
|
|
66
|
+
#: Refresh errors that mean the sign-in is over: sign in again (OpenAI's list).
|
|
67
|
+
UNUSABLE_REFRESH = frozenset(
|
|
68
|
+
{
|
|
69
|
+
"invalid_grant",
|
|
70
|
+
"invalid_refresh_token",
|
|
71
|
+
"token_expired",
|
|
72
|
+
"refresh_token_expired",
|
|
73
|
+
"refresh_token_invalidated",
|
|
74
|
+
"refresh_token_reused",
|
|
75
|
+
}
|
|
76
|
+
)
|
|
77
|
+
#: Asymmetric algorithms only: an ID token is never trusted on a shared secret.
|
|
78
|
+
_ALGORITHMS = frozenset({"RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384"})
|
|
79
|
+
_RECORD = "chatgpt-registration"
|
|
80
|
+
|
|
81
|
+
SIGN_IN_AGAIN = "Your ChatGPT sign-in has ended. Sign in again: /login chatgpt"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class SignInError(Exception):
|
|
85
|
+
"""A sign-in attempt failed. The message is shown to the user as is."""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class Registration(BaseModel):
|
|
89
|
+
"""Kept across sign-outs, so a later sign-in reuses the same client (OpenAI's guidance)."""
|
|
90
|
+
|
|
91
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
92
|
+
|
|
93
|
+
client_id: str
|
|
94
|
+
subject: str
|
|
95
|
+
email: str | None = None
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class Attempt:
|
|
100
|
+
"""One sign-in in progress: secrets that only this gateway and the browser round trip see."""
|
|
101
|
+
|
|
102
|
+
id: str
|
|
103
|
+
state: str
|
|
104
|
+
nonce: str
|
|
105
|
+
verifier: str
|
|
106
|
+
redirect_uri: str
|
|
107
|
+
#: The issued client id for a returning account, else ``dynamic_agent_client``.
|
|
108
|
+
client_id: str
|
|
109
|
+
#: The account a returning sign-in must come back as; None registers a new one.
|
|
110
|
+
registration: Registration | None
|
|
111
|
+
started: float
|
|
112
|
+
status: Literal["pending", "connected", "failed"] = "pending"
|
|
113
|
+
message: str | None = None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def host_id(config_dir: Path) -> str:
|
|
117
|
+
"""This installation's ``ext_agent_host_id``: created once, then reused for every sign-in."""
|
|
118
|
+
path = config_dir / "host-id"
|
|
119
|
+
try:
|
|
120
|
+
value = path.read_text(encoding="utf-8").strip()
|
|
121
|
+
except FileNotFoundError:
|
|
122
|
+
value = ""
|
|
123
|
+
if not value.startswith("urn:uuid:"):
|
|
124
|
+
value = f"urn:uuid:{uuid.uuid4()}"
|
|
125
|
+
write_private(path, value + "\n")
|
|
126
|
+
return value
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def challenge(verifier: str) -> str:
|
|
130
|
+
"""PKCE S256: base64url of the SHA-256 of the verifier, without padding."""
|
|
131
|
+
digest = hashlib.sha256(verifier.encode("ascii")).digest()
|
|
132
|
+
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class ChatGPTSignIn:
|
|
136
|
+
"""Signs in, keeps the tokens fresh, and signs out, for one ChatGPT account at a time."""
|
|
137
|
+
|
|
138
|
+
def __init__(
|
|
139
|
+
self,
|
|
140
|
+
store: CredentialStore,
|
|
141
|
+
host: str,
|
|
142
|
+
http: httpx2.AsyncClient,
|
|
143
|
+
*,
|
|
144
|
+
on_change: Callable[[], None],
|
|
145
|
+
clock: Callable[[], float] = time.monotonic,
|
|
146
|
+
now: Callable[[], datetime] = lambda: datetime.now(UTC),
|
|
147
|
+
) -> None:
|
|
148
|
+
self._store = store
|
|
149
|
+
self._host = host
|
|
150
|
+
self._http = http
|
|
151
|
+
self._on_change = on_change
|
|
152
|
+
self._clock = clock
|
|
153
|
+
self._now = now
|
|
154
|
+
self._attempts: dict[str, Attempt] = {}
|
|
155
|
+
self._discovery: dict[str, Any] | None = None
|
|
156
|
+
self._jwks: jwt.PyJWKSet | None = None
|
|
157
|
+
self._renewing = asyncio.Lock()
|
|
158
|
+
|
|
159
|
+
# ---------- signing in ----------
|
|
160
|
+
|
|
161
|
+
def start(self, redirect_uri: str, *, new_account: bool = False) -> Attempt:
|
|
162
|
+
"""Begin a sign-in. A returning account reuses its client; ``new_account`` registers one."""
|
|
163
|
+
self._forget_stale()
|
|
164
|
+
registration = None if new_account else self.registration()
|
|
165
|
+
attempt = Attempt(
|
|
166
|
+
id=secrets.token_urlsafe(16),
|
|
167
|
+
state=secrets.token_urlsafe(32),
|
|
168
|
+
nonce=secrets.token_urlsafe(32),
|
|
169
|
+
verifier=secrets.token_urlsafe(64),
|
|
170
|
+
redirect_uri=redirect_uri,
|
|
171
|
+
client_id=registration.client_id if registration else DYNAMIC_CLIENT,
|
|
172
|
+
registration=registration,
|
|
173
|
+
started=self._clock(),
|
|
174
|
+
)
|
|
175
|
+
self._attempts[attempt.id] = attempt
|
|
176
|
+
return attempt
|
|
177
|
+
|
|
178
|
+
def attempt(self, login_id: str) -> Attempt | None:
|
|
179
|
+
self._forget_stale()
|
|
180
|
+
return self._attempts.get(login_id)
|
|
181
|
+
|
|
182
|
+
def authorize_url(self, attempt: Attempt) -> str:
|
|
183
|
+
"""OpenAI's sign-in page for this attempt. Carries no token, only one-time values."""
|
|
184
|
+
params = {
|
|
185
|
+
"response_type": "code",
|
|
186
|
+
"client_id": attempt.client_id,
|
|
187
|
+
"redirect_uri": attempt.redirect_uri,
|
|
188
|
+
"scope": " ".join(SCOPES),
|
|
189
|
+
"resource": RESOURCE,
|
|
190
|
+
"state": attempt.state,
|
|
191
|
+
"nonce": attempt.nonce,
|
|
192
|
+
"code_challenge": challenge(attempt.verifier),
|
|
193
|
+
"code_challenge_method": "S256",
|
|
194
|
+
"ext_agent_host_id": self._host,
|
|
195
|
+
}
|
|
196
|
+
if attempt.registration is None:
|
|
197
|
+
params["agent_name_hint"] = AGENT_NAME # first registration only
|
|
198
|
+
elif attempt.registration.email:
|
|
199
|
+
params["login_hint"] = attempt.registration.email
|
|
200
|
+
return f"{AUTHORIZE_URL}?{urlencode(params, quote_via=quote)}"
|
|
201
|
+
|
|
202
|
+
async def finish(self, params: Mapping[str, str]) -> Attempt | None:
|
|
203
|
+
"""The browser came back. Returns the attempt with its outcome, or None for an unknown
|
|
204
|
+
state (nothing is touched then). Each state is accepted once."""
|
|
205
|
+
attempt = self._pending_for(params.get("state", ""))
|
|
206
|
+
if attempt is None:
|
|
207
|
+
return None
|
|
208
|
+
try:
|
|
209
|
+
label = await self._complete(attempt, params)
|
|
210
|
+
except SignInError as exc:
|
|
211
|
+
attempt.status, attempt.message = "failed", str(exc)
|
|
212
|
+
except httpx2.HTTPError as exc:
|
|
213
|
+
log.warning("chatgpt sign-in unreachable", extra={"error": type(exc).__name__})
|
|
214
|
+
attempt.status = "failed"
|
|
215
|
+
attempt.message = "Could not reach OpenAI to finish signing in. Check the connection."
|
|
216
|
+
else:
|
|
217
|
+
attempt.status, attempt.message = "connected", f"Signed in with ChatGPT as {label}."
|
|
218
|
+
return attempt
|
|
219
|
+
|
|
220
|
+
async def _complete(self, attempt: Attempt, params: Mapping[str, str]) -> str:
|
|
221
|
+
if (error := params.get("error")) is not None:
|
|
222
|
+
if error == "access_denied":
|
|
223
|
+
msg = "The ChatGPT sign-in was cancelled, so nothing was connected."
|
|
224
|
+
raise SignInError(msg)
|
|
225
|
+
msg = f"ChatGPT sign-in failed ({_code(error)}). Nothing was connected."
|
|
226
|
+
raise SignInError(msg)
|
|
227
|
+
code = params.get("code")
|
|
228
|
+
if not code:
|
|
229
|
+
msg = "ChatGPT sign-in came back without a code. Start it again."
|
|
230
|
+
raise SignInError(msg)
|
|
231
|
+
client_id = self._client_for(attempt, params.get("client_id"))
|
|
232
|
+
tokens = await self._exchange(attempt, client_id, code)
|
|
233
|
+
claims = await self.verify_id_token(tokens["id_token"], client_id, attempt.nonce)
|
|
234
|
+
subject: str = claims["sub"]
|
|
235
|
+
if attempt.registration is not None and subject != attempt.registration.subject:
|
|
236
|
+
msg = (
|
|
237
|
+
"That is a different ChatGPT account from the one Enzo knows, so nothing changed. "
|
|
238
|
+
"To use it instead, run /login chatgpt new."
|
|
239
|
+
)
|
|
240
|
+
raise SignInError(msg)
|
|
241
|
+
email = claims.get("email") if isinstance(claims.get("email"), str) else None
|
|
242
|
+
# The client exists now, whatever was granted: later sign-ins reuse it.
|
|
243
|
+
registration = Registration(client_id=client_id, subject=subject, email=email)
|
|
244
|
+
self._store.keep_record(_RECORD, registration.model_dump_json())
|
|
245
|
+
scopes = tuple(sorted(str(tokens.get("scope", "")).split()))
|
|
246
|
+
if PLAN_SCOPE not in scopes:
|
|
247
|
+
msg = (
|
|
248
|
+
"You signed in, but Enzo was not allowed to use your ChatGPT plan, so nothing was "
|
|
249
|
+
"connected. Sign in again and allow it, or use an API key: /login openai."
|
|
250
|
+
)
|
|
251
|
+
raise SignInError(msg)
|
|
252
|
+
credential = ChatGPTCredential(
|
|
253
|
+
client_id=client_id,
|
|
254
|
+
subject=subject,
|
|
255
|
+
email=email,
|
|
256
|
+
id_token=SecretStr(tokens["id_token"]),
|
|
257
|
+
access_token=SecretStr(tokens["access_token"]),
|
|
258
|
+
refresh_token=SecretStr(tokens["refresh_token"]),
|
|
259
|
+
scopes=scopes,
|
|
260
|
+
expires_at=self._now() + timedelta(seconds=int(tokens["expires_in"])),
|
|
261
|
+
)
|
|
262
|
+
models = await self.plan_models(tokens["access_token"])
|
|
263
|
+
label = email or "your ChatGPT account"
|
|
264
|
+
self._store.connect(PROVIDER, credential, label=label, models=models)
|
|
265
|
+
self._on_change()
|
|
266
|
+
return label
|
|
267
|
+
|
|
268
|
+
def _client_for(self, attempt: Attempt, returned: str | None) -> str:
|
|
269
|
+
if attempt.registration is None:
|
|
270
|
+
if not returned or returned == DYNAMIC_CLIENT:
|
|
271
|
+
msg = "ChatGPT did not finish registering Enzo. Start the sign-in again."
|
|
272
|
+
raise SignInError(msg)
|
|
273
|
+
return returned
|
|
274
|
+
if returned and returned != attempt.client_id:
|
|
275
|
+
msg = "ChatGPT answered for a different app registration, so nothing changed."
|
|
276
|
+
raise SignInError(msg)
|
|
277
|
+
return attempt.client_id
|
|
278
|
+
|
|
279
|
+
async def _exchange(self, attempt: Attempt, client_id: str, code: str) -> dict[str, Any]:
|
|
280
|
+
response = await self._http.post(
|
|
281
|
+
TOKEN_URL,
|
|
282
|
+
data={
|
|
283
|
+
"grant_type": "authorization_code",
|
|
284
|
+
"client_id": client_id,
|
|
285
|
+
"code": code,
|
|
286
|
+
"code_verifier": attempt.verifier,
|
|
287
|
+
"redirect_uri": attempt.redirect_uri,
|
|
288
|
+
"resource": RESOURCE,
|
|
289
|
+
},
|
|
290
|
+
headers={"Accept": "application/json"},
|
|
291
|
+
)
|
|
292
|
+
if response.status_code != httpx2.codes.OK:
|
|
293
|
+
error = _oauth_error(response)
|
|
294
|
+
_log_refusal("code exchange", response, error)
|
|
295
|
+
if error == "invalid_grant":
|
|
296
|
+
msg = "That sign-in expired before Enzo could finish it. Start it again."
|
|
297
|
+
raise SignInError(msg)
|
|
298
|
+
msg = f"OpenAI refused to finish the sign-in ({error or response.status_code})."
|
|
299
|
+
raise SignInError(msg)
|
|
300
|
+
body = _json(response)
|
|
301
|
+
for name in ("access_token", "refresh_token", "id_token"):
|
|
302
|
+
if not isinstance(body.get(name), str) or not body[name]:
|
|
303
|
+
msg = f"OpenAI's sign-in reply had no {name.replace('_', ' ')}. Try again."
|
|
304
|
+
raise SignInError(msg)
|
|
305
|
+
if not isinstance(body.get("expires_in"), int):
|
|
306
|
+
msg = "OpenAI's sign-in reply had no expiry. Try again."
|
|
307
|
+
raise SignInError(msg)
|
|
308
|
+
return body
|
|
309
|
+
|
|
310
|
+
async def verify_id_token(self, token: str, client_id: str, nonce: str) -> dict[str, Any]:
|
|
311
|
+
"""Signature against OpenAI's published keys, then issuer, audience, expiry and nonce."""
|
|
312
|
+
try:
|
|
313
|
+
header = jwt.get_unverified_header(token)
|
|
314
|
+
algorithm = header.get("alg")
|
|
315
|
+
if algorithm not in _ALGORITHMS:
|
|
316
|
+
msg = f"unexpected signing algorithm {algorithm!r}"
|
|
317
|
+
raise jwt.InvalidAlgorithmError(msg)
|
|
318
|
+
key = await self._signing_key(header.get("kid"))
|
|
319
|
+
claims: dict[str, Any] = jwt.decode(
|
|
320
|
+
token,
|
|
321
|
+
key=key.key,
|
|
322
|
+
algorithms=[algorithm],
|
|
323
|
+
audience=client_id,
|
|
324
|
+
issuer=ISSUER,
|
|
325
|
+
leeway=5,
|
|
326
|
+
options={"require": ["sub", "exp", "iat", "aud", "iss"]},
|
|
327
|
+
)
|
|
328
|
+
except jwt.PyJWTError as exc:
|
|
329
|
+
log.warning("chatgpt id token rejected", extra={"reason": type(exc).__name__})
|
|
330
|
+
msg = "Could not verify the ChatGPT sign-in, so nothing was connected."
|
|
331
|
+
raise SignInError(msg) from exc
|
|
332
|
+
if not secrets.compare_digest(str(claims.get("nonce", "")), nonce):
|
|
333
|
+
msg = "The ChatGPT sign-in did not match this attempt, so nothing was connected."
|
|
334
|
+
raise SignInError(msg)
|
|
335
|
+
if not isinstance(claims.get("sub"), str) or not claims["sub"]:
|
|
336
|
+
msg = "The ChatGPT sign-in named no account, so nothing was connected."
|
|
337
|
+
raise SignInError(msg)
|
|
338
|
+
return claims
|
|
339
|
+
|
|
340
|
+
async def _signing_key(self, kid: object) -> jwt.PyJWK:
|
|
341
|
+
# Keys rotate: an unfamiliar kid fetches the set once more before giving up.
|
|
342
|
+
for fresh in (False, True):
|
|
343
|
+
if self._jwks is None or fresh:
|
|
344
|
+
discovery = await self._discover()
|
|
345
|
+
response = await self._http.get(str(discovery["jwks_uri"]))
|
|
346
|
+
response.raise_for_status()
|
|
347
|
+
self._jwks = jwt.PyJWKSet.from_dict(_json(response))
|
|
348
|
+
for key in self._jwks.keys:
|
|
349
|
+
if key.key_id == kid:
|
|
350
|
+
return key
|
|
351
|
+
msg = "OpenAI's signing key for this sign-in was not found"
|
|
352
|
+
raise jwt.InvalidKeyError(msg)
|
|
353
|
+
|
|
354
|
+
async def _discover(self) -> dict[str, Any]:
|
|
355
|
+
if self._discovery is None:
|
|
356
|
+
response = await self._http.get(DISCOVERY_URL)
|
|
357
|
+
response.raise_for_status()
|
|
358
|
+
discovery = _json(response)
|
|
359
|
+
if discovery.get("issuer") != ISSUER or not discovery.get("jwks_uri"):
|
|
360
|
+
msg = "OpenAI's sign-in configuration looked wrong, so nothing was connected."
|
|
361
|
+
raise SignInError(msg)
|
|
362
|
+
self._discovery = discovery
|
|
363
|
+
return self._discovery
|
|
364
|
+
|
|
365
|
+
async def plan_models(self, access_token: str) -> list[str] | None:
|
|
366
|
+
"""The models this ChatGPT account may use, or None when the list can't be read."""
|
|
367
|
+
try:
|
|
368
|
+
response = await self._http.get(
|
|
369
|
+
MODELS_URL, headers={"Authorization": f"Bearer {access_token}"}
|
|
370
|
+
)
|
|
371
|
+
except httpx2.HTTPError:
|
|
372
|
+
return None
|
|
373
|
+
if response.status_code != httpx2.codes.OK:
|
|
374
|
+
_log_refusal("model list", response, _oauth_error(response))
|
|
375
|
+
return None
|
|
376
|
+
models = _json(response).get("models")
|
|
377
|
+
if not isinstance(models, list):
|
|
378
|
+
return None
|
|
379
|
+
return [m["slug"] for m in models if isinstance(m, dict) and isinstance(m.get("slug"), str)]
|
|
380
|
+
|
|
381
|
+
def registration(self) -> Registration | None:
|
|
382
|
+
raw = self._store.record(_RECORD)
|
|
383
|
+
if raw is None:
|
|
384
|
+
return None
|
|
385
|
+
try:
|
|
386
|
+
return Registration.model_validate_json(raw)
|
|
387
|
+
except ValidationError:
|
|
388
|
+
return None
|
|
389
|
+
|
|
390
|
+
def _pending_for(self, state: str) -> Attempt | None:
|
|
391
|
+
self._forget_stale()
|
|
392
|
+
for attempt in self._attempts.values():
|
|
393
|
+
if attempt.state and secrets.compare_digest(attempt.state, state):
|
|
394
|
+
attempt.state = "" # single use, from the first moment: a replay finds nothing
|
|
395
|
+
return attempt
|
|
396
|
+
return None
|
|
397
|
+
|
|
398
|
+
def _forget_stale(self) -> None:
|
|
399
|
+
cutoff = self._clock() - ATTEMPT_TTL_S
|
|
400
|
+
for login_id in [i for i, a in self._attempts.items() if a.started < cutoff]:
|
|
401
|
+
del self._attempts[login_id]
|
|
402
|
+
|
|
403
|
+
# ---------- staying signed in ----------
|
|
404
|
+
|
|
405
|
+
def credential(self) -> ChatGPTCredential | None:
|
|
406
|
+
credential = self._store.credential(PROVIDER)
|
|
407
|
+
return credential if isinstance(credential, ChatGPTCredential) else None
|
|
408
|
+
|
|
409
|
+
async def access_token(self) -> str:
|
|
410
|
+
"""A valid access token, renewed shortly before it expires. One renewal at a time."""
|
|
411
|
+
async with self._renewing:
|
|
412
|
+
credential = self.credential()
|
|
413
|
+
if credential is None:
|
|
414
|
+
raise AuthError(SIGN_IN_AGAIN, provider=PROVIDER, model="")
|
|
415
|
+
if credential.expires_at - self._now() > REFRESH_MARGIN:
|
|
416
|
+
return credential.access_token.get_secret_value()
|
|
417
|
+
renewed = await self._renew(credential)
|
|
418
|
+
return renewed.access_token.get_secret_value()
|
|
419
|
+
|
|
420
|
+
async def _renew(self, credential: ChatGPTCredential) -> ChatGPTCredential:
|
|
421
|
+
ctx = {"provider": PROVIDER, "model": ""}
|
|
422
|
+
try:
|
|
423
|
+
response = await self._http.post(
|
|
424
|
+
TOKEN_URL,
|
|
425
|
+
data={
|
|
426
|
+
"grant_type": "refresh_token",
|
|
427
|
+
"client_id": credential.client_id,
|
|
428
|
+
"refresh_token": credential.refresh_token.get_secret_value(),
|
|
429
|
+
"resource": RESOURCE,
|
|
430
|
+
},
|
|
431
|
+
headers={"Accept": "application/json"},
|
|
432
|
+
)
|
|
433
|
+
except httpx2.TimeoutException as exc:
|
|
434
|
+
msg = "OpenAI did not answer in time while renewing the ChatGPT sign-in"
|
|
435
|
+
raise ProviderTimeoutError(msg, **ctx) from exc
|
|
436
|
+
except httpx2.HTTPError as exc:
|
|
437
|
+
msg = "Could not reach OpenAI to renew the ChatGPT sign-in"
|
|
438
|
+
raise ProviderConnectionError(msg, **ctx) from exc
|
|
439
|
+
if response.status_code == httpx2.codes.OK:
|
|
440
|
+
body = _json(response)
|
|
441
|
+
if not isinstance(body.get("access_token"), str) or not isinstance(
|
|
442
|
+
body.get("expires_in"), int
|
|
443
|
+
):
|
|
444
|
+
msg = "OpenAI's renewal reply was incomplete"
|
|
445
|
+
raise ProviderServerError(msg, **ctx)
|
|
446
|
+
update: dict[str, Any] = {
|
|
447
|
+
"access_token": SecretStr(body["access_token"]),
|
|
448
|
+
"expires_at": self._now() + timedelta(seconds=body["expires_in"]),
|
|
449
|
+
}
|
|
450
|
+
if isinstance(body.get("refresh_token"), str): # it rotates: keep the replacement
|
|
451
|
+
update["refresh_token"] = SecretStr(body["refresh_token"])
|
|
452
|
+
if isinstance(body.get("id_token"), str):
|
|
453
|
+
update["id_token"] = SecretStr(body["id_token"])
|
|
454
|
+
if isinstance(body.get("scope"), str):
|
|
455
|
+
update["scopes"] = tuple(sorted(body["scope"].split()))
|
|
456
|
+
renewed = credential.model_copy(update=update)
|
|
457
|
+
self._store.replace(PROVIDER, renewed)
|
|
458
|
+
return renewed
|
|
459
|
+
error = _oauth_error(response)
|
|
460
|
+
_log_refusal("renewal", response, error)
|
|
461
|
+
if error in UNUSABLE_REFRESH or response.status_code == httpx2.codes.UNAUTHORIZED:
|
|
462
|
+
# Over for good: forget the tokens (the registration stays), say how to come back.
|
|
463
|
+
self._store.disconnect(PROVIDER)
|
|
464
|
+
self._on_change()
|
|
465
|
+
raise AuthError(SIGN_IN_AGAIN, **ctx)
|
|
466
|
+
if response.status_code >= httpx2.codes.INTERNAL_SERVER_ERROR:
|
|
467
|
+
msg = f"OpenAI could not renew the ChatGPT sign-in right now ({response.status_code})"
|
|
468
|
+
raise ProviderServerError(msg, **ctx)
|
|
469
|
+
msg = f"OpenAI refused to renew the ChatGPT sign-in ({error or response.status_code})"
|
|
470
|
+
raise AuthError(msg, **ctx)
|
|
471
|
+
|
|
472
|
+
async def sign_out(self) -> bool:
|
|
473
|
+
"""End the renewable session with OpenAI. True when OpenAI confirmed it. The caller then
|
|
474
|
+
forgets the tokens either way; the registration stays for a later sign-in."""
|
|
475
|
+
credential = self.credential()
|
|
476
|
+
if credential is None:
|
|
477
|
+
return True
|
|
478
|
+
try:
|
|
479
|
+
discovery = await self._discover()
|
|
480
|
+
endpoint = discovery.get("revocation_endpoint")
|
|
481
|
+
if not isinstance(endpoint, str):
|
|
482
|
+
return False
|
|
483
|
+
response = await self._http.post(
|
|
484
|
+
endpoint,
|
|
485
|
+
data={
|
|
486
|
+
"token": credential.refresh_token.get_secret_value(),
|
|
487
|
+
"token_type_hint": "refresh_token",
|
|
488
|
+
"client_id": credential.client_id,
|
|
489
|
+
},
|
|
490
|
+
)
|
|
491
|
+
except (httpx2.HTTPError, SignInError):
|
|
492
|
+
return False
|
|
493
|
+
return response.status_code == httpx2.codes.OK
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _json(response: httpx2.Response) -> dict[str, Any]:
|
|
497
|
+
try:
|
|
498
|
+
body = response.json()
|
|
499
|
+
except ValueError:
|
|
500
|
+
return {}
|
|
501
|
+
return body if isinstance(body, dict) else {}
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _oauth_error(response: httpx2.Response) -> str | None:
|
|
505
|
+
"""The OAuth or Responses error code in a refusal, when it has one."""
|
|
506
|
+
body = _json(response)
|
|
507
|
+
error = body.get("error")
|
|
508
|
+
if isinstance(error, dict):
|
|
509
|
+
error = error.get("code")
|
|
510
|
+
return _code(error) if isinstance(error, str) else None
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def _code(value: str) -> str:
|
|
514
|
+
"""Error codes come from outside: keep only what a code can contain, never free text."""
|
|
515
|
+
return re.sub(r"[^a-z0-9_.-]", "", value.lower())[:64] or "unknown"
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _log_refusal(step: str, response: httpx2.Response, error: str | None) -> None:
|
|
519
|
+
request_id = response.headers.get("openai-request-id") or response.headers.get("x-request-id")
|
|
520
|
+
log.warning(
|
|
521
|
+
"chatgpt %s refused",
|
|
522
|
+
step,
|
|
523
|
+
extra={"status": response.status_code, "error": error, "request_id": request_id},
|
|
524
|
+
)
|
enzo/accounts/check.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Live credential checks: is this key accepted by the provider? (spec §8.2 status check)."""
|
|
2
|
+
|
|
3
|
+
import anthropic
|
|
4
|
+
import httpx2
|
|
5
|
+
import openai
|
|
6
|
+
|
|
7
|
+
from enzo.brain.adapters import anthropic_brain, openai_brain
|
|
8
|
+
from enzo.brain.config import BrainConfig
|
|
9
|
+
from enzo.brain.errors import (
|
|
10
|
+
AuthError,
|
|
11
|
+
ProviderConnectionError,
|
|
12
|
+
ProviderServerError,
|
|
13
|
+
ProviderTimeoutError,
|
|
14
|
+
RateLimitError,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def check_api_key(
|
|
19
|
+
cfg: BrainConfig, api_key: str, *, http_client: httpx2.AsyncClient | None = None
|
|
20
|
+
) -> None:
|
|
21
|
+
"""List models with the key: cheap, read-only, and fails exactly like a real call would.
|
|
22
|
+
|
|
23
|
+
Raises the canonical errors (AuthError for a rejected key, connection/server errors when the
|
|
24
|
+
provider cannot be reached). One attempt, no retries (ADR 0002).
|
|
25
|
+
"""
|
|
26
|
+
if cfg.api == "anthropic":
|
|
27
|
+
a_client = anthropic.AsyncAnthropic(
|
|
28
|
+
api_key=api_key,
|
|
29
|
+
base_url=cfg.base_url,
|
|
30
|
+
max_retries=0,
|
|
31
|
+
http_client=http_client,
|
|
32
|
+
)
|
|
33
|
+
with anthropic_brain.mapped_errors(cfg.model):
|
|
34
|
+
await a_client.models.list(limit=1)
|
|
35
|
+
return
|
|
36
|
+
o_client = openai.AsyncOpenAI(
|
|
37
|
+
api_key=api_key,
|
|
38
|
+
base_url=cfg.base_url,
|
|
39
|
+
max_retries=0,
|
|
40
|
+
http_client=http_client,
|
|
41
|
+
)
|
|
42
|
+
with openai_brain.mapped_errors(cfg.provider_name, cfg.model):
|
|
43
|
+
await o_client.models.list()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
TAVILY_USAGE = "https://api.tavily.com/usage"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
async def check_tavily_key(api_key: str, *, http_client: httpx2.AsyncClient | None = None) -> None:
|
|
50
|
+
"""Ask Tavily for the key's usage: read-only, costs no credits (docs.tavily.com, 2026-11-18).
|
|
51
|
+
|
|
52
|
+
Fails like a brain check would: AuthError for a rejected key, connection or server errors when
|
|
53
|
+
Tavily cannot be reached, so the gateway reports both the same way.
|
|
54
|
+
"""
|
|
55
|
+
ctx = {"provider": "tavily", "model": "-"}
|
|
56
|
+
headers = {"Authorization": f"Bearer {api_key}"}
|
|
57
|
+
try:
|
|
58
|
+
if http_client is None:
|
|
59
|
+
async with httpx2.AsyncClient(timeout=15) as http:
|
|
60
|
+
response = await http.get(TAVILY_USAGE, headers=headers)
|
|
61
|
+
else:
|
|
62
|
+
response = await http_client.get(TAVILY_USAGE, headers=headers)
|
|
63
|
+
except httpx2.TimeoutException as exc:
|
|
64
|
+
raise ProviderTimeoutError("Tavily did not answer in time", **ctx) from exc
|
|
65
|
+
except httpx2.HTTPError as exc:
|
|
66
|
+
raise ProviderConnectionError(
|
|
67
|
+
f"could not reach Tavily ({type(exc).__name__})", **ctx
|
|
68
|
+
) from exc
|
|
69
|
+
if response.status_code in (401, 403):
|
|
70
|
+
raise AuthError("Tavily rejected this key", **ctx)
|
|
71
|
+
if response.status_code == 429:
|
|
72
|
+
raise RateLimitError(
|
|
73
|
+
"Tavily is rate limiting key checks; try again in a few minutes", **ctx
|
|
74
|
+
)
|
|
75
|
+
if response.status_code != 200:
|
|
76
|
+
raise ProviderServerError(f"Tavily answered HTTP {response.status_code}", **ctx)
|