agentjam 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.
- agentjam/__init__.py +435 -0
- agentjam/_adapters/__init__.py +0 -0
- agentjam/_adapters/responses.py +73 -0
- agentjam/_adapters/shared.py +435 -0
- agentjam/_agent.py +1032 -0
- agentjam/_agent_access.py +360 -0
- agentjam/_agent_delegations.py +376 -0
- agentjam/_agent_executions.py +566 -0
- agentjam/_agent_judging.py +288 -0
- agentjam/_agent_options.py +122 -0
- agentjam/_agent_routing.py +214 -0
- agentjam/_agent_session.py +195 -0
- agentjam/_agent_support.py +415 -0
- agentjam/_artifacts.py +565 -0
- agentjam/_attachments.py +112 -0
- agentjam/_connections.py +1282 -0
- agentjam/_content.py +29 -0
- agentjam/_cron.py +302 -0
- agentjam/_errors.py +238 -0
- agentjam/_events.py +113 -0
- agentjam/_files.py +55 -0
- agentjam/_github.py +742 -0
- agentjam/_idempotency.py +68 -0
- agentjam/_inputs.py +79 -0
- agentjam/_models.py +21 -0
- agentjam/_polling.py +139 -0
- agentjam/_profile.py +244 -0
- agentjam/_protocol.py +480 -0
- agentjam/_providers.py +365 -0
- agentjam/_recaps.py +67 -0
- agentjam/_relay/__init__.py +0 -0
- agentjam/_relay/actions.py +234 -0
- agentjam/_relay/artifacts.py +96 -0
- agentjam/_relay/base.py +387 -0
- agentjam/_relay/commits.py +77 -0
- agentjam/_relay/copies.py +66 -0
- agentjam/_relay/credentials.py +127 -0
- agentjam/_relay/endpoints.py +39 -0
- agentjam/_relay/follow_ups.py +548 -0
- agentjam/_relay/frames.py +443 -0
- agentjam/_relay/guest_store.py +114 -0
- agentjam/_relay/guests.py +55 -0
- agentjam/_relay/inputs.py +119 -0
- agentjam/_relay/lineage.py +294 -0
- agentjam/_relay/memory.py +1045 -0
- agentjam/_relay/payments.py +204 -0
- agentjam/_relay/profiles.py +95 -0
- agentjam/_relay/remote.py +826 -0
- agentjam/_relay/resumptions.py +65 -0
- agentjam/_relay/revisions.py +43 -0
- agentjam/_relay/schedule_follow_ups.py +274 -0
- agentjam/_relay/schedules.py +547 -0
- agentjam/_relay/secrets.py +275 -0
- agentjam/_relay/sessions.py +640 -0
- agentjam/_relay/uploads.py +71 -0
- agentjam/_requests.py +178 -0
- agentjam/_screening.py +368 -0
- agentjam/_secrets.py +153 -0
- agentjam/_sentry.py +233 -0
- agentjam/_signals.py +98 -0
- agentjam/_slack.py +468 -0
- agentjam/_stripe.py +93 -0
- agentjam/_tasks/__init__.py +0 -0
- agentjam/_tasks/access.py +142 -0
- agentjam/_tasks/incoming.py +952 -0
- agentjam/_tasks/outgoing.py +472 -0
- agentjam/_tasks/scheduled.py +206 -0
- agentjam/_tasks/serial.py +40 -0
- agentjam/_tasks/triggers.py +258 -0
- agentjam/_tasks/watches.py +77 -0
- agentjam/_tools.py +1035 -0
- agentjam/_types.py +965 -0
- agentjam/_utils.py +75 -0
- agentjam/_verdicts.py +21 -0
- agentjam/_watermarks.py +59 -0
- agentjam/anthropic.py +442 -0
- agentjam/mpp.py +233 -0
- agentjam/openai.py +141 -0
- agentjam/openai_agents.py +253 -0
- agentjam/py.typed +0 -0
- agentjam/pydantic_ai.py +301 -0
- agentjam/skills.py +69 -0
- agentjam-0.1.0.dist-info/METADATA +210 -0
- agentjam-0.1.0.dist-info/RECORD +86 -0
- agentjam-0.1.0.dist-info/WHEEL +4 -0
- agentjam-0.1.0.dist-info/licenses/LICENSE +21 -0
agentjam/_github.py
ADDED
|
@@ -0,0 +1,742 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any, Generic, Literal, TypeVar
|
|
7
|
+
from urllib.parse import urlencode
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
from pydantic import BaseModel
|
|
11
|
+
|
|
12
|
+
from agentjam._errors import AgentJamError
|
|
13
|
+
from agentjam._events import (
|
|
14
|
+
EventSource,
|
|
15
|
+
ReportedEvent,
|
|
16
|
+
SourceDelivery,
|
|
17
|
+
SourceEvent,
|
|
18
|
+
SourceRequest,
|
|
19
|
+
SourceResponse,
|
|
20
|
+
read_source_request,
|
|
21
|
+
)
|
|
22
|
+
from agentjam._models import WireModel
|
|
23
|
+
from agentjam._polling import (
|
|
24
|
+
Polling,
|
|
25
|
+
Watermark,
|
|
26
|
+
compute_now,
|
|
27
|
+
construct_interval_property,
|
|
28
|
+
get_interval,
|
|
29
|
+
log_error,
|
|
30
|
+
parse_time,
|
|
31
|
+
poll_schedule,
|
|
32
|
+
truncate_summary,
|
|
33
|
+
)
|
|
34
|
+
from agentjam._types import (
|
|
35
|
+
JsonObject,
|
|
36
|
+
JsonSchema,
|
|
37
|
+
OnScheduleActive,
|
|
38
|
+
Trigger,
|
|
39
|
+
TriggerActivation,
|
|
40
|
+
TriggerContext,
|
|
41
|
+
TriggerEvent,
|
|
42
|
+
TriggerSchedule,
|
|
43
|
+
)
|
|
44
|
+
from agentjam._watermarks import MemoryWatermarkStore, WatermarkStore
|
|
45
|
+
|
|
46
|
+
GITHUB_API = "https://api.github.com"
|
|
47
|
+
|
|
48
|
+
PULL_REQUESTS_PAGE_SIZE = 50
|
|
49
|
+
|
|
50
|
+
ISSUE_EVENTS_PAGE_SIZE = 100
|
|
51
|
+
|
|
52
|
+
MAX_ISSUE_EVENT_PAGES = 10
|
|
53
|
+
|
|
54
|
+
MAX_EVENT_KEY_LENGTH = 256
|
|
55
|
+
|
|
56
|
+
REPOSITORY_PROPERTY: JsonSchema = {
|
|
57
|
+
"type": "string",
|
|
58
|
+
"pattern": r"^[\w.-]+/[\w.-]+$",
|
|
59
|
+
"description": "The GitHub repository to watch, as owner/name",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class GitHubPullRequestData(WireModel):
|
|
64
|
+
"""A pull request, as the `task.event.data` of a `pull_request_opened` run."""
|
|
65
|
+
|
|
66
|
+
repository: str
|
|
67
|
+
"""The repository, as `owner/name`."""
|
|
68
|
+
repository_id: int
|
|
69
|
+
number: int
|
|
70
|
+
title: str
|
|
71
|
+
url: str
|
|
72
|
+
author: str | None
|
|
73
|
+
"""The login of the pull request's author, unless their account was deleted."""
|
|
74
|
+
draft: bool
|
|
75
|
+
fork: bool
|
|
76
|
+
"""Whether the pull request's branch lives in a fork, or in a fork that was deleted."""
|
|
77
|
+
base_branch: str
|
|
78
|
+
head_branch: str
|
|
79
|
+
head_sha: str
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class GitHubMergedPullRequestData(GitHubPullRequestData):
|
|
83
|
+
"""A merged pull request, as the `task.event.data` of a `pull_request_merged` run."""
|
|
84
|
+
|
|
85
|
+
merged_at: str
|
|
86
|
+
merge_commit_sha: str | None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class GitHubIssueAssignedData(WireModel):
|
|
90
|
+
"""An issue assigned to the schedule's user or labeled with its label, as the `task.event.data` of an `issue_assigned` run."""
|
|
91
|
+
|
|
92
|
+
repository: str
|
|
93
|
+
"""The repository, as `owner/name`."""
|
|
94
|
+
repository_id: int
|
|
95
|
+
number: int
|
|
96
|
+
title: str
|
|
97
|
+
url: str
|
|
98
|
+
action: Literal["assigned", "labeled"]
|
|
99
|
+
"""What the issue event changed."""
|
|
100
|
+
assignee: str | None = None
|
|
101
|
+
"""The login of the user the issue was assigned to, when `action` is `assigned`."""
|
|
102
|
+
label: str | None = None
|
|
103
|
+
"""The label added to the issue, when `action` is `labeled`."""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class GitHubRepository(BaseModel):
|
|
107
|
+
id: int
|
|
108
|
+
full_name: str
|
|
109
|
+
default_branch: str
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class GitHubUser(BaseModel):
|
|
113
|
+
login: str
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class GitHubForkRepository(BaseModel):
|
|
117
|
+
id: int
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class GitHubHead(BaseModel):
|
|
121
|
+
ref: str
|
|
122
|
+
sha: str
|
|
123
|
+
repo: GitHubForkRepository | None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class GitHubBase(BaseModel):
|
|
127
|
+
ref: str
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class GitHubPullRequest(BaseModel):
|
|
131
|
+
number: int
|
|
132
|
+
title: str
|
|
133
|
+
html_url: str
|
|
134
|
+
draft: bool | None = None
|
|
135
|
+
user: GitHubUser | None
|
|
136
|
+
created_at: str
|
|
137
|
+
merged_at: str | None
|
|
138
|
+
merge_commit_sha: str | None
|
|
139
|
+
head: GitHubHead
|
|
140
|
+
base: GitHubBase
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class GitHubIssue(BaseModel):
|
|
144
|
+
number: int
|
|
145
|
+
title: str
|
|
146
|
+
html_url: str
|
|
147
|
+
pull_request: dict[str, Any] | None = None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class GitHubLabel(BaseModel):
|
|
151
|
+
name: str
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class GitHubIssueEvent(BaseModel):
|
|
155
|
+
id: int
|
|
156
|
+
event: str
|
|
157
|
+
created_at: str
|
|
158
|
+
issue: GitHubIssue | None = None
|
|
159
|
+
assignee: GitHubUser | None = None
|
|
160
|
+
label: GitHubLabel | None = None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class PullRequestDelivery(BaseModel):
|
|
164
|
+
action: str | None = None
|
|
165
|
+
repository: GitHubRepository | None = None
|
|
166
|
+
pull_request: GitHubPullRequest | None = None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
Item = TypeVar("Item", bound=BaseModel)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@dataclass(frozen=True, kw_only=True)
|
|
173
|
+
class Page(Generic[Item]):
|
|
174
|
+
items: list[Item]
|
|
175
|
+
etag: str | None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@dataclass(frozen=True, kw_only=True)
|
|
179
|
+
class IssueEvents:
|
|
180
|
+
etag: str | None
|
|
181
|
+
events: list[GitHubIssueEvent]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def is_signed(secret: str, headers: httpx.Headers, body: str) -> bool:
|
|
185
|
+
digest = hmac.new(secret.encode(), body.encode(), hashlib.sha256).hexdigest()
|
|
186
|
+
signature = headers.get("x-hub-signature-256", "")
|
|
187
|
+
|
|
188
|
+
return hmac.compare_digest(signature.encode(), f"sha256={digest}".encode())
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
async def request_github(
|
|
192
|
+
token: str, path: str, etag: str | None = None
|
|
193
|
+
) -> httpx.Response:
|
|
194
|
+
headers = {
|
|
195
|
+
"accept": "application/vnd.github+json",
|
|
196
|
+
"authorization": f"Bearer {token}",
|
|
197
|
+
"x-github-api-version": "2022-11-28",
|
|
198
|
+
}
|
|
199
|
+
if etag:
|
|
200
|
+
headers["if-none-match"] = etag
|
|
201
|
+
|
|
202
|
+
async with httpx.AsyncClient(base_url=GITHUB_API) as client:
|
|
203
|
+
response = await client.get(path, headers=headers)
|
|
204
|
+
|
|
205
|
+
if response.is_success or response.status_code == 304:
|
|
206
|
+
return response
|
|
207
|
+
|
|
208
|
+
raise AgentJamError(
|
|
209
|
+
f"GitHub answered {response.status_code} for {path}: {response.text}"
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
async def list_page(
|
|
214
|
+
token: str, path: str, etag: str | None, kind: type[Item]
|
|
215
|
+
) -> Page[Item] | None:
|
|
216
|
+
"""Lists a page of `path`, or returns None when GitHub says it hasn't changed since `etag`, which costs no rate limit."""
|
|
217
|
+
response = await request_github(token, path, etag)
|
|
218
|
+
if response.status_code == 304:
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
items = [kind.model_validate(item) for item in response.json()]
|
|
222
|
+
|
|
223
|
+
return Page(items=items, etag=response.headers.get("etag"))
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
async def get_repository(token: str, repository: str) -> GitHubRepository:
|
|
227
|
+
try:
|
|
228
|
+
response = await request_github(token, f"/repos/{repository}")
|
|
229
|
+
|
|
230
|
+
return GitHubRepository.model_validate(response.json())
|
|
231
|
+
except Exception as error:
|
|
232
|
+
raise AgentJamError(
|
|
233
|
+
f"The schedule's GitHub account can't read {repository}, so it can't be watched"
|
|
234
|
+
) from error
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def is_later(time: str, since: str) -> bool:
|
|
238
|
+
return parse_time(time) > parse_time(since)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def is_match(value: str | None, wanted: str | None) -> bool:
|
|
242
|
+
return wanted is not None and value is not None and value.lower() == wanted.lower()
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def construct_pull_request_data(
|
|
246
|
+
repository: GitHubRepository, pull_request: GitHubPullRequest
|
|
247
|
+
) -> GitHubPullRequestData:
|
|
248
|
+
head_repository = pull_request.head.repo
|
|
249
|
+
|
|
250
|
+
return GitHubPullRequestData(
|
|
251
|
+
repository=repository.full_name,
|
|
252
|
+
repository_id=repository.id,
|
|
253
|
+
number=pull_request.number,
|
|
254
|
+
title=pull_request.title,
|
|
255
|
+
url=pull_request.html_url,
|
|
256
|
+
author=pull_request.user.login if pull_request.user is not None else None,
|
|
257
|
+
draft=pull_request.draft or False,
|
|
258
|
+
fork=head_repository is None or head_repository.id != repository.id,
|
|
259
|
+
base_branch=pull_request.base.ref,
|
|
260
|
+
head_branch=pull_request.head.ref,
|
|
261
|
+
head_sha=pull_request.head.sha,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
# Invariant: the id leaves out whether the pull request was a draft, so a draft that ran when it opened doesn't run again once it's ready.
|
|
266
|
+
def construct_opened_event(data: GitHubPullRequestData) -> TriggerEvent:
|
|
267
|
+
return TriggerEvent(
|
|
268
|
+
id=f"github:{data.repository_id}#{data.number}",
|
|
269
|
+
summary=truncate_summary(
|
|
270
|
+
f"Pull request #{data.number} opened in {data.repository}: {data.title}"
|
|
271
|
+
),
|
|
272
|
+
data=data.model_dump(mode="json"),
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def construct_merged_event(
|
|
277
|
+
repository: GitHubRepository, pull_request: GitHubPullRequest, merged_at: str
|
|
278
|
+
) -> TriggerEvent:
|
|
279
|
+
data = GitHubMergedPullRequestData(
|
|
280
|
+
**dict(construct_pull_request_data(repository, pull_request)),
|
|
281
|
+
merged_at=merged_at,
|
|
282
|
+
merge_commit_sha=pull_request.merge_commit_sha,
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
return TriggerEvent(
|
|
286
|
+
id=f"github:{data.repository_id}#{data.number}:merged",
|
|
287
|
+
summary=truncate_summary(
|
|
288
|
+
f"Pull request #{data.number} merged into {data.base_branch} in {data.repository}: {data.title}"
|
|
289
|
+
),
|
|
290
|
+
data=data.model_dump(mode="json"),
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def read_issue_change(
|
|
295
|
+
issue_event: GitHubIssueEvent, config: JsonObject
|
|
296
|
+
) -> JsonObject | None:
|
|
297
|
+
login = issue_event.assignee.login if issue_event.assignee is not None else None
|
|
298
|
+
name = issue_event.label.name if issue_event.label is not None else None
|
|
299
|
+
if issue_event.event == "assigned" and is_match(login, config.get("assignee")):
|
|
300
|
+
return {"action": "assigned", "assignee": login}
|
|
301
|
+
|
|
302
|
+
if issue_event.event == "labeled" and is_match(name, config.get("label")):
|
|
303
|
+
return {"action": "labeled", "label": name}
|
|
304
|
+
|
|
305
|
+
return None
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def read_assignment(
|
|
309
|
+
repository: GitHubRepository, issue_event: GitHubIssueEvent, config: JsonObject
|
|
310
|
+
) -> TriggerEvent | None:
|
|
311
|
+
issue = issue_event.issue
|
|
312
|
+
change = read_issue_change(issue_event, config)
|
|
313
|
+
if issue is None or issue.pull_request is not None or change is None:
|
|
314
|
+
return None
|
|
315
|
+
|
|
316
|
+
data = GitHubIssueAssignedData(
|
|
317
|
+
repository=repository.full_name,
|
|
318
|
+
repository_id=repository.id,
|
|
319
|
+
number=issue.number,
|
|
320
|
+
title=issue.title,
|
|
321
|
+
url=issue.html_url,
|
|
322
|
+
**change,
|
|
323
|
+
)
|
|
324
|
+
action = (
|
|
325
|
+
f"assigned to {data.assignee}"
|
|
326
|
+
if data.action == "assigned"
|
|
327
|
+
else f"labeled {data.label}"
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
return TriggerEvent(
|
|
331
|
+
id=f"github:{repository.id}#{issue.number}@{issue_event.id}",
|
|
332
|
+
summary=truncate_summary(
|
|
333
|
+
f"Issue #{issue.number} in {repository.full_name} {action}: {issue.title}"
|
|
334
|
+
),
|
|
335
|
+
data=data.to_wire(),
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def construct_opened_key(repository_id: int, *, draft: bool, fork: bool) -> str:
|
|
340
|
+
prefix = ("fork_" if fork else "") + ("draft_" if draft else "")
|
|
341
|
+
|
|
342
|
+
return f"github:{repository_id}:{prefix}pull_request_opened"
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def construct_merged_key(repository_id: int, branch: str) -> str:
|
|
346
|
+
return f"github:{repository_id}:pull_request_merged:{branch}"
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def read_delivery(delivery: PullRequestDelivery) -> list[SourceEvent]:
|
|
350
|
+
repository, pull_request = delivery.repository, delivery.pull_request
|
|
351
|
+
if repository is None or pull_request is None:
|
|
352
|
+
return []
|
|
353
|
+
|
|
354
|
+
data = construct_pull_request_data(repository, pull_request)
|
|
355
|
+
is_opened = delivery.action == "opened" or (
|
|
356
|
+
delivery.action == "ready_for_review" and not data.draft
|
|
357
|
+
)
|
|
358
|
+
if is_opened:
|
|
359
|
+
event_keys = [
|
|
360
|
+
construct_opened_key(repository.id, draft=data.draft, fork=data.fork)
|
|
361
|
+
]
|
|
362
|
+
|
|
363
|
+
return [
|
|
364
|
+
ReportedEvent(event_keys=event_keys, event=construct_opened_event(data))
|
|
365
|
+
]
|
|
366
|
+
|
|
367
|
+
if delivery.action != "closed" or pull_request.merged_at is None:
|
|
368
|
+
return []
|
|
369
|
+
|
|
370
|
+
merged_key = construct_merged_key(repository.id, data.base_branch)
|
|
371
|
+
if len(merged_key) > MAX_EVENT_KEY_LENGTH:
|
|
372
|
+
return []
|
|
373
|
+
|
|
374
|
+
event = construct_merged_event(repository, pull_request, pull_request.merged_at)
|
|
375
|
+
|
|
376
|
+
return [ReportedEvent(event_keys=[merged_key], event=event)]
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
class GitHubWebhooks:
|
|
380
|
+
"""Reads the webhook deliveries of a GitHub App or repository, verifying each one's signature."""
|
|
381
|
+
|
|
382
|
+
def __init__(self, secret: str) -> None:
|
|
383
|
+
self._secret = secret
|
|
384
|
+
|
|
385
|
+
async def receive(self, request: SourceRequest | httpx.Request) -> SourceDelivery:
|
|
386
|
+
"""Verifies a GitHub delivery and reads the pull request events it carries.
|
|
387
|
+
|
|
388
|
+
Args:
|
|
389
|
+
request: GitHub's delivery.
|
|
390
|
+
|
|
391
|
+
Returns:
|
|
392
|
+
The answer to send GitHub, and the events to dispatch.
|
|
393
|
+
"""
|
|
394
|
+
received = await read_source_request(request)
|
|
395
|
+
if not is_signed(self._secret, received.headers, received.body):
|
|
396
|
+
return SourceDelivery(
|
|
397
|
+
response=SourceResponse(status=401, body="Invalid GitHub signature")
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
if received.headers.get("x-github-event") != "pull_request":
|
|
401
|
+
return SourceDelivery(response=SourceResponse(status=200))
|
|
402
|
+
|
|
403
|
+
delivery = PullRequestDelivery.model_validate(json.loads(received.body))
|
|
404
|
+
|
|
405
|
+
return SourceDelivery(
|
|
406
|
+
response=SourceResponse(status=200), events=read_delivery(delivery)
|
|
407
|
+
)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def github_webhooks(*, secret: str) -> EventSource:
|
|
411
|
+
"""Reads the webhook deliveries of a GitHub App or repository, for `agent.receive_events()` at the webhook's URL.
|
|
412
|
+
|
|
413
|
+
It verifies each delivery's `X-Hub-Signature-256` in constant time, and reads opened, ready for review and merged
|
|
414
|
+
pull requests under the keys `github_triggers()` subscribe to, with the same event ids their polls fire.
|
|
415
|
+
|
|
416
|
+
Args:
|
|
417
|
+
secret: The secret of the webhook, which signs each delivery.
|
|
418
|
+
|
|
419
|
+
Returns:
|
|
420
|
+
An event source for GitHub's deliveries.
|
|
421
|
+
"""
|
|
422
|
+
return GitHubWebhooks(secret)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def list_opened_keys(repository_id: int, *, drafts: bool, forks: bool) -> list[str]:
|
|
426
|
+
return [
|
|
427
|
+
construct_opened_key(repository_id, draft=draft, fork=fork)
|
|
428
|
+
for fork in [False, *([True] if forks else [])]
|
|
429
|
+
for draft in [False, *([True] if drafts else [])]
|
|
430
|
+
]
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def watch_opened(polling: Polling) -> OnScheduleActive:
|
|
434
|
+
async def activate(
|
|
435
|
+
schedule: TriggerSchedule, context: TriggerContext
|
|
436
|
+
) -> TriggerActivation:
|
|
437
|
+
include_drafts = bool(schedule.config.get("includeDrafts", False))
|
|
438
|
+
include_forks = bool(schedule.config.get("includeForks", False))
|
|
439
|
+
repository = await get_repository(
|
|
440
|
+
await context.credentials(polling.provider), schedule.config["repository"]
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
def is_watched(data: GitHubPullRequestData) -> bool:
|
|
444
|
+
return (include_drafts or not data.draft) and (
|
|
445
|
+
include_forks or not data.fork
|
|
446
|
+
)
|
|
447
|
+
|
|
448
|
+
async def poll(watermark: Watermark) -> None:
|
|
449
|
+
since, etag = watermark.current["since"], watermark.current["etag"]
|
|
450
|
+
page = await list_page(
|
|
451
|
+
await context.credentials(polling.provider),
|
|
452
|
+
f"/repos/{repository.full_name}/pulls?state=open&sort=created&direction=desc&per_page={PULL_REQUESTS_PAGE_SIZE}",
|
|
453
|
+
etag,
|
|
454
|
+
GitHubPullRequest,
|
|
455
|
+
)
|
|
456
|
+
if page is None:
|
|
457
|
+
return
|
|
458
|
+
|
|
459
|
+
opened = sorted(
|
|
460
|
+
(
|
|
461
|
+
(
|
|
462
|
+
pull_request.created_at,
|
|
463
|
+
construct_pull_request_data(repository, pull_request),
|
|
464
|
+
)
|
|
465
|
+
for pull_request in page.items
|
|
466
|
+
if is_later(pull_request.created_at, since)
|
|
467
|
+
),
|
|
468
|
+
key=lambda entry: parse_time(entry[0]),
|
|
469
|
+
)
|
|
470
|
+
for created_at, data in opened:
|
|
471
|
+
if is_watched(data):
|
|
472
|
+
await context.fire(construct_opened_event(data))
|
|
473
|
+
await watermark.advance(since=created_at)
|
|
474
|
+
|
|
475
|
+
await watermark.advance(etag=page.etag)
|
|
476
|
+
|
|
477
|
+
stop = await poll_schedule(
|
|
478
|
+
schedule=schedule,
|
|
479
|
+
watermarks=polling.watermarks,
|
|
480
|
+
initial={"since": compute_now(), "etag": None},
|
|
481
|
+
interval_minutes=get_interval(schedule, polling),
|
|
482
|
+
target=f"{repository.full_name} for opened pull requests",
|
|
483
|
+
on_error=polling.on_error,
|
|
484
|
+
poll=poll,
|
|
485
|
+
)
|
|
486
|
+
event_keys = list_opened_keys(
|
|
487
|
+
repository.id, drafts=include_drafts, forks=include_forks
|
|
488
|
+
)
|
|
489
|
+
|
|
490
|
+
return TriggerActivation(event_keys=event_keys, stop=stop)
|
|
491
|
+
|
|
492
|
+
return activate
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def watch_merged(polling: Polling) -> OnScheduleActive:
|
|
496
|
+
async def activate(
|
|
497
|
+
schedule: TriggerSchedule, context: TriggerContext
|
|
498
|
+
) -> TriggerActivation:
|
|
499
|
+
repository = await get_repository(
|
|
500
|
+
await context.credentials(polling.provider), schedule.config["repository"]
|
|
501
|
+
)
|
|
502
|
+
branch = schedule.config.get("branch") or repository.default_branch
|
|
503
|
+
query = urlencode(
|
|
504
|
+
{
|
|
505
|
+
"state": "closed",
|
|
506
|
+
"base": branch,
|
|
507
|
+
"sort": "updated",
|
|
508
|
+
"direction": "desc",
|
|
509
|
+
"per_page": PULL_REQUESTS_PAGE_SIZE,
|
|
510
|
+
}
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
async def poll(watermark: Watermark) -> None:
|
|
514
|
+
since, etag = watermark.current["since"], watermark.current["etag"]
|
|
515
|
+
page = await list_page(
|
|
516
|
+
await context.credentials(polling.provider),
|
|
517
|
+
f"/repos/{repository.full_name}/pulls?{query}",
|
|
518
|
+
etag,
|
|
519
|
+
GitHubPullRequest,
|
|
520
|
+
)
|
|
521
|
+
if page is None:
|
|
522
|
+
return
|
|
523
|
+
|
|
524
|
+
merged = sorted(
|
|
525
|
+
(
|
|
526
|
+
(pull_request.merged_at, pull_request)
|
|
527
|
+
for pull_request in page.items
|
|
528
|
+
if pull_request.merged_at is not None
|
|
529
|
+
and is_later(pull_request.merged_at, since)
|
|
530
|
+
),
|
|
531
|
+
key=lambda entry: parse_time(entry[0]),
|
|
532
|
+
)
|
|
533
|
+
for merged_at, pull_request in merged:
|
|
534
|
+
await context.fire(
|
|
535
|
+
construct_merged_event(repository, pull_request, merged_at)
|
|
536
|
+
)
|
|
537
|
+
await watermark.advance(since=merged_at)
|
|
538
|
+
|
|
539
|
+
await watermark.advance(etag=page.etag)
|
|
540
|
+
|
|
541
|
+
stop = await poll_schedule(
|
|
542
|
+
schedule=schedule,
|
|
543
|
+
watermarks=polling.watermarks,
|
|
544
|
+
initial={"since": compute_now(), "etag": None},
|
|
545
|
+
interval_minutes=get_interval(schedule, polling),
|
|
546
|
+
target=f"{repository.full_name} for pull requests merged into {branch}",
|
|
547
|
+
on_error=polling.on_error,
|
|
548
|
+
poll=poll,
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
return TriggerActivation(
|
|
552
|
+
event_keys=[construct_merged_key(repository.id, branch)], stop=stop
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
return activate
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
async def list_issue_events(
|
|
559
|
+
token: str, repository: str, cursor: int, etag: str | None
|
|
560
|
+
) -> IssueEvents | None:
|
|
561
|
+
"""Lists the issue events newer than `cursor`, oldest first, paging back to it, or only the newest page for a new watch."""
|
|
562
|
+
events: list[GitHubIssueEvent] = []
|
|
563
|
+
first_etag: str | None = None
|
|
564
|
+
|
|
565
|
+
for number in range(1, MAX_ISSUE_EVENT_PAGES + 1):
|
|
566
|
+
answer = await list_page(
|
|
567
|
+
token,
|
|
568
|
+
f"/repos/{repository}/issues/events?per_page={ISSUE_EVENTS_PAGE_SIZE}&page={number}",
|
|
569
|
+
etag if number == 1 else None,
|
|
570
|
+
GitHubIssueEvent,
|
|
571
|
+
)
|
|
572
|
+
if answer is None:
|
|
573
|
+
return None
|
|
574
|
+
|
|
575
|
+
if number == 1:
|
|
576
|
+
first_etag = answer.etag
|
|
577
|
+
|
|
578
|
+
events.extend(answer.items)
|
|
579
|
+
is_last_page = len(answer.items) < ISSUE_EVENTS_PAGE_SIZE
|
|
580
|
+
reached_cursor = any(item.id <= cursor for item in answer.items)
|
|
581
|
+
if cursor == 0 or is_last_page or reached_cursor:
|
|
582
|
+
break
|
|
583
|
+
|
|
584
|
+
newer = sorted(
|
|
585
|
+
(event for event in events if event.id > cursor), key=lambda event: event.id
|
|
586
|
+
)
|
|
587
|
+
|
|
588
|
+
return IssueEvents(etag=first_etag, events=newer)
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def watch_assigned(polling: Polling) -> OnScheduleActive:
|
|
592
|
+
async def activate(
|
|
593
|
+
schedule: TriggerSchedule, context: TriggerContext
|
|
594
|
+
) -> TriggerActivation:
|
|
595
|
+
config = schedule.config
|
|
596
|
+
if config.get("assignee") is None and config.get("label") is None:
|
|
597
|
+
raise AgentJamError(
|
|
598
|
+
"An issue_assigned schedule needs an assignee, a label or both to watch for"
|
|
599
|
+
)
|
|
600
|
+
|
|
601
|
+
repository = await get_repository(
|
|
602
|
+
await context.credentials(polling.provider), config["repository"]
|
|
603
|
+
)
|
|
604
|
+
|
|
605
|
+
async def poll(watermark: Watermark) -> None:
|
|
606
|
+
since, cursor = watermark.current["since"], watermark.current["cursor"]
|
|
607
|
+
listed = await list_issue_events(
|
|
608
|
+
await context.credentials(polling.provider),
|
|
609
|
+
repository.full_name,
|
|
610
|
+
cursor,
|
|
611
|
+
watermark.current["etag"],
|
|
612
|
+
)
|
|
613
|
+
if listed is None:
|
|
614
|
+
return
|
|
615
|
+
|
|
616
|
+
for issue_event in listed.events:
|
|
617
|
+
assignment = (
|
|
618
|
+
read_assignment(repository, issue_event, config)
|
|
619
|
+
if is_later(issue_event.created_at, since)
|
|
620
|
+
else None
|
|
621
|
+
)
|
|
622
|
+
if assignment is None:
|
|
623
|
+
continue
|
|
624
|
+
|
|
625
|
+
await context.fire(assignment)
|
|
626
|
+
await watermark.advance(cursor=issue_event.id)
|
|
627
|
+
|
|
628
|
+
newest = listed.events[-1].id if listed.events else cursor
|
|
629
|
+
await watermark.advance(cursor=newest, etag=listed.etag)
|
|
630
|
+
|
|
631
|
+
stop = await poll_schedule(
|
|
632
|
+
schedule=schedule,
|
|
633
|
+
watermarks=polling.watermarks,
|
|
634
|
+
initial={"since": compute_now(), "etag": None, "cursor": 0},
|
|
635
|
+
interval_minutes=get_interval(schedule, polling),
|
|
636
|
+
target=f"{repository.full_name} for assigned issues",
|
|
637
|
+
on_error=polling.on_error,
|
|
638
|
+
poll=poll,
|
|
639
|
+
)
|
|
640
|
+
|
|
641
|
+
return TriggerActivation(stop=stop)
|
|
642
|
+
|
|
643
|
+
return activate
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def github_triggers(
|
|
647
|
+
*,
|
|
648
|
+
provider: str = "github",
|
|
649
|
+
watermarks: WatermarkStore | None = None,
|
|
650
|
+
poll_interval_minutes: float = 2,
|
|
651
|
+
on_error: Callable[[Exception], None] = log_error,
|
|
652
|
+
) -> dict[str, Trigger]:
|
|
653
|
+
"""Triggers that run a schedule on a GitHub repository's activity, for a skill with the GitHub connection `provider` names.
|
|
654
|
+
|
|
655
|
+
Each polls with the schedule's token from where `watermarks` says it left off, and the pull request triggers also
|
|
656
|
+
subscribe to the keys `github_webhooks()` reads deliveries under, which only make runs sooner.
|
|
657
|
+
|
|
658
|
+
Args:
|
|
659
|
+
provider: The provider of the skill's GitHub connection, such as `github-app` for a GitHub App.
|
|
660
|
+
watermarks: Where polls keep each schedule's progress. Defaults to a `MemoryWatermarkStore`, which forgets it on exit.
|
|
661
|
+
poll_interval_minutes: How often a schedule that doesn't set `pollIntervalMinutes` polls GitHub.
|
|
662
|
+
on_error: Handles a failed poll, which is tried again at the next interval. Defaults to logging it.
|
|
663
|
+
|
|
664
|
+
Returns:
|
|
665
|
+
The `pull_request_opened`, `pull_request_merged` and `issue_assigned` triggers, for a skill's `triggers`.
|
|
666
|
+
"""
|
|
667
|
+
polling = Polling(
|
|
668
|
+
provider=provider,
|
|
669
|
+
watermarks=watermarks if watermarks is not None else MemoryWatermarkStore(),
|
|
670
|
+
poll_interval_minutes=poll_interval_minutes,
|
|
671
|
+
on_error=on_error,
|
|
672
|
+
)
|
|
673
|
+
|
|
674
|
+
return {
|
|
675
|
+
"pull_request_opened": Trigger(
|
|
676
|
+
description="A pull request is opened in a GitHub repository, or a draft is marked ready for review",
|
|
677
|
+
config={
|
|
678
|
+
"type": "object",
|
|
679
|
+
"properties": {
|
|
680
|
+
"repository": REPOSITORY_PROPERTY,
|
|
681
|
+
"includeDrafts": {
|
|
682
|
+
"type": "boolean",
|
|
683
|
+
"description": "Whether to run when a draft is opened, rather than once it's marked ready for review",
|
|
684
|
+
},
|
|
685
|
+
"includeForks": {
|
|
686
|
+
"type": "boolean",
|
|
687
|
+
"description": "Whether to also run on pull requests from forks",
|
|
688
|
+
},
|
|
689
|
+
"pollIntervalMinutes": construct_interval_property(
|
|
690
|
+
"opened pull requests a webhook missed"
|
|
691
|
+
),
|
|
692
|
+
},
|
|
693
|
+
"required": ["repository"],
|
|
694
|
+
},
|
|
695
|
+
on_schedule_active=watch_opened(polling),
|
|
696
|
+
),
|
|
697
|
+
"pull_request_merged": Trigger(
|
|
698
|
+
description="A pull request is merged into a GitHub repository's default branch, or into another branch",
|
|
699
|
+
config={
|
|
700
|
+
"type": "object",
|
|
701
|
+
"properties": {
|
|
702
|
+
"repository": REPOSITORY_PROPERTY,
|
|
703
|
+
"branch": {
|
|
704
|
+
"type": "string",
|
|
705
|
+
"minLength": 1,
|
|
706
|
+
"maxLength": 200,
|
|
707
|
+
"description": "The branch to watch merges into. Defaults to the repository's default branch",
|
|
708
|
+
},
|
|
709
|
+
"pollIntervalMinutes": construct_interval_property(
|
|
710
|
+
"merged pull requests a webhook missed"
|
|
711
|
+
),
|
|
712
|
+
},
|
|
713
|
+
"required": ["repository"],
|
|
714
|
+
},
|
|
715
|
+
on_schedule_active=watch_merged(polling),
|
|
716
|
+
),
|
|
717
|
+
"issue_assigned": Trigger(
|
|
718
|
+
description="An issue in a GitHub repository is assigned to a user or labeled with a label",
|
|
719
|
+
config={
|
|
720
|
+
"type": "object",
|
|
721
|
+
"properties": {
|
|
722
|
+
"repository": REPOSITORY_PROPERTY,
|
|
723
|
+
"assignee": {
|
|
724
|
+
"type": "string",
|
|
725
|
+
"minLength": 1,
|
|
726
|
+
"description": "Runs when an issue is assigned to this GitHub user, such as a bot account",
|
|
727
|
+
},
|
|
728
|
+
"label": {
|
|
729
|
+
"type": "string",
|
|
730
|
+
"minLength": 1,
|
|
731
|
+
"description": "Runs when this label is added to an issue",
|
|
732
|
+
},
|
|
733
|
+
"pollIntervalMinutes": construct_interval_property(
|
|
734
|
+
"assigned issues"
|
|
735
|
+
),
|
|
736
|
+
},
|
|
737
|
+
"required": ["repository"],
|
|
738
|
+
"anyOf": [{"required": ["assignee"]}, {"required": ["label"]}],
|
|
739
|
+
},
|
|
740
|
+
on_schedule_active=watch_assigned(polling),
|
|
741
|
+
),
|
|
742
|
+
}
|