continuum-task-server-bundle 1.0.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.
Files changed (90) hide show
  1. continuum_task_server_bundle/__init__.py +1 -0
  2. continuum_task_server_bundle/daytona/__init__.py +4 -0
  3. continuum_task_server_bundle/daytona/common.py +534 -0
  4. continuum_task_server_bundle/daytona/create_sandbox.py +166 -0
  5. continuum_task_server_bundle/daytona/dispatch.py +125 -0
  6. continuum_task_server_bundle/daytona/execute_sandbox.py +243 -0
  7. continuum_task_server_bundle/daytona/filesystem.py +330 -0
  8. continuum_task_server_bundle/daytona/fs_edit.py +127 -0
  9. continuum_task_server_bundle/daytona/git_ops.py +585 -0
  10. continuum_task_server_bundle/daytona/github_app.py +207 -0
  11. continuum_task_server_bundle/daytona/manage_sandbox.py +104 -0
  12. continuum_task_server_bundle/daytona/plugin.py +18 -0
  13. continuum_task_server_bundle/daytona/s3_transfer.py +207 -0
  14. continuum_task_server_bundle/discord/__init__.py +4 -0
  15. continuum_task_server_bundle/discord/attachment_registry_db.py +127 -0
  16. continuum_task_server_bundle/discord/attachment_resolve.py +213 -0
  17. continuum_task_server_bundle/discord/await_cleanup.py +105 -0
  18. continuum_task_server_bundle/discord/discord_ready.py +39 -0
  19. continuum_task_server_bundle/discord/message_await_apply.py +143 -0
  20. continuum_task_server_bundle/discord/message_await_db.py +197 -0
  21. continuum_task_server_bundle/discord/message_await_inbound.py +54 -0
  22. continuum_task_server_bundle/discord/message_await_logic.py +133 -0
  23. continuum_task_server_bundle/discord/message_await_poller.py +122 -0
  24. continuum_task_server_bundle/discord/message_chunking.py +45 -0
  25. continuum_task_server_bundle/discord/methods.py +408 -0
  26. continuum_task_server_bundle/discord/plugin.py +105 -0
  27. continuum_task_server_bundle/discord/reaction_await_apply.py +238 -0
  28. continuum_task_server_bundle/discord/reaction_await_db.py +174 -0
  29. continuum_task_server_bundle/discord/reaction_await_inbound.py +47 -0
  30. continuum_task_server_bundle/discord/reaction_await_logic.py +118 -0
  31. continuum_task_server_bundle/discord/reaction_await_poller.py +131 -0
  32. continuum_task_server_bundle/discord/s3_attachment_config.py +25 -0
  33. continuum_task_server_bundle/discord/s3_message_attachments.py +139 -0
  34. continuum_task_server_bundle/discord/sql/001_message_awaits.sql +112 -0
  35. continuum_task_server_bundle/discord/sql/002_reaction_awaits.sql +61 -0
  36. continuum_task_server_bundle/github/__init__.py +4 -0
  37. continuum_task_server_bundle/github/awaits/__init__.py +1 -0
  38. continuum_task_server_bundle/github/awaits/apply.py +92 -0
  39. continuum_task_server_bundle/github/awaits/cleanup.py +94 -0
  40. continuum_task_server_bundle/github/awaits/db.py +220 -0
  41. continuum_task_server_bundle/github/awaits/evaluators.py +325 -0
  42. continuum_task_server_bundle/github/awaits/fetch.py +192 -0
  43. continuum_task_server_bundle/github/awaits/poller.py +82 -0
  44. continuum_task_server_bundle/github/awaits/register.py +37 -0
  45. continuum_task_server_bundle/github/ci_status.py +70 -0
  46. continuum_task_server_bundle/github/comment_normalize.py +76 -0
  47. continuum_task_server_bundle/github/errors.py +52 -0
  48. continuum_task_server_bundle/github/github_app.py +291 -0
  49. continuum_task_server_bundle/github/github_http.py +377 -0
  50. continuum_task_server_bundle/github/methods/__init__.py +90 -0
  51. continuum_task_server_bundle/github/methods/_common.py +183 -0
  52. continuum_task_server_bundle/github/methods/awaits.py +107 -0
  53. continuum_task_server_bundle/github/methods/ci.py +158 -0
  54. continuum_task_server_bundle/github/methods/comments.py +214 -0
  55. continuum_task_server_bundle/github/methods/credentials.py +59 -0
  56. continuum_task_server_bundle/github/methods/issues.py +131 -0
  57. continuum_task_server_bundle/github/methods/pulls.py +329 -0
  58. continuum_task_server_bundle/github/methods/repos.py +424 -0
  59. continuum_task_server_bundle/github/methods/search.py +109 -0
  60. continuum_task_server_bundle/github/plugin.py +91 -0
  61. continuum_task_server_bundle/github/sql/001_github_awaits.sql +65 -0
  62. continuum_task_server_bundle/github/webhook_server.py +126 -0
  63. continuum_task_server_bundle/jira/__init__.py +4 -0
  64. continuum_task_server_bundle/jira/await_poller.py +236 -0
  65. continuum_task_server_bundle/jira/await_store.py +271 -0
  66. continuum_task_server_bundle/jira/config.py +68 -0
  67. continuum_task_server_bundle/jira/jira_client.py +382 -0
  68. continuum_task_server_bundle/jira/methods.py +246 -0
  69. continuum_task_server_bundle/jira/plugin.py +86 -0
  70. continuum_task_server_bundle/jira/sql/001_jira_issue_comment_waits.sql +19 -0
  71. continuum_task_server_bundle/jira/webhook.py +70 -0
  72. continuum_task_server_bundle/openrouter/__init__.py +4 -0
  73. continuum_task_server_bundle/openrouter/chat_service.py +1037 -0
  74. continuum_task_server_bundle/openrouter/chat_store.py +849 -0
  75. continuum_task_server_bundle/openrouter/environment.py +29 -0
  76. continuum_task_server_bundle/openrouter/handler.py +59 -0
  77. continuum_task_server_bundle/openrouter/image_context.py +207 -0
  78. continuum_task_server_bundle/openrouter/openrouter_client.py +324 -0
  79. continuum_task_server_bundle/openrouter/plugin.py +37 -0
  80. continuum_task_server_bundle/openrouter/prompt_projection.py +417 -0
  81. continuum_task_server_bundle/openrouter/sql/chat.sql +50 -0
  82. continuum_task_server_bundle/openrouter/sql/migrate_prune_then_chunk_v1.sql +11 -0
  83. continuum_task_server_bundle/roblox/__init__.py +4 -0
  84. continuum_task_server_bundle/roblox/open_cloud.py +335 -0
  85. continuum_task_server_bundle/roblox/plugin.py +30 -0
  86. continuum_task_server_bundle/roblox/storage_s3.py +55 -0
  87. continuum_task_server_bundle-1.0.0.dist-info/METADATA +109 -0
  88. continuum_task_server_bundle-1.0.0.dist-info/RECORD +90 -0
  89. continuum_task_server_bundle-1.0.0.dist-info/WHEEL +5 -0
  90. continuum_task_server_bundle-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,291 @@
1
+ """GitHub App authentication.
2
+
3
+ Signs an app JWT, resolves an installation per repository owner, and caches
4
+ installation tokens per installation and per downscope. Tokens are refreshed
5
+ five minutes before they expire. A 401 invalidates the cached token so the
6
+ next call mints a new one.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import threading
13
+ import time
14
+ from datetime import datetime, timedelta, timezone
15
+ from os import getenv
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import jwt
20
+
21
+ from continuum_task_server_bundle.github.errors import GitHubRequestError, GitHubUnauthorized
22
+ from continuum_task_server_bundle.github.github_http import GitHubHttp, GitHubResponse
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ _TOKEN_SKEW = timedelta(minutes=5)
27
+ _JWT_LIFETIME = 9 * 60
28
+ _INSTALL_TTL_SECONDS = 3600
29
+
30
+
31
+ def _utcnow() -> datetime:
32
+ return datetime.now(timezone.utc)
33
+
34
+
35
+ def load_private_key() -> str:
36
+ path = getenv("GITHUB_APP_PRIVATE_KEY_PATH")
37
+ if path:
38
+ return Path(path).read_text()
39
+ raw = getenv("GITHUB_APP_PRIVATE_KEY")
40
+ if not raw:
41
+ raise RuntimeError("Set GITHUB_APP_PRIVATE_KEY or GITHUB_APP_PRIVATE_KEY_PATH")
42
+ text = raw.replace("\\n", "\n").strip()
43
+ if not text.startswith("-----"):
44
+ candidate = Path(text)
45
+ if candidate.is_file():
46
+ return candidate.read_text()
47
+ return text
48
+
49
+
50
+ def _parse_expiry(value: str) -> datetime:
51
+ text = value.replace("Z", "+00:00")
52
+ parsed = datetime.fromisoformat(text)
53
+ if parsed.tzinfo is None:
54
+ parsed = parsed.replace(tzinfo=timezone.utc)
55
+ return parsed.astimezone(timezone.utc)
56
+
57
+
58
+ def _token_cache_key(
59
+ installation_id: int,
60
+ repositories: list[str] | None,
61
+ permissions: dict[str, str] | None,
62
+ ) -> tuple:
63
+ repos = tuple(sorted(repositories or []))
64
+ perms = tuple(sorted((permissions or {}).items()))
65
+ return (installation_id, repos, perms)
66
+
67
+
68
+ class GitHubApp:
69
+ def __init__(
70
+ self,
71
+ http: GitHubHttp,
72
+ *,
73
+ app_id: str | None = None,
74
+ private_key: str | None = None,
75
+ ):
76
+ self.http = http
77
+ self.app_id = app_id or getenv("GITHUB_APP_ID") or ""
78
+ self._private_key = private_key if private_key is not None else None
79
+ self._lock = threading.Lock()
80
+ self._jwt: tuple[str, float] | None = None
81
+ self._slug: str | None = None
82
+ # owner login (lower) -> (installation id, monotonic expiry)
83
+ self._owner_installations: dict[str, tuple[int, float]] = {}
84
+ # "owner/repo" (lower) -> installation id, same clock as above
85
+ self._repo_installations: dict[str, tuple[int, float]] = {}
86
+ self._tokens: dict[tuple, tuple[str, datetime]] = {}
87
+
88
+ def app_jwt(self) -> str:
89
+ now = time.time()
90
+ with self._lock:
91
+ cached = self._jwt
92
+ if cached is not None and cached[1] - now > 60:
93
+ return cached[0]
94
+ if not self.app_id:
95
+ raise RuntimeError("GITHUB_APP_ID is not set")
96
+ key = self._private_key if self._private_key is not None else load_private_key()
97
+ payload = {"iat": int(now) - 60, "exp": int(now) + _JWT_LIFETIME, "iss": str(self.app_id)}
98
+ token = jwt.encode(payload, key, algorithm="RS256")
99
+ if isinstance(token, bytes):
100
+ token = token.decode()
101
+ with self._lock:
102
+ self._jwt = (token, now + _JWT_LIFETIME)
103
+ return token
104
+
105
+ def slug(self) -> str:
106
+ with self._lock:
107
+ if self._slug:
108
+ return self._slug
109
+ data = self.http.rest("GET", "/app", token=self.app_jwt()).data or {}
110
+ slug = str(data.get("slug") or "")
111
+ if not slug:
112
+ raise RuntimeError("GitHub /app response did not include slug")
113
+ with self._lock:
114
+ self._slug = slug
115
+ return slug
116
+
117
+ def installation_id_for_repo(self, owner: str, repo: str) -> int:
118
+ full = f"{owner}/{repo}".lower()
119
+ cached = self._cached_installation(self._repo_installations, full)
120
+ if cached is not None:
121
+ return cached
122
+ response = self.http.rest(
123
+ "GET",
124
+ f"/repos/{owner}/{repo}/installation",
125
+ token=self.app_jwt(),
126
+ )
127
+ return self._remember_installation(response.data or {}, repo_key=full)
128
+
129
+ def installation_id_for_owner(self, owner: str) -> int:
130
+ key = owner.lower()
131
+ cached = self._cached_installation(self._owner_installations, key)
132
+ if cached is not None:
133
+ return cached
134
+ token = self.app_jwt()
135
+ try:
136
+ response = self.http.rest("GET", f"/orgs/{owner}/installation", token=token)
137
+ except GitHubRequestError as exc:
138
+ if exc.status != 404:
139
+ raise
140
+ response = self.http.rest("GET", f"/users/{owner}/installation", token=token)
141
+ return self._remember_installation(response.data or {}, owner_key=key)
142
+
143
+ def installation_token(
144
+ self,
145
+ installation_id: int,
146
+ *,
147
+ repositories: list[str] | None = None,
148
+ permissions: dict[str, str] | None = None,
149
+ force: bool = False,
150
+ ) -> tuple[str, datetime]:
151
+ """Return ``(token, expires_at)``.
152
+
153
+ ``repositories`` is a list of repo names (not ``owner/name``) used to
154
+ downscope the token. ``permissions`` maps a permission name to
155
+ ``read`` / ``write`` / ``admin``.
156
+ """
157
+ key = _token_cache_key(installation_id, repositories, permissions)
158
+ if not force:
159
+ with self._lock:
160
+ hit = self._tokens.get(key)
161
+ if hit is not None and hit[1] - _utcnow() > _TOKEN_SKEW:
162
+ return hit
163
+
164
+ body: dict[str, Any] = {}
165
+ if repositories:
166
+ body["repositories"] = list(repositories)
167
+ if permissions:
168
+ body["permissions"] = dict(permissions)
169
+ response = self.http.rest(
170
+ "POST",
171
+ f"/app/installations/{installation_id}/access_tokens",
172
+ token=self.app_jwt(),
173
+ json_body=body or None,
174
+ )
175
+ data = response.data or {}
176
+ token = data.get("token")
177
+ expires_raw = data.get("expires_at")
178
+ if not token or not expires_raw:
179
+ raise RuntimeError("GitHub installation token response was missing token or expires_at")
180
+ expires_at = _parse_expiry(str(expires_raw))
181
+ with self._lock:
182
+ self._tokens[key] = (str(token), expires_at)
183
+ return str(token), expires_at
184
+
185
+ def invalidate_installation_tokens(self, installation_id: int) -> None:
186
+ with self._lock:
187
+ for key in list(self._tokens):
188
+ if key[0] == installation_id:
189
+ del self._tokens[key]
190
+
191
+ def token_for_repo(self, owner: str, repo: str, *, force: bool = False) -> str:
192
+ installation_id = self.installation_id_for_repo(owner, repo)
193
+ token, _expires = self.installation_token(installation_id, force=force)
194
+ return token
195
+
196
+ def token_for_owner(self, owner: str, *, force: bool = False) -> str:
197
+ installation_id = self.installation_id_for_owner(owner)
198
+ token, _expires = self.installation_token(installation_id, force=force)
199
+ return token
200
+
201
+ def rest(
202
+ self,
203
+ method: str,
204
+ path: str,
205
+ *,
206
+ repo: str | None = None,
207
+ owner: str | None = None,
208
+ **kwargs: Any,
209
+ ) -> GitHubResponse:
210
+ """REST call authenticated as the installation for ``repo`` or ``owner``.
211
+
212
+ On 401 the cached token for that installation is dropped and the call
213
+ is retried once.
214
+ """
215
+ token, installation_id = self._token_and_installation(repo=repo, owner=owner, force=False)
216
+ try:
217
+ return self.http.rest(method, path, token=token, **kwargs)
218
+ except GitHubUnauthorized:
219
+ logger.info("GitHub 401 for installation %s; refreshing token", installation_id)
220
+ if installation_id is not None:
221
+ self.invalidate_installation_tokens(installation_id)
222
+ token, _installation_id = self._token_and_installation(repo=repo, owner=owner, force=True)
223
+ return self.http.rest(method, path, token=token, **kwargs)
224
+
225
+ def graphql(
226
+ self,
227
+ query: str,
228
+ variables: dict[str, Any] | None,
229
+ *,
230
+ repo: str | None = None,
231
+ owner: str | None = None,
232
+ ) -> dict[str, Any]:
233
+ token, installation_id = self._token_and_installation(repo=repo, owner=owner, force=False)
234
+ try:
235
+ return self.http.graphql(query, variables, token=token)
236
+ except GitHubUnauthorized:
237
+ if installation_id is not None:
238
+ self.invalidate_installation_tokens(installation_id)
239
+ token, _installation_id = self._token_and_installation(repo=repo, owner=owner, force=True)
240
+ return self.http.graphql(query, variables, token=token)
241
+
242
+ def _token_and_installation(
243
+ self,
244
+ *,
245
+ repo: str | None,
246
+ owner: str | None,
247
+ force: bool,
248
+ ) -> tuple[str, int | None]:
249
+ if repo:
250
+ repo_owner, repo_name = repo.split("/", 1)
251
+ installation_id = self.installation_id_for_repo(repo_owner, repo_name)
252
+ token, _expires = self.installation_token(installation_id, force=force)
253
+ return token, installation_id
254
+ if owner:
255
+ installation_id = self.installation_id_for_owner(owner)
256
+ token, _expires = self.installation_token(installation_id, force=force)
257
+ return token, installation_id
258
+ raise RuntimeError("repo or owner is required to choose a GitHub installation")
259
+
260
+ def _cached_installation(self, cache: dict[str, tuple[int, float]], key: str) -> int | None:
261
+ with self._lock:
262
+ hit = cache.get(key)
263
+ if hit is None:
264
+ return None
265
+ installation_id, expires = hit
266
+ if expires <= time.monotonic():
267
+ return None
268
+ return installation_id
269
+
270
+ def _remember_installation(
271
+ self,
272
+ data: dict[str, Any],
273
+ *,
274
+ repo_key: str | None = None,
275
+ owner_key: str | None = None,
276
+ ) -> int:
277
+ installation_id = data.get("id")
278
+ if installation_id is None:
279
+ raise RuntimeError("GitHub installation response was missing id")
280
+ installation_id = int(installation_id)
281
+ account = data.get("account") or {}
282
+ login = str(account.get("login") or "").lower()
283
+ deadline = time.monotonic() + _INSTALL_TTL_SECONDS
284
+ with self._lock:
285
+ if login:
286
+ self._owner_installations[login] = (installation_id, deadline)
287
+ if owner_key:
288
+ self._owner_installations[owner_key] = (installation_id, deadline)
289
+ if repo_key:
290
+ self._repo_installations[repo_key] = (installation_id, deadline)
291
+ return installation_id
@@ -0,0 +1,377 @@
1
+ """Thin GitHub REST and GraphQL client.
2
+
3
+ Expected 4xx responses (400, 403 that is not a rate limit, 404, 409, 422, and
4
+ other non-rate-limit 4xx) raise ``GitHubRequestError``. 401 raises
5
+ ``GitHubUnauthorized``. 429, secondary rate limits, 5xx, and transport errors
6
+ are retried, then raised as ``GitHubRetryableError``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import logging
13
+ import time
14
+ from dataclasses import dataclass, field
15
+ from os import getenv
16
+ from typing import Any
17
+ import httpx
18
+
19
+ from continuum_task_server_bundle.github.errors import GitHubRequestError, GitHubRetryableError, GitHubUnauthorized
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ _API_VERSION = "2022-11-28"
24
+ _USER_AGENT = "continuum-github-task-server"
25
+ _MAX_RATE_LIMIT_SLEEP = 60.0
26
+ _RETRY_BACKOFF = (1.0, 2.0, 4.0)
27
+
28
+ # 4xx that workflows should observe as success:false rather than a retry.
29
+ _CLIENT_STATUSES = {400, 403, 404, 409, 422}
30
+
31
+
32
+ @dataclass
33
+ class GitHubResponse:
34
+ status: int
35
+ data: Any
36
+ etag: str | None = None
37
+ not_modified: bool = False
38
+ next_url: str | None = None
39
+ incomplete: bool = False
40
+ headers: dict[str, str] = field(default_factory=dict)
41
+
42
+
43
+ def graphql_url(api_url: str) -> str:
44
+ """REST base to GraphQL URL, including GitHub Enterprise ``/api/v3``."""
45
+ base = api_url.rstrip("/")
46
+ if base.endswith("/api/v3"):
47
+ return base[: -len("/api/v3")] + "/api/graphql"
48
+ return base + "/graphql"
49
+
50
+
51
+ def github_error_message(body: Any) -> str:
52
+ if isinstance(body, dict):
53
+ message = str(body.get("message") or "").strip()
54
+ errors = body.get("errors")
55
+ if errors:
56
+ extra = errors if isinstance(errors, str) else json.dumps(errors, default=str)
57
+ return f"{message}: {extra}" if message else str(extra)
58
+ return message or json.dumps(body, default=str)[:500]
59
+ if body is None:
60
+ return ""
61
+ return str(body)[:500]
62
+
63
+
64
+ def _parse_next_link(link_header: str | None) -> str | None:
65
+ if not link_header:
66
+ return None
67
+ for part in link_header.split(","):
68
+ pieces = [p.strip() for p in part.split(";")]
69
+ if len(pieces) < 2:
70
+ continue
71
+ url = pieces[0]
72
+ if url.startswith("<") and url.endswith(">"):
73
+ url = url[1:-1]
74
+ rels = " ".join(pieces[1:])
75
+ if 'rel="next"' in rels or "rel=next" in rels:
76
+ return url
77
+ return None
78
+
79
+
80
+ def _is_secondary_rate_limit(response: httpx.Response) -> bool:
81
+ if response.status_code not in (403, 429):
82
+ return False
83
+ if response.status_code == 429:
84
+ return True
85
+ remaining = response.headers.get("x-ratelimit-remaining")
86
+ if remaining == "0":
87
+ return True
88
+ text = ""
89
+ try:
90
+ text = response.text.lower()
91
+ except Exception:
92
+ return False
93
+ return "secondary rate limit" in text or "rate limit" in text or "abuse detection" in text
94
+
95
+
96
+ def _retry_delay(response: httpx.Response) -> float | None:
97
+ if not _is_secondary_rate_limit(response):
98
+ return None
99
+ retry_after = response.headers.get("retry-after")
100
+ if retry_after:
101
+ try:
102
+ return max(0.0, float(retry_after))
103
+ except ValueError:
104
+ return 1.0
105
+ reset = response.headers.get("x-ratelimit-reset")
106
+ if reset:
107
+ try:
108
+ return max(0.0, float(reset) - time.time()) + 0.5
109
+ except ValueError:
110
+ return 1.0
111
+ return 5.0
112
+
113
+
114
+ class GitHubHttp:
115
+ def __init__(self, api_url: str | None = None, *, client: httpx.Client | None = None):
116
+ self.api_url = (api_url or getenv("GITHUB_API_URL") or "https://api.github.com").rstrip("/")
117
+ self._owns_client = client is None
118
+ self._client = client or httpx.Client(timeout=httpx.Timeout(60.0, connect=10.0), follow_redirects=True)
119
+
120
+ def close(self) -> None:
121
+ if self._owns_client:
122
+ self._client.close()
123
+
124
+ def rest(
125
+ self,
126
+ method: str,
127
+ path: str,
128
+ *,
129
+ token: str,
130
+ json_body: Any = None,
131
+ params: dict[str, Any] | None = None,
132
+ etag: str | None = None,
133
+ accept: str = "application/vnd.github+json",
134
+ paginate: bool = False,
135
+ list_key: str | None = None,
136
+ max_pages: int = 10,
137
+ ) -> GitHubResponse:
138
+ first = self._request(
139
+ method,
140
+ path,
141
+ token=token,
142
+ json_body=json_body,
143
+ params=params,
144
+ etag=etag,
145
+ accept=accept,
146
+ )
147
+ if not paginate or first.not_modified:
148
+ return first
149
+
150
+ items = _extract_list(first.data, list_key)
151
+ pages = 1
152
+ next_url = first.next_url
153
+ while next_url and pages < max_pages:
154
+ nxt = self._request("GET", next_url, token=token, accept=accept)
155
+ items.extend(_extract_list(nxt.data, list_key))
156
+ next_url = nxt.next_url
157
+ pages += 1
158
+ return GitHubResponse(
159
+ status=first.status,
160
+ data=items,
161
+ etag=first.etag,
162
+ not_modified=False,
163
+ next_url=next_url,
164
+ incomplete=next_url is not None,
165
+ headers=first.headers,
166
+ )
167
+
168
+ def graphql(self, query: str, variables: dict[str, Any] | None, *, token: str) -> dict[str, Any]:
169
+ response = self._request(
170
+ "POST",
171
+ graphql_url(self.api_url),
172
+ token=token,
173
+ json_body={"query": query, "variables": variables or {}},
174
+ accept="application/json",
175
+ )
176
+ body = response.data if isinstance(response.data, dict) else {}
177
+ errors = body.get("errors")
178
+ if errors:
179
+ message = "; ".join(str(item.get("message") or item) for item in errors)
180
+ raise GitHubRequestError(422, message, message)
181
+ data = body.get("data")
182
+ return data if isinstance(data, dict) else {}
183
+
184
+ def read_tail(
185
+ self,
186
+ path: str,
187
+ *,
188
+ token: str,
189
+ max_bytes: int,
190
+ max_download: int = 8_000_000,
191
+ accept: str = "application/vnd.github+json",
192
+ ) -> tuple[str, bool]:
193
+ """Follow redirects and keep the last ``max_bytes`` of the body.
194
+
195
+ Stops early once ``max_download`` bytes have been read. Returns
196
+ ``(text, truncated)``.
197
+ """
198
+ url = self._url(path)
199
+ headers = self._headers(token=token, accept=accept, etag=None)
200
+ buf = bytearray()
201
+ downloaded = 0
202
+ truncated = False
203
+ try:
204
+ with self._client.stream("GET", url, headers=headers) as response:
205
+ if response.status_code == 401:
206
+ raise GitHubUnauthorized(github_error_message(_safe_error_body(response)) or "unauthorized")
207
+ if response.status_code >= 500:
208
+ raise GitHubRetryableError(
209
+ f"GitHub {response.status_code}: {github_error_message(_safe_error_body(response))}"
210
+ )
211
+ if response.status_code >= 400:
212
+ message = github_error_message(_safe_error_body(response)) or f"GitHub HTTP {response.status_code}"
213
+ raise GitHubRequestError(response.status_code, message, message)
214
+ for chunk in response.iter_bytes():
215
+ if not chunk:
216
+ continue
217
+ downloaded += len(chunk)
218
+ buf.extend(chunk)
219
+ if len(buf) > max_bytes:
220
+ del buf[:-max_bytes]
221
+ if downloaded > max_download:
222
+ truncated = True
223
+ break
224
+ except (GitHubRequestError, GitHubRetryableError):
225
+ raise
226
+ except httpx.HTTPError as exc:
227
+ raise GitHubRetryableError(str(exc)) from exc
228
+ if downloaded > max_bytes:
229
+ truncated = True
230
+ return buf.decode("utf-8", errors="replace"), truncated
231
+
232
+ def _request(
233
+ self,
234
+ method: str,
235
+ path: str,
236
+ *,
237
+ token: str,
238
+ json_body: Any = None,
239
+ params: dict[str, Any] | None = None,
240
+ etag: str | None = None,
241
+ accept: str,
242
+ ) -> GitHubResponse:
243
+ url = self._url(path)
244
+ attempt = 0
245
+ while True:
246
+ headers = self._headers(token=token, accept=accept, etag=etag)
247
+ try:
248
+ response = self._client.request(
249
+ method,
250
+ url,
251
+ headers=headers,
252
+ params=_drop_none(params),
253
+ json=json_body,
254
+ )
255
+ except httpx.HTTPError as exc:
256
+ if attempt >= len(_RETRY_BACKOFF):
257
+ raise GitHubRetryableError(str(exc)) from exc
258
+ delay = _RETRY_BACKOFF[attempt]
259
+ attempt += 1
260
+ logger.warning("GitHub transport error (%s); retrying in %.1fs", exc, delay)
261
+ time.sleep(delay)
262
+ continue
263
+
264
+ if response.status_code == 304:
265
+ return GitHubResponse(
266
+ status=304,
267
+ data=None,
268
+ etag=response.headers.get("etag") or etag,
269
+ not_modified=True,
270
+ headers=_header_map(response),
271
+ )
272
+
273
+ delay = _retry_delay(response)
274
+ if delay is not None:
275
+ if delay > _MAX_RATE_LIMIT_SLEEP or attempt >= len(_RETRY_BACKOFF):
276
+ raise GitHubRetryableError(
277
+ f"GitHub rate limit (retry after {delay:.0f}s): {github_error_message(_json_or_text(response))}"
278
+ )
279
+ logger.info("GitHub rate limit; sleeping %.1fs", delay)
280
+ time.sleep(delay)
281
+ attempt += 1
282
+ continue
283
+
284
+ if response.status_code >= 500:
285
+ if attempt >= len(_RETRY_BACKOFF):
286
+ message = github_error_message(_json_or_text(response)) or f"GitHub HTTP {response.status_code}"
287
+ raise GitHubRetryableError(f"GitHub {response.status_code}: {message}")
288
+ delay = _RETRY_BACKOFF[attempt]
289
+ attempt += 1
290
+ logger.warning("GitHub %s; retrying in %.1fs", response.status_code, delay)
291
+ time.sleep(delay)
292
+ continue
293
+
294
+ body = _json_or_text(response)
295
+ if response.status_code == 401:
296
+ raise GitHubUnauthorized(github_error_message(body) or "unauthorized")
297
+
298
+ if response.status_code >= 400:
299
+ message = github_error_message(body) or f"GitHub HTTP {response.status_code}"
300
+ if response.status_code in _CLIENT_STATUSES or 400 <= response.status_code < 500:
301
+ raise GitHubRequestError(response.status_code, message, message)
302
+ raise GitHubRetryableError(message)
303
+
304
+ return GitHubResponse(
305
+ status=response.status_code,
306
+ data=body,
307
+ etag=response.headers.get("etag"),
308
+ not_modified=False,
309
+ next_url=_parse_next_link(response.headers.get("link")),
310
+ headers=_header_map(response),
311
+ )
312
+
313
+ def _url(self, path: str) -> str:
314
+ if path.startswith("https://") or path.startswith("http://"):
315
+ return path
316
+ if not path.startswith("/"):
317
+ path = "/" + path
318
+ return self.api_url + path
319
+
320
+ @staticmethod
321
+ def _headers(*, token: str, accept: str, etag: str | None) -> dict[str, str]:
322
+ headers = {
323
+ "Accept": accept,
324
+ "Authorization": f"Bearer {token}",
325
+ "User-Agent": _USER_AGENT,
326
+ "X-GitHub-Api-Version": _API_VERSION,
327
+ }
328
+ if etag:
329
+ headers["If-None-Match"] = etag
330
+ return headers
331
+
332
+
333
+ def _extract_list(data: Any, list_key: str | None) -> list:
334
+ if list_key:
335
+ if isinstance(data, dict):
336
+ value = data.get(list_key) or []
337
+ return list(value) if isinstance(value, list) else []
338
+ return []
339
+ if isinstance(data, list):
340
+ return list(data)
341
+ return []
342
+
343
+
344
+ def _drop_none(params: dict[str, Any] | None) -> dict[str, Any] | None:
345
+ if not params:
346
+ return None
347
+ return {key: value for key, value in params.items() if value is not None}
348
+
349
+
350
+ def _json_or_text(response: httpx.Response) -> Any:
351
+ if not response.content:
352
+ return None
353
+ content_type = response.headers.get("content-type", "")
354
+ if "json" in content_type:
355
+ try:
356
+ return response.json()
357
+ except json.JSONDecodeError:
358
+ return response.text
359
+ text = response.text
360
+ stripped = text.lstrip()
361
+ if stripped.startswith("{") or stripped.startswith("["):
362
+ try:
363
+ return json.loads(text)
364
+ except json.JSONDecodeError:
365
+ return text
366
+ return text
367
+
368
+
369
+ def _safe_error_body(response: httpx.Response) -> Any:
370
+ try:
371
+ return _json_or_text(response)
372
+ except httpx.HTTPError:
373
+ return None
374
+
375
+
376
+ def _header_map(response: httpx.Response) -> dict[str, str]:
377
+ return {key.lower(): value for key, value in response.headers.items()}