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,424 @@
1
+ """Repository, branch, fork, and file methods."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import re
7
+ from typing import Any
8
+
9
+ from continuum_task_server_bundle.github.awaits.register import register_await
10
+ from continuum_task_server_bundle.github.errors import GitHubRequestError, InputError
11
+ from continuum_task_server_bundle.github.methods._common import (
12
+ Call,
13
+ as_bool,
14
+ opt_float,
15
+ opt_int,
16
+ path_segment,
17
+ repo_full_name,
18
+ require_repo,
19
+ require_str,
20
+ trim_repo,
21
+ )
22
+
23
+ _SHA = re.compile(r"^[0-9a-fA-F]{40}$")
24
+ _MAX_FILE_CHARS = 1_000_000
25
+
26
+
27
+ def get_repo(call: Call) -> dict[str, Any]:
28
+ owner, name = require_repo(call.data)
29
+ repo = f"{owner}/{name}"
30
+ body = call.app.rest("GET", f"/repos/{owner}/{name}", repo=repo).data or {}
31
+ return {"success": True, "repo": trim_repo(body)}
32
+
33
+
34
+ def list_branches(call: Call) -> dict[str, Any]:
35
+ owner, name = require_repo(call.data)
36
+ repo = f"{owner}/{name}"
37
+ limit = min(2000, max(1, opt_int(call.data, "limit", "per_page", default=100)))
38
+ max_pages = max(1, (limit + 99) // 100)
39
+ branches = call.app.rest(
40
+ "GET",
41
+ f"/repos/{owner}/{name}/branches",
42
+ repo=repo,
43
+ params={"per_page": min(100, limit)},
44
+ paginate=True,
45
+ max_pages=max_pages,
46
+ ).data or []
47
+ trimmed = [
48
+ {"name": branch.get("name"), "sha": (branch.get("commit") or {}).get("sha"), "protected": branch.get("protected")}
49
+ for branch in branches[:limit]
50
+ ]
51
+ return {"success": True, "branches": trimmed}
52
+
53
+
54
+ def get_branch(call: Call) -> dict[str, Any]:
55
+ owner, name = require_repo(call.data)
56
+ branch = require_str(call.data, "branch")
57
+ repo = f"{owner}/{name}"
58
+ body = call.app.rest(
59
+ "GET",
60
+ f"/repos/{owner}/{name}/branches/{path_segment(branch)}",
61
+ repo=repo,
62
+ ).data or {}
63
+ commit = body.get("commit") or {}
64
+ return {
65
+ "success": True,
66
+ "name": body.get("name"),
67
+ "sha": commit.get("sha"),
68
+ "protected": body.get("protected"),
69
+ }
70
+
71
+
72
+ def list_commits(call: Call) -> dict[str, Any]:
73
+ owner, name = require_repo(call.data)
74
+ repo = f"{owner}/{name}"
75
+ per_page = min(100, max(1, opt_int(call.data, "per_page", "limit", default=30)))
76
+ commits = call.app.rest(
77
+ "GET",
78
+ f"/repos/{owner}/{name}/commits",
79
+ repo=repo,
80
+ params={
81
+ "sha": call.data.get("sha") or call.data.get("ref") or call.data.get("branch"),
82
+ "path": call.data.get("path"),
83
+ "per_page": per_page,
84
+ },
85
+ ).data or []
86
+ if isinstance(commits, dict):
87
+ commits = []
88
+ return {"success": True, "commits": [_trim_commit(commit) for commit in commits]}
89
+
90
+
91
+ def compare(call: Call) -> dict[str, Any]:
92
+ owner, name = require_repo(call.data)
93
+ base = require_str(call.data, "base")
94
+ head = require_str(call.data, "head")
95
+ repo = f"{owner}/{name}"
96
+ spec = f"{path_segment(base)}...{path_segment(head)}"
97
+ body = call.app.rest("GET", f"/repos/{owner}/{name}/compare/{spec}", repo=repo).data or {}
98
+ files = []
99
+ for item in (body.get("files") or [])[:100]:
100
+ files.append(
101
+ {
102
+ "filename": item.get("filename"),
103
+ "status": item.get("status"),
104
+ "additions": item.get("additions"),
105
+ "deletions": item.get("deletions"),
106
+ "changes": item.get("changes"),
107
+ }
108
+ )
109
+ commits = [_trim_commit(commit) for commit in (body.get("commits") or [])[:50]]
110
+ return {
111
+ "success": True,
112
+ "status": body.get("status"),
113
+ "ahead_by": body.get("ahead_by"),
114
+ "behind_by": body.get("behind_by"),
115
+ "total_commits": body.get("total_commits"),
116
+ "files": files,
117
+ "commits": commits,
118
+ "html_url": body.get("permalink_url") or body.get("html_url"),
119
+ }
120
+
121
+
122
+ def get_file(call: Call) -> dict[str, Any]:
123
+ owner, name = require_repo(call.data)
124
+ path = require_str(call.data, "path").lstrip("/")
125
+ repo = f"{owner}/{name}"
126
+ body = call.app.rest(
127
+ "GET",
128
+ f"/repos/{owner}/{name}/contents/{path_segment(path)}",
129
+ repo=repo,
130
+ params={"ref": call.data.get("ref") or call.data.get("branch")},
131
+ ).data
132
+ if isinstance(body, list):
133
+ entries = [
134
+ {
135
+ "type": entry.get("type"),
136
+ "name": entry.get("name"),
137
+ "path": entry.get("path"),
138
+ "sha": entry.get("sha"),
139
+ "size": entry.get("size"),
140
+ "html_url": entry.get("html_url"),
141
+ }
142
+ for entry in body
143
+ ]
144
+ return {"success": True, "type": "dir", "path": path, "entries": entries}
145
+ body = body or {}
146
+ content = None
147
+ truncated = False
148
+ if body.get("encoding") == "base64" and body.get("content"):
149
+ raw = base64.b64decode(body["content"])
150
+ if len(raw) > _MAX_FILE_CHARS:
151
+ truncated = True
152
+ else:
153
+ content = raw.decode("utf-8", errors="replace")
154
+ return {
155
+ "success": True,
156
+ "type": body.get("type"),
157
+ "path": body.get("path"),
158
+ "sha": body.get("sha"),
159
+ "size": body.get("size"),
160
+ "encoding": body.get("encoding"),
161
+ "html_url": body.get("html_url"),
162
+ "content": content,
163
+ "truncated": truncated,
164
+ }
165
+
166
+
167
+ def create_branch(call: Call) -> dict[str, Any]:
168
+ owner, name = require_repo(call.data)
169
+ branch = require_str(call.data, "branch")
170
+ source = call.data.get("from") or call.data.get("sha") or call.data.get("ref")
171
+ if not isinstance(source, str) or not source.strip():
172
+ raise InputError("from (ref or sha) is required")
173
+ repo = f"{owner}/{name}"
174
+ sha = _resolve_sha(call, owner, name, source.strip())
175
+ ref = f"refs/heads/{branch}"
176
+ try:
177
+ call.app.rest(
178
+ "POST",
179
+ f"/repos/{owner}/{name}/git/refs",
180
+ repo=repo,
181
+ json_body={"ref": ref, "sha": sha},
182
+ )
183
+ return {"success": True, "ref": branch, "sha": sha, "existing": False}
184
+ except GitHubRequestError as exc:
185
+ if exc.status != 422:
186
+ raise
187
+ existing = call.app.rest(
188
+ "GET",
189
+ f"/repos/{owner}/{name}/git/ref/heads/{path_segment(branch)}",
190
+ repo=repo,
191
+ ).data or {}
192
+ existing_sha = (existing.get("object") or {}).get("sha")
193
+ if existing_sha == sha:
194
+ return {"success": True, "ref": branch, "sha": sha, "existing": True}
195
+ raise GitHubRequestError(
196
+ 409,
197
+ f"branch {branch} already exists at {existing_sha}",
198
+ exc.github_message,
199
+ ) from exc
200
+
201
+
202
+ def delete_branch(call: Call) -> dict[str, Any]:
203
+ owner, name = require_repo(call.data)
204
+ branch = require_str(call.data, "branch")
205
+ repo = f"{owner}/{name}"
206
+ repo_body = call.app.rest("GET", f"/repos/{owner}/{name}", repo=repo).data or {}
207
+ default_branch = repo_body.get("default_branch")
208
+ if branch == default_branch:
209
+ raise InputError(f"refusing to delete the default branch {branch!r}")
210
+ branch_body = call.app.rest(
211
+ "GET",
212
+ f"/repos/{owner}/{name}/branches/{path_segment(branch)}",
213
+ repo=repo,
214
+ ).data or {}
215
+ if branch_body.get("protected"):
216
+ raise InputError(f"refusing to delete protected branch {branch!r}")
217
+ call.app.rest(
218
+ "DELETE",
219
+ f"/repos/{owner}/{name}/git/refs/heads/{path_segment(branch)}",
220
+ repo=repo,
221
+ )
222
+ return {"success": True, "ref": branch}
223
+
224
+
225
+ def put_file(call: Call) -> dict[str, Any]:
226
+ owner, name = require_repo(call.data)
227
+ path = require_str(call.data, "path").lstrip("/")
228
+ message = require_str(call.data, "message")
229
+ repo = f"{owner}/{name}"
230
+ branch = call.data.get("branch")
231
+ if "content_base64" in call.data and call.data.get("content_base64") is not None:
232
+ encoded = str(call.data["content_base64"])
233
+ elif "content" in call.data and call.data.get("content") is not None:
234
+ encoded = base64.b64encode(str(call.data["content"]).encode()).decode()
235
+ else:
236
+ raise InputError("content or content_base64 is required")
237
+
238
+ sha = call.data.get("sha")
239
+ if not sha:
240
+ try:
241
+ current = call.app.rest(
242
+ "GET",
243
+ f"/repos/{owner}/{name}/contents/{path_segment(path)}",
244
+ repo=repo,
245
+ params={"ref": branch},
246
+ ).data
247
+ if isinstance(current, dict):
248
+ sha = current.get("sha")
249
+ except GitHubRequestError as exc:
250
+ if exc.status != 404:
251
+ raise
252
+ sha = None
253
+
254
+ body: dict[str, Any] = {"message": message, "content": encoded}
255
+ if branch:
256
+ body["branch"] = branch
257
+ if sha:
258
+ body["sha"] = sha
259
+ result = call.app.rest(
260
+ "PUT",
261
+ f"/repos/{owner}/{name}/contents/{path_segment(path)}",
262
+ repo=repo,
263
+ json_body=body,
264
+ ).data or {}
265
+ content = result.get("content") or {}
266
+ commit = result.get("commit") or {}
267
+ return {
268
+ "success": True,
269
+ "path": content.get("path") or path,
270
+ "sha": content.get("sha"),
271
+ "commit_sha": commit.get("sha"),
272
+ "html_url": content.get("html_url"),
273
+ "branch": branch,
274
+ }
275
+
276
+
277
+ def fork_repo(call: Call) -> dict[str, Any] | None:
278
+ owner, name = require_repo(call.data)
279
+ repo = f"{owner}/{name}"
280
+ body: dict[str, Any] = {}
281
+ if call.data.get("organization"):
282
+ body["organization"] = call.data["organization"]
283
+ if call.data.get("name"):
284
+ body["name"] = call.data["name"]
285
+ if call.data.get("default_branch_only") is not None:
286
+ body["default_branch_only"] = as_bool(call.data.get("default_branch_only"))
287
+ created = call.app.rest("POST", f"/repos/{owner}/{name}/forks", repo=repo, json_body=body or None).data or {}
288
+ trimmed = trim_repo(created)
289
+ if not as_bool(call.data.get("wait_until_ready")):
290
+ return {"success": True, "repo": trimmed}
291
+ _register_repo_ready(call, trimmed)
292
+ return None
293
+
294
+
295
+ def create_repo_from_template(call: Call) -> dict[str, Any] | None:
296
+ data = call.data
297
+ template = data.get("template")
298
+ if not isinstance(template, str) or template.count("/") != 1:
299
+ raise InputError("template must be owner/name")
300
+ template_owner, template_name = template.split("/", 1)
301
+ dest_owner = data.get("owner")
302
+ if not isinstance(dest_owner, str) or not dest_owner.strip():
303
+ raise InputError("owner is required")
304
+ dest_name = require_str(data, "name")
305
+ repo = f"{template_owner}/{template_name}"
306
+ body: dict[str, Any] = {
307
+ "owner": dest_owner.strip(),
308
+ "name": dest_name,
309
+ "private": as_bool(data.get("private"), default=True),
310
+ "include_all_branches": as_bool(data.get("include_all_branches"), default=False),
311
+ }
312
+ if data.get("description") is not None:
313
+ body["description"] = data["description"]
314
+ created = call.app.rest(
315
+ "POST",
316
+ f"/repos/{template_owner}/{template_name}/generate",
317
+ repo=repo,
318
+ json_body=body,
319
+ ).data or {}
320
+ trimmed = trim_repo(created)
321
+ if not trimmed.get("full_name"):
322
+ trimmed["full_name"] = f"{dest_owner.strip()}/{dest_name}"
323
+ trimmed["owner"] = dest_owner.strip()
324
+ trimmed["name"] = dest_name
325
+ if not as_bool(data.get("wait_until_ready")):
326
+ return {"success": True, "repo": trimmed}
327
+ _register_repo_ready(call, trimmed)
328
+ return None
329
+
330
+
331
+ def create_repo(call: Call) -> dict[str, Any]:
332
+ data = call.data
333
+ owner = data.get("owner")
334
+ if not isinstance(owner, str) or not owner.strip():
335
+ raise InputError("owner is required")
336
+ name = require_str(data, "name")
337
+ body: dict[str, Any] = {
338
+ "name": name,
339
+ "private": as_bool(data.get("private"), default=True),
340
+ "auto_init": as_bool(data.get("auto_init"), default=False),
341
+ }
342
+ if data.get("description") is not None:
343
+ body["description"] = data["description"]
344
+ created = call.app.rest(
345
+ "POST",
346
+ f"/orgs/{owner.strip()}/repos",
347
+ owner=owner.strip(),
348
+ json_body=body,
349
+ ).data or {}
350
+ return {"success": True, "repo": trim_repo(created)}
351
+
352
+
353
+ def set_actions_enabled(call: Call) -> dict[str, Any]:
354
+ owner, name = require_repo(call.data)
355
+ repo = f"{owner}/{name}"
356
+ enabled = as_bool(call.data.get("enabled"), default=True)
357
+ body: dict[str, Any] = {"enabled": enabled}
358
+ if enabled:
359
+ allowed = call.data.get("allowed_actions") or "all"
360
+ if allowed not in ("all", "local_only", "selected"):
361
+ raise InputError("allowed_actions must be all, local_only, or selected")
362
+ body["allowed_actions"] = allowed
363
+ call.app.rest(
364
+ "PUT",
365
+ f"/repos/{owner}/{name}/actions/permissions",
366
+ repo=repo,
367
+ json_body=body,
368
+ )
369
+ return {"success": True, "repo": repo_full_name(owner, name), "enabled": enabled}
370
+
371
+
372
+ def _register_repo_ready(call: Call, repo: dict[str, Any]) -> None:
373
+ full_name = repo.get("full_name")
374
+ if not full_name:
375
+ raise RuntimeError("GitHub did not return a repository full_name")
376
+ register_await(
377
+ call.item.id,
378
+ kind="repo_ready",
379
+ repo_full_name=str(full_name),
380
+ params={
381
+ "full_name": full_name,
382
+ "html_url": repo.get("html_url"),
383
+ "clone_url": repo.get("clone_url"),
384
+ },
385
+ timeout_seconds=opt_float(call.data, "timeout_seconds", "timeout", default=180.0),
386
+ poll_interval_seconds=opt_float(call.data, "poll_interval_seconds", "poll_interval", default=5.0),
387
+ )
388
+
389
+
390
+ def _resolve_sha(call: Call, owner: str, name: str, ref: str) -> str:
391
+ if _SHA.fullmatch(ref):
392
+ return ref.lower()
393
+ repo = f"{owner}/{name}"
394
+ try:
395
+ body = call.app.rest(
396
+ "GET",
397
+ f"/repos/{owner}/{name}/git/ref/heads/{path_segment(ref)}",
398
+ repo=repo,
399
+ ).data or {}
400
+ sha = (body.get("object") or {}).get("sha")
401
+ if sha:
402
+ return str(sha)
403
+ except GitHubRequestError as exc:
404
+ if exc.status != 404:
405
+ raise
406
+ commit = call.app.rest("GET", f"/repos/{owner}/{name}/commits/{path_segment(ref)}", repo=repo).data or {}
407
+ sha = commit.get("sha")
408
+ if not sha:
409
+ raise InputError(f"could not resolve ref {ref!r}")
410
+ return str(sha)
411
+
412
+
413
+ def _trim_commit(commit: dict[str, Any]) -> dict[str, Any]:
414
+ commit_body = commit.get("commit") or {}
415
+ message = commit_body.get("message") or commit.get("message") or ""
416
+ author = commit_body.get("author") or {}
417
+ git_author = commit.get("author") or {}
418
+ return {
419
+ "sha": commit.get("sha"),
420
+ "message": message.split("\n", 1)[0][:300],
421
+ "author": author.get("name") or (git_author.get("login") if isinstance(git_author, dict) else None),
422
+ "date": author.get("date"),
423
+ "html_url": commit.get("html_url"),
424
+ }
@@ -0,0 +1,109 @@
1
+ """Code, repository, and issue search.
2
+
3
+ ``owner`` (or ``GITHUB_DEFAULT_OWNER``) selects which installation token to use.
4
+ Put ``org:``, ``user:``, or ``repo:`` qualifiers in ``q`` yourself. Code search
5
+ is limited by GitHub to about 10 requests per minute.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from os import getenv
11
+ from typing import Any
12
+
13
+ from continuum_task_server_bundle.github.errors import InputError
14
+ from continuum_task_server_bundle.github.methods._common import Call, opt_int
15
+
16
+
17
+ def search_code(call: Call) -> dict[str, Any]:
18
+ return _search(call, "code", _trim_code)
19
+
20
+
21
+ def search_repos(call: Call) -> dict[str, Any]:
22
+ return _search(call, "repositories", _trim_repo)
23
+
24
+
25
+ def search_issues(call: Call) -> dict[str, Any]:
26
+ return _search(call, "issues", _trim_issue)
27
+
28
+
29
+ def _search(call: Call, resource: str, trim) -> dict[str, Any]:
30
+ data = call.data
31
+ query = data.get("q", data.get("query"))
32
+ if not isinstance(query, str) or not query.strip():
33
+ raise InputError("q is required")
34
+ owner = _owner(data)
35
+ per_page = min(100, max(1, opt_int(data, "per_page", "limit", default=30)))
36
+ page = max(1, opt_int(data, "page", default=1))
37
+ response = call.app.rest(
38
+ "GET",
39
+ f"/search/{resource}",
40
+ owner=owner,
41
+ params={"q": query.strip(), "per_page": per_page, "page": page, "sort": data.get("sort"), "order": data.get("order")},
42
+ )
43
+ body = response.data or {}
44
+ items = body.get("items") or []
45
+ return {
46
+ "success": True,
47
+ "total_count": body.get("total_count", 0),
48
+ "incomplete_results": bool(body.get("incomplete_results")),
49
+ "items": [trim(item) for item in items],
50
+ }
51
+
52
+
53
+ def _owner(data: dict[str, Any]) -> str:
54
+ owner = data.get("owner") or getenv("GITHUB_DEFAULT_OWNER")
55
+ if not owner or not isinstance(owner, str) or not owner.strip():
56
+ raise InputError("owner is required (or set GITHUB_DEFAULT_OWNER)")
57
+ return owner.strip()
58
+
59
+
60
+ def _trim_code(item: dict[str, Any]) -> dict[str, Any]:
61
+ repo = item.get("repository") or {}
62
+ matches = item.get("text_matches") or []
63
+ trimmed_matches = []
64
+ for match in matches[:5]:
65
+ fragment = match.get("fragment") or ""
66
+ trimmed_matches.append(
67
+ {
68
+ "property": match.get("property"),
69
+ "fragment": fragment[:500],
70
+ }
71
+ )
72
+ return {
73
+ "name": item.get("name"),
74
+ "path": item.get("path"),
75
+ "sha": item.get("sha"),
76
+ "html_url": item.get("html_url"),
77
+ "repository": repo.get("full_name") if isinstance(repo, dict) else None,
78
+ "text_matches": trimmed_matches,
79
+ }
80
+
81
+
82
+ def _trim_repo(item: dict[str, Any]) -> dict[str, Any]:
83
+ return {
84
+ "full_name": item.get("full_name"),
85
+ "description": item.get("description"),
86
+ "html_url": item.get("html_url"),
87
+ "private": item.get("private"),
88
+ "language": item.get("language"),
89
+ "stargazers_count": item.get("stargazers_count"),
90
+ "default_branch": item.get("default_branch"),
91
+ "fork": item.get("fork"),
92
+ }
93
+
94
+
95
+ def _trim_issue(item: dict[str, Any]) -> dict[str, Any]:
96
+ repo = item.get("repository") or {}
97
+ body = item.get("body") or ""
98
+ user = item.get("user") or {}
99
+ return {
100
+ "number": item.get("number"),
101
+ "title": item.get("title"),
102
+ "state": item.get("state"),
103
+ "html_url": item.get("html_url"),
104
+ "body": body[:500],
105
+ "user_login": user.get("login") if isinstance(user, dict) else None,
106
+ "is_pull_request": item.get("pull_request") is not None,
107
+ "repository": repo.get("full_name") if isinstance(repo, dict) else None,
108
+ "updated_at": item.get("updated_at"),
109
+ }
@@ -0,0 +1,91 @@
1
+ """GitHub task registration and managed polling/webhook lifecycle."""
2
+ import logging
3
+ import socket
4
+ import threading
5
+ import time
6
+ from os import getenv
7
+
8
+ import uvicorn
9
+
10
+ from .awaits.cleanup import drop_await_rows
11
+ from .awaits.poller import run_github_await_poller
12
+ from .errors import GitHubRequestError, InputError
13
+ from .github_app import GitHubApp
14
+ from .github_http import GitHubHttp
15
+ from .methods import METHODS
16
+ from .methods._common import Call
17
+ from .webhook_server import webhook_app, webhook_enabled
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ class _GitHubService:
22
+ def __init__(self, server, app, http):
23
+ self.server, self.app, self.http = server, app, http
24
+ self.stop_event = threading.Event()
25
+ self.threads = []
26
+ self.web = None
27
+ self.socket = None
28
+
29
+ def start(self):
30
+ if webhook_enabled():
31
+ address = getenv("GITHUB_WEBHOOK_HOST", getenv("WEBHOOK_HOST", "0.0.0.0"))
32
+ port = int(getenv("GITHUB_WEBHOOK_PORT", getenv("WEBHOOK_PORT", "8088")))
33
+ self.web = uvicorn.Server(uvicorn.Config(webhook_app, host=address, port=port, log_level="info"))
34
+ self.socket = self.web.config.bind_socket() # fail startup on bind errors
35
+ thread = threading.Thread(target=self.web.run, kwargs={"sockets": [self.socket]}, name="github-webhook", daemon=True)
36
+ self.threads.append(thread)
37
+ thread.start()
38
+ deadline = time.monotonic() + 10
39
+ while not self.web.started and thread.is_alive() and time.monotonic() < deadline:
40
+ time.sleep(0.01)
41
+ if not self.web.started:
42
+ raise RuntimeError("GitHub webhook failed to start")
43
+ thread = threading.Thread(target=run_github_await_poller, args=(self.server, self.app, self.stop_event), name="github-await-poller", daemon=True)
44
+ self.threads.append(thread)
45
+ thread.start()
46
+
47
+ def stop(self):
48
+ self.stop_event.set()
49
+ if self.web is not None:
50
+ self.web.should_exit = True
51
+ for thread in self.threads:
52
+ if thread.ident is not None:
53
+ thread.join(timeout=10)
54
+ if self.socket is not None:
55
+ self.socket.close()
56
+ if any(thread.is_alive() for thread in self.threads):
57
+ raise RuntimeError("GitHub service failed to stop")
58
+ self.http.close()
59
+
60
+
61
+ def register_github(host, *, concurrency=None):
62
+ server = host.server
63
+ http = GitHubHttp()
64
+ app = GitHubApp(http)
65
+ service = _GitHubService(server, app, http)
66
+ concurrency = int(getenv("GITHUB_TASK_CONCURRENCY", "8")) if concurrency is None else concurrency
67
+
68
+ def handle(item, context):
69
+ context.on_cancelled(lambda: drop_await_rows(item.id))
70
+ if context.is_cancelled():
71
+ return
72
+ if not item.task_item_version_id:
73
+ result = {"success": False, "status": 400, "error": "task item version is required", "github_message": None}
74
+ else:
75
+ version = server.client.task_items.versions.get_by_id(item.task_item_version_id)
76
+ method = (version.item_definition_json or {}).get("method")
77
+ handler = METHODS.get(method)
78
+ if handler is None:
79
+ result = {"success": False, "status": 400, "error": "Method not found" if method else "method is required", "github_message": None}
80
+ else:
81
+ try:
82
+ result = handler(Call(app=app, item=item))
83
+ except (GitHubRequestError, InputError) as exc:
84
+ result = exc.to_output()
85
+ if context.is_cancelled():
86
+ drop_await_rows(item.id)
87
+ elif result is not None:
88
+ server.complete_queue_item(item.id, output_data=result)
89
+
90
+ server.register("github", handle, auto_complete=False, occupy_slot_until_complete=False, concurrency=concurrency)
91
+ host.add_service("github", service)
@@ -0,0 +1,65 @@
1
+ -- github_awaits: durable state for Continuum queue items waiting on GitHub.
2
+ --
3
+ -- Apply: psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f db/001_github_awaits.sql
4
+ --
5
+ -- Requires PostgreSQL 13+ (gen_random_uuid() without extensions).
6
+
7
+ DROP TABLE IF EXISTS github_awaits CASCADE;
8
+
9
+ CREATE TABLE github_awaits (
10
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
11
+
12
+ -- Continuum queue item this await belongs to (one row per item; idempotent INSERT).
13
+ queue_item_id UUID NOT NULL UNIQUE,
14
+
15
+ kind TEXT NOT NULL
16
+ CHECK (kind IN ('await_ci', 'await_comments', 'await_pull_request', 'repo_ready')),
17
+
18
+ -- Lowercased owner/name. Webhook routing compares against this.
19
+ repo_full_name TEXT NOT NULL,
20
+
21
+ -- Pull request or issue number. Null for repo_ready and ref-based CI waits.
22
+ number INTEGER,
23
+
24
+ -- Commit the wait is pinned to (await_ci). Also used to route check webhooks.
25
+ head_sha TEXT,
26
+
27
+ params_json JSONB NOT NULL DEFAULT '{}'::jsonb,
28
+ state_json JSONB NOT NULL DEFAULT '{}'::jsonb,
29
+ etags_json JSONB NOT NULL DEFAULT '{}'::jsonb,
30
+
31
+ timeout_seconds DOUBLE PRECISION NOT NULL
32
+ CHECK (timeout_seconds > 0),
33
+
34
+ poll_interval_seconds DOUBLE PRECISION NOT NULL
35
+ CHECK (poll_interval_seconds > 0),
36
+
37
+ registered_at TIMESTAMPTZ NOT NULL DEFAULT now(),
38
+ deadline_at TIMESTAMPTZ NOT NULL,
39
+ next_poll_at TIMESTAMPTZ NOT NULL DEFAULT now(),
40
+
41
+ status TEXT NOT NULL DEFAULT 'active'
42
+ CHECK (status IN ('active', 'completed', 'failed')),
43
+
44
+ completed_at TIMESTAMPTZ,
45
+ error_json JSONB
46
+ );
47
+
48
+ COMMENT ON TABLE github_awaits IS
49
+ 'In-flight GitHub awaits for Continuum queue items; workers claim rows when next_poll_at <= now().';
50
+
51
+ COMMENT ON COLUMN github_awaits.queue_item_id IS 'Continuum QueueItem.id; unique so registration is idempotent.';
52
+ COMMENT ON COLUMN github_awaits.next_poll_at IS 'Claim when <= now(); claim query advances by poll_interval_seconds. Webhooks set this to now().';
53
+ COMMENT ON COLUMN github_awaits.head_sha IS 'Pinned commit for await_ci. Check webhooks match this column.';
54
+
55
+ CREATE INDEX github_awaits_active_next_poll_idx
56
+ ON github_awaits (next_poll_at ASC)
57
+ WHERE status = 'active';
58
+
59
+ CREATE INDEX github_awaits_active_number_idx
60
+ ON github_awaits (repo_full_name, number)
61
+ WHERE status = 'active' AND number IS NOT NULL;
62
+
63
+ CREATE INDEX github_awaits_active_sha_idx
64
+ ON github_awaits (repo_full_name, head_sha)
65
+ WHERE status = 'active' AND head_sha IS NOT NULL;