managed-deepagents 0.9.1.dev2__py3-none-win_amd64.whl → 0.9.1.dev4__py3-none-win_amd64.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.
- managed_deepagents/__init__.py +22 -0
- managed_deepagents/_binaries/mda.exe +0 -0
- managed_deepagents/_channels/github.py +280 -0
- managed_deepagents/_channels/github_events.py +28 -0
- managed_deepagents/_channels/github_schema.py +201 -0
- managed_deepagents/_channels/github_types.py +123 -0
- managed_deepagents/_channels/http/__init__.py +5 -1
- managed_deepagents/_channels/http/http.py +6 -0
- managed_deepagents/_connections.py +22 -0
- managed_deepagents/_sandbox_proxy.py +0 -13
- managed_deepagents/namespaces.py +2 -0
- managed_deepagents/runtime.py +328 -161
- {managed_deepagents-0.9.1.dev2.dist-info → managed_deepagents-0.9.1.dev4.dist-info}/METADATA +110 -1
- {managed_deepagents-0.9.1.dev2.dist-info → managed_deepagents-0.9.1.dev4.dist-info}/RECORD +18 -14
- {managed_deepagents-0.9.1.dev2.dist-info → managed_deepagents-0.9.1.dev4.dist-info}/WHEEL +0 -0
- {managed_deepagents-0.9.1.dev2.dist-info → managed_deepagents-0.9.1.dev4.dist-info}/entry_points.txt +0 -0
- {managed_deepagents-0.9.1.dev2.dist-info → managed_deepagents-0.9.1.dev4.dist-info}/licenses/LICENSE +0 -0
- {managed_deepagents-0.9.1.dev2.dist-info → managed_deepagents-0.9.1.dev4.dist-info}/top_level.txt +0 -0
managed_deepagents/__init__.py
CHANGED
|
@@ -15,6 +15,18 @@ primitive is not part of the public surface.
|
|
|
15
15
|
|
|
16
16
|
from __future__ import annotations
|
|
17
17
|
|
|
18
|
+
from managed_deepagents._channels.github_types import (
|
|
19
|
+
GitHubAppOptions,
|
|
20
|
+
GitHubChannelRuntime,
|
|
21
|
+
GitHubEvent,
|
|
22
|
+
GitHubEventCallback,
|
|
23
|
+
GitHubHandlers,
|
|
24
|
+
GitHubLabeledIssuePayload,
|
|
25
|
+
GitHubPayload,
|
|
26
|
+
GitHubPullRequestPayload,
|
|
27
|
+
GitHubWorkflowPayload,
|
|
28
|
+
SupportedEventKey,
|
|
29
|
+
)
|
|
18
30
|
from managed_deepagents._channels.http import (
|
|
19
31
|
HttpChannel,
|
|
20
32
|
HttpChannelInboundMessage,
|
|
@@ -106,6 +118,15 @@ __all__ = [
|
|
|
106
118
|
"CredentialStoreError",
|
|
107
119
|
"DeepAgentDefinition",
|
|
108
120
|
"GeneratedSkill",
|
|
121
|
+
"GitHubAppOptions",
|
|
122
|
+
"GitHubChannelRuntime",
|
|
123
|
+
"GitHubEvent",
|
|
124
|
+
"GitHubEventCallback",
|
|
125
|
+
"GitHubHandlers",
|
|
126
|
+
"GitHubLabeledIssuePayload",
|
|
127
|
+
"GitHubPayload",
|
|
128
|
+
"GitHubPullRequestPayload",
|
|
129
|
+
"GitHubWorkflowPayload",
|
|
109
130
|
"HttpChannel",
|
|
110
131
|
"HttpChannelInboundMessage",
|
|
111
132
|
"HttpChannelParseResult",
|
|
@@ -142,6 +163,7 @@ __all__ = [
|
|
|
142
163
|
"SkillSelection",
|
|
143
164
|
"SlackPromptResponse",
|
|
144
165
|
"SseMcpServerConfig",
|
|
166
|
+
"SupportedEventKey",
|
|
145
167
|
"auth",
|
|
146
168
|
"basic",
|
|
147
169
|
"bearer",
|
|
Binary file
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import hmac
|
|
5
|
+
import inspect
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import time
|
|
10
|
+
import uuid
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from dataclasses import asdict
|
|
13
|
+
from importlib import import_module
|
|
14
|
+
from typing import TYPE_CHECKING, cast
|
|
15
|
+
|
|
16
|
+
from managed_deepagents._channels.github_events import github_event
|
|
17
|
+
from managed_deepagents._channels.github_schema import (
|
|
18
|
+
SUPPORTED_EVENT_KEYS,
|
|
19
|
+
github_identifier_adapter,
|
|
20
|
+
github_receipt_adapter,
|
|
21
|
+
)
|
|
22
|
+
from managed_deepagents._channels.github_types import (
|
|
23
|
+
GitHubAppOptions,
|
|
24
|
+
GitHubChannelRuntime,
|
|
25
|
+
GitHubEventCallback,
|
|
26
|
+
GitHubHandlers,
|
|
27
|
+
SupportedEventKey,
|
|
28
|
+
_ChannelName,
|
|
29
|
+
)
|
|
30
|
+
from managed_deepagents._channels.http import HttpChannel, http_channel
|
|
31
|
+
from managed_deepagents._channels.runtime import is_json_value
|
|
32
|
+
from managed_deepagents._log import logger
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from managed_deepagents._channels.http.types import (
|
|
36
|
+
HttpChannelParseResult,
|
|
37
|
+
HttpChannelRequest,
|
|
38
|
+
JsonValue,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
_MAX_SAFE_INTEGER = 9007199254740991
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def github_channel(
|
|
45
|
+
*, on: GitHubHandlers | None = None, app: GitHubAppOptions | None = None
|
|
46
|
+
) -> HttpChannel:
|
|
47
|
+
"""Verified GitHub receipts; string callback results start fresh runs, None skips."""
|
|
48
|
+
handlers = cast("Mapping[SupportedEventKey, GitHubEventCallback]", dict(on or {}))
|
|
49
|
+
if set(handlers) - SUPPORTED_EVENT_KEYS:
|
|
50
|
+
raise ValueError("unsupported GitHub event key")
|
|
51
|
+
unsupported = sorted(set(app or {}) - {"permissions", "repositories"})
|
|
52
|
+
if unsupported:
|
|
53
|
+
raise ValueError(
|
|
54
|
+
f"{', '.join(unsupported)}: GitHub app takes only permissions and repositories. "
|
|
55
|
+
"The App is named after the agent; GitHub does not let deploy change its name, "
|
|
56
|
+
"owner or description later, so set those on GitHub."
|
|
57
|
+
)
|
|
58
|
+
# GitHub names are case-insensitive; deploy validates the rest.
|
|
59
|
+
repositories = (
|
|
60
|
+
None
|
|
61
|
+
if app is None or "repositories" not in app
|
|
62
|
+
else frozenset(repository.strip().lower() for repository in app["repositories"])
|
|
63
|
+
)
|
|
64
|
+
if repositories is not None and not repositories:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
"GitHub app.repositories must list at least one repository; "
|
|
67
|
+
"omit it to allow every repository"
|
|
68
|
+
)
|
|
69
|
+
provider_config: dict[str, JsonValue] = {"events": sorted(handlers)}
|
|
70
|
+
if app is not None:
|
|
71
|
+
provider_config["app"] = _app_config(app)
|
|
72
|
+
|
|
73
|
+
async def parse(ctx: HttpChannelRequest) -> HttpChannelParseResult:
|
|
74
|
+
return await _parse(ctx, handlers, channel.name or channel.kind, repositories)
|
|
75
|
+
|
|
76
|
+
channel = http_channel(
|
|
77
|
+
provider="github", verify=_verify, parse=parse, provider_config=provider_config
|
|
78
|
+
)
|
|
79
|
+
return channel
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _app_config(app: GitHubAppOptions) -> dict[str, JsonValue]:
|
|
83
|
+
"""The App options deploy reads, without unset fields."""
|
|
84
|
+
config: dict[str, JsonValue] = {}
|
|
85
|
+
if "permissions" in app:
|
|
86
|
+
config["permissions"] = dict(app["permissions"])
|
|
87
|
+
if "repositories" in app:
|
|
88
|
+
config["repositories"] = list(app["repositories"])
|
|
89
|
+
return config
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# How long a value read from Agent Auth is reused before it is read again.
|
|
93
|
+
_APP_VALUE_TTL_SECONDS = 300.0
|
|
94
|
+
# How long a missing value is remembered, so unsigned traffic cannot hammer Agent Auth.
|
|
95
|
+
_MISSING_APP_VALUE_TTL_SECONDS = 60.0
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class _AppValue:
|
|
99
|
+
__slots__ = ("expires_at", "value")
|
|
100
|
+
|
|
101
|
+
def __init__(self, value: asyncio.Future[str | None], expires_at: float) -> None:
|
|
102
|
+
self.value = value
|
|
103
|
+
self.expires_at = expires_at
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
_app_values: dict[str, _AppValue] = {}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def _github_app_value(env_key: str, suffix: str) -> str | None:
|
|
110
|
+
"""The App's webhook secret or bot ID.
|
|
111
|
+
|
|
112
|
+
The ``GH_*`` env override wins; otherwise the agent secret Agent Auth stored
|
|
113
|
+
when ``mda deploy`` created the App, at ``mda/github-app/{deployment}/{suffix}``.
|
|
114
|
+
Only a missing connection reads as ``None``; credential store failures propagate.
|
|
115
|
+
"""
|
|
116
|
+
from managed_deepagents._connections import ( # noqa: PLC0415
|
|
117
|
+
DEPLOYMENT_ID_ENV,
|
|
118
|
+
github_app_connection_slug,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
override = os.environ.get(env_key, "").strip()
|
|
122
|
+
if override:
|
|
123
|
+
return override
|
|
124
|
+
deployment_id = os.environ.get(DEPLOYMENT_ID_ENV, "").strip()
|
|
125
|
+
if not deployment_id:
|
|
126
|
+
return None
|
|
127
|
+
slug = github_app_connection_slug(deployment_id, suffix)
|
|
128
|
+
entry = _app_values.get(slug)
|
|
129
|
+
if entry is None or entry.expires_at <= time.monotonic():
|
|
130
|
+
# Concurrent deliveries share the in-flight read.
|
|
131
|
+
entry = _AppValue(
|
|
132
|
+
asyncio.ensure_future(_read_app_value(slug, suffix)),
|
|
133
|
+
time.monotonic() + _APP_VALUE_TTL_SECONDS,
|
|
134
|
+
)
|
|
135
|
+
_app_values[slug] = entry
|
|
136
|
+
try:
|
|
137
|
+
# Shielded so one cancelled delivery does not cancel the shared read.
|
|
138
|
+
value = await asyncio.shield(entry.value)
|
|
139
|
+
except Exception:
|
|
140
|
+
# Read again on the next delivery rather than caching a failure.
|
|
141
|
+
if _app_values.get(slug) is entry:
|
|
142
|
+
del _app_values[slug]
|
|
143
|
+
raise
|
|
144
|
+
if value is None:
|
|
145
|
+
entry.expires_at = min(entry.expires_at, time.monotonic() + _MISSING_APP_VALUE_TTL_SECONDS)
|
|
146
|
+
return value
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
async def _read_app_value(slug: str, suffix: str) -> str | None:
|
|
150
|
+
from managed_deepagents._connections import ( # noqa: PLC0415
|
|
151
|
+
ConnectionNotFoundError,
|
|
152
|
+
connections,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
try:
|
|
156
|
+
return await connections.resolve_deployment_secret(slug)
|
|
157
|
+
except ConnectionNotFoundError:
|
|
158
|
+
logger.error("GitHub App %s is not stored in Agent Auth", suffix)
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def reset_github_app_values() -> None:
|
|
163
|
+
"""Forget values read from Agent Auth; for tests."""
|
|
164
|
+
_app_values.clear()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
async def _verify(ctx: HttpChannelRequest) -> bool:
|
|
168
|
+
# Reject unsigned deliveries before reading the secret from Agent Auth.
|
|
169
|
+
signature = ctx.request.headers.get("x-hub-signature-256", "")
|
|
170
|
+
if re.fullmatch(r"sha256=[a-fA-F0-9]{64}", signature) is None:
|
|
171
|
+
return False
|
|
172
|
+
secret = await _github_app_value("GH_WEBHOOK_SECRET", "webhook-secret")
|
|
173
|
+
if not secret:
|
|
174
|
+
return False
|
|
175
|
+
expected = hmac.digest(secret.encode(), ctx.raw_body, "sha256")
|
|
176
|
+
return hmac.compare_digest(expected, bytes.fromhex(signature[7:]))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
async def _parse( # noqa: PLR0911 - each filter short-circuits
|
|
180
|
+
ctx: HttpChannelRequest,
|
|
181
|
+
handlers: Mapping[SupportedEventKey, GitHubEventCallback],
|
|
182
|
+
channel_name: str,
|
|
183
|
+
repositories: frozenset[str] | None,
|
|
184
|
+
) -> HttpChannelParseResult:
|
|
185
|
+
json_response = import_module("starlette.responses").JSONResponse
|
|
186
|
+
|
|
187
|
+
envelope = github_receipt_adapter.validate_python(
|
|
188
|
+
{
|
|
189
|
+
"event": ctx.request.headers.get("x-github-event"),
|
|
190
|
+
"delivery_id": ctx.request.headers.get("x-github-delivery"),
|
|
191
|
+
"payload": await ctx.request.json(),
|
|
192
|
+
},
|
|
193
|
+
strict=True,
|
|
194
|
+
)
|
|
195
|
+
event = envelope["event"]
|
|
196
|
+
record = envelope["payload"]
|
|
197
|
+
receipt = _receipt(record, event, envelope["delivery_id"])
|
|
198
|
+
response = json_response({"status": "received"}, status_code=200 if event == "ping" else 202)
|
|
199
|
+
|
|
200
|
+
# Unhandled events stop before callback execution or run creation.
|
|
201
|
+
key = cast("SupportedEventKey", f"{event}.{record.get('action')}")
|
|
202
|
+
handler = handlers.get(key)
|
|
203
|
+
if handler is None:
|
|
204
|
+
return {"type": "ignore", "response": response}
|
|
205
|
+
|
|
206
|
+
parsed_event = github_event(key, record, envelope["delivery_id"])
|
|
207
|
+
|
|
208
|
+
# Events from repositories the channel is not limited to start nothing.
|
|
209
|
+
if repositories is not None and parsed_event.repository.full_name.lower() not in repositories:
|
|
210
|
+
return {"type": "ignore", "response": response}
|
|
211
|
+
|
|
212
|
+
# Ignore the App's own activity to avoid triggering ourselves.
|
|
213
|
+
configured_bot_id = await _github_app_value("GH_APP_BOT_ID", "bot-id") or ""
|
|
214
|
+
if not re.fullmatch(r"[1-9][0-9]*", configured_bot_id):
|
|
215
|
+
raise TypeError(
|
|
216
|
+
"GitHub App bot ID is unavailable; run `mda deploy` to store it or set GH_APP_BOT_ID"
|
|
217
|
+
)
|
|
218
|
+
bot_id = github_identifier_adapter.validate_python(int(configured_bot_id), strict=True)
|
|
219
|
+
if parsed_event.sender.id == bot_id:
|
|
220
|
+
return {"type": "ignore", "response": response}
|
|
221
|
+
|
|
222
|
+
# Preserve the original event even if the callback modifies its argument.
|
|
223
|
+
event_snapshot = asdict(parsed_event)
|
|
224
|
+
if not is_json_value(event_snapshot):
|
|
225
|
+
raise TypeError("invalid GitHub event")
|
|
226
|
+
|
|
227
|
+
try:
|
|
228
|
+
result = handler(
|
|
229
|
+
parsed_event, GitHubChannelRuntime(channel=_ChannelName(name=channel_name))
|
|
230
|
+
)
|
|
231
|
+
content = await result if inspect.isawaitable(result) else result
|
|
232
|
+
except Exception as error: # noqa: BLE001
|
|
233
|
+
logger.error(
|
|
234
|
+
"github callback failed %s (%s)",
|
|
235
|
+
json.dumps(receipt),
|
|
236
|
+
logger.safe_error_label(error),
|
|
237
|
+
)
|
|
238
|
+
return {"type": "ignore", "response": response}
|
|
239
|
+
|
|
240
|
+
if content is None:
|
|
241
|
+
return {"type": "ignore", "response": response}
|
|
242
|
+
if not isinstance(content, str) or not content.strip():
|
|
243
|
+
logger.error("github callback returned invalid input %s", json.dumps(receipt))
|
|
244
|
+
return {"type": "ignore", "response": response}
|
|
245
|
+
|
|
246
|
+
# HTTP owns run creation; the adapter supplies a fresh message/thread.
|
|
247
|
+
thread_id = str(uuid.uuid4())
|
|
248
|
+
logger.info(
|
|
249
|
+
"GitHub handler returned run input %s",
|
|
250
|
+
json.dumps({"deliveryId": receipt["deliveryId"], "threadId": thread_id}),
|
|
251
|
+
)
|
|
252
|
+
return {
|
|
253
|
+
"type": "message",
|
|
254
|
+
"message": {
|
|
255
|
+
"content": content,
|
|
256
|
+
"thread_id": thread_id,
|
|
257
|
+
"user_id": "mda:channel",
|
|
258
|
+
"target": None,
|
|
259
|
+
},
|
|
260
|
+
"raw_event": event_snapshot,
|
|
261
|
+
"response": response,
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _receipt(record: Mapping[str, object], event: str, delivery_id: str) -> dict[str, str | int]:
|
|
266
|
+
receipt: dict[str, str | int] = {
|
|
267
|
+
"event": logger.log_identifier(event),
|
|
268
|
+
"deliveryId": logger.log_identifier(delivery_id),
|
|
269
|
+
}
|
|
270
|
+
action = record.get("action")
|
|
271
|
+
if isinstance(action, str):
|
|
272
|
+
receipt["action"] = logger.log_identifier(action)
|
|
273
|
+
for key, field in (("repository", "id"), ("issue", "number"), ("pull_request", "number")):
|
|
274
|
+
value = record.get(key)
|
|
275
|
+
if isinstance(value, dict):
|
|
276
|
+
receipt_id = value.get(field)
|
|
277
|
+
if type(receipt_id) is int and abs(receipt_id) <= _MAX_SAFE_INTEGER:
|
|
278
|
+
receipt[key] = receipt_id
|
|
279
|
+
logger.info("github receipt %s", json.dumps(receipt))
|
|
280
|
+
return receipt
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Normalize validated dispatch events into the callback attribute interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from managed_deepagents._channels.github_schema import SupportedEventKey, validate_payload
|
|
6
|
+
from managed_deepagents._channels.github_types import GitHubEvent, GitHubRepository, GitHubSender
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def github_event(key: SupportedEventKey, payload: object, delivery_id: str) -> GitHubEvent:
|
|
10
|
+
validated = validate_payload(key, payload)
|
|
11
|
+
repository = validated["repository"]
|
|
12
|
+
sender = validated["sender"]
|
|
13
|
+
return GitHubEvent(
|
|
14
|
+
key=key,
|
|
15
|
+
name=key.split(".")[0],
|
|
16
|
+
action=validated["action"],
|
|
17
|
+
delivery_id=delivery_id,
|
|
18
|
+
installation_id=validated["installation"]["id"],
|
|
19
|
+
repository=GitHubRepository(
|
|
20
|
+
id=repository["id"],
|
|
21
|
+
owner=repository["owner"]["login"],
|
|
22
|
+
name=repository["name"],
|
|
23
|
+
full_name=repository["full_name"],
|
|
24
|
+
private=repository["private"],
|
|
25
|
+
),
|
|
26
|
+
sender=GitHubSender(id=sender["id"], login=sender["login"], type=sender["type"]),
|
|
27
|
+
payload=validated,
|
|
28
|
+
)
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Separate receipt and dispatch schemas for handwritten GitHub payload subsets."""
|
|
2
|
+
|
|
3
|
+
from typing import Annotated, Literal, NotRequired
|
|
4
|
+
|
|
5
|
+
from pydantic import AfterValidator, ConfigDict, Field, TypeAdapter, with_config
|
|
6
|
+
from typing_extensions import TypedDict
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _nonblank(value: str) -> str:
|
|
10
|
+
if not value.strip():
|
|
11
|
+
raise ValueError("must be nonblank")
|
|
12
|
+
return value
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
_Nonblank = Annotated[str, AfterValidator(_nonblank)]
|
|
16
|
+
_SafeInteger = Annotated[int, Field(ge=-9007199254740991, le=9007199254740991)]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
20
|
+
class _Repository(TypedDict):
|
|
21
|
+
id: NotRequired[_SafeInteger]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
25
|
+
class _Subject(TypedDict):
|
|
26
|
+
number: NotRequired[_SafeInteger]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
30
|
+
class _Payload(TypedDict):
|
|
31
|
+
action: NotRequired[str]
|
|
32
|
+
repository: NotRequired[_Repository]
|
|
33
|
+
issue: NotRequired[_Subject]
|
|
34
|
+
pull_request: NotRequired[_Subject]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class GitHubReceipt(TypedDict):
|
|
38
|
+
event: _Nonblank
|
|
39
|
+
delivery_id: _Nonblank
|
|
40
|
+
payload: _Payload
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
github_receipt_adapter = TypeAdapter(GitHubReceipt)
|
|
44
|
+
|
|
45
|
+
# Dispatch schemas are stronger than receipt schemas, and are used only when a
|
|
46
|
+
# matching callback is registered. Preserve unknown provider fields at every level.
|
|
47
|
+
_PositiveId = Annotated[_SafeInteger, Field(gt=0)]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
51
|
+
class GitHubIssue(TypedDict):
|
|
52
|
+
number: _PositiveId
|
|
53
|
+
title: _Nonblank
|
|
54
|
+
body: str | None
|
|
55
|
+
pull_request: NotRequired[dict[str, object]]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class GitHubPullRequest(GitHubIssue):
|
|
59
|
+
draft: NotRequired[bool]
|
|
60
|
+
merged: NotRequired[bool]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
64
|
+
class GitHubComment(TypedDict):
|
|
65
|
+
id: _PositiveId
|
|
66
|
+
body: str
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
70
|
+
class GitHubLabel(TypedDict):
|
|
71
|
+
name: _Nonblank
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
75
|
+
class GitHubReview(TypedDict):
|
|
76
|
+
id: _PositiveId
|
|
77
|
+
body: str | None
|
|
78
|
+
state: _Nonblank
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
82
|
+
class GitHubWorkflowRun(TypedDict):
|
|
83
|
+
id: _PositiveId
|
|
84
|
+
conclusion: str | None
|
|
85
|
+
pull_requests: list[dict[str, object]]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
89
|
+
class _Owner(TypedDict):
|
|
90
|
+
login: _Nonblank
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
94
|
+
class _DispatchRepository(TypedDict):
|
|
95
|
+
id: _PositiveId
|
|
96
|
+
owner: _Owner
|
|
97
|
+
name: _Nonblank
|
|
98
|
+
full_name: _Nonblank
|
|
99
|
+
private: bool
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
103
|
+
class _Sender(TypedDict):
|
|
104
|
+
id: _PositiveId
|
|
105
|
+
login: _Nonblank
|
|
106
|
+
type: Literal["User", "Bot", "Organization"]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
110
|
+
class _Installation(TypedDict):
|
|
111
|
+
id: _PositiveId
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@with_config(ConfigDict(extra="allow", strict=True))
|
|
115
|
+
class _DispatchPayload(TypedDict):
|
|
116
|
+
action: _Nonblank
|
|
117
|
+
repository: _DispatchRepository
|
|
118
|
+
sender: _Sender
|
|
119
|
+
installation: _Installation
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class _IssuePayload(_DispatchPayload):
|
|
123
|
+
issue: GitHubIssue
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class _LabeledIssuePayload(_IssuePayload):
|
|
127
|
+
label: GitHubLabel
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class _IssueCommentPayload(_IssuePayload):
|
|
131
|
+
comment: GitHubComment
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class _PullRequestPayload(_DispatchPayload):
|
|
135
|
+
pull_request: GitHubPullRequest
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class _LabeledPullRequestPayload(_PullRequestPayload):
|
|
139
|
+
label: GitHubLabel
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class _ReviewPayload(_PullRequestPayload):
|
|
143
|
+
review: GitHubReview
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class _ReviewCommentPayload(_PullRequestPayload):
|
|
147
|
+
comment: GitHubComment
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class _WorkflowPayload(_DispatchPayload):
|
|
151
|
+
workflow_run: GitHubWorkflowRun
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
GitHubPayload = (
|
|
155
|
+
_IssuePayload
|
|
156
|
+
| _LabeledIssuePayload
|
|
157
|
+
| _IssueCommentPayload
|
|
158
|
+
| _PullRequestPayload
|
|
159
|
+
| _LabeledPullRequestPayload
|
|
160
|
+
| _ReviewPayload
|
|
161
|
+
| _ReviewCommentPayload
|
|
162
|
+
| _WorkflowPayload
|
|
163
|
+
)
|
|
164
|
+
SupportedEventKey = Literal[
|
|
165
|
+
"issues.opened",
|
|
166
|
+
"issues.labeled",
|
|
167
|
+
"issue_comment.created",
|
|
168
|
+
"pull_request.opened",
|
|
169
|
+
"pull_request.ready_for_review",
|
|
170
|
+
"pull_request.synchronize",
|
|
171
|
+
"pull_request.labeled",
|
|
172
|
+
"pull_request.closed",
|
|
173
|
+
"pull_request_review.submitted",
|
|
174
|
+
"pull_request_review_comment.created",
|
|
175
|
+
"workflow_run.completed",
|
|
176
|
+
]
|
|
177
|
+
|
|
178
|
+
# Several event actions share a payload shape; routing chooses the validator.
|
|
179
|
+
_pr_adapter: TypeAdapter[GitHubPayload] = TypeAdapter(_PullRequestPayload)
|
|
180
|
+
_PAYLOAD_ADAPTERS: dict[SupportedEventKey, TypeAdapter[GitHubPayload]] = {
|
|
181
|
+
"issues.opened": TypeAdapter(_IssuePayload),
|
|
182
|
+
"issues.labeled": TypeAdapter(_LabeledIssuePayload),
|
|
183
|
+
"issue_comment.created": TypeAdapter(_IssueCommentPayload),
|
|
184
|
+
"pull_request.opened": _pr_adapter,
|
|
185
|
+
"pull_request.ready_for_review": _pr_adapter,
|
|
186
|
+
"pull_request.synchronize": _pr_adapter,
|
|
187
|
+
"pull_request.labeled": TypeAdapter(_LabeledPullRequestPayload),
|
|
188
|
+
"pull_request.closed": _pr_adapter,
|
|
189
|
+
"pull_request_review.submitted": TypeAdapter(_ReviewPayload),
|
|
190
|
+
"pull_request_review_comment.created": TypeAdapter(_ReviewCommentPayload),
|
|
191
|
+
"workflow_run.completed": TypeAdapter(_WorkflowPayload),
|
|
192
|
+
}
|
|
193
|
+
github_identifier_adapter = TypeAdapter(_PositiveId)
|
|
194
|
+
SUPPORTED_EVENT_KEYS = frozenset(_PAYLOAD_ADAPTERS)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def validate_payload(key: SupportedEventKey, payload: object) -> GitHubPayload:
|
|
198
|
+
validated = _PAYLOAD_ADAPTERS[key].validate_python(payload, strict=True)
|
|
199
|
+
if validated["action"] != key.split(".", 1)[1]:
|
|
200
|
+
raise ValueError("GitHub action does not match event key")
|
|
201
|
+
return validated
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Handwritten webhook subsets; other provider fields remain in the original payload."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Generic, Literal
|
|
8
|
+
|
|
9
|
+
from typing_extensions import TypedDict, TypeVar
|
|
10
|
+
|
|
11
|
+
from managed_deepagents._channels.github_schema import (
|
|
12
|
+
GitHubPayload,
|
|
13
|
+
SupportedEventKey,
|
|
14
|
+
_IssueCommentPayload,
|
|
15
|
+
_IssuePayload,
|
|
16
|
+
_LabeledIssuePayload,
|
|
17
|
+
_LabeledPullRequestPayload,
|
|
18
|
+
_PullRequestPayload,
|
|
19
|
+
_ReviewCommentPayload,
|
|
20
|
+
_ReviewPayload,
|
|
21
|
+
_WorkflowPayload,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
_Payload = TypeVar("_Payload", bound=GitHubPayload, default=GitHubPayload)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class GitHubRepository:
|
|
29
|
+
id: int
|
|
30
|
+
owner: str
|
|
31
|
+
name: str
|
|
32
|
+
full_name: str
|
|
33
|
+
private: bool
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class GitHubSender:
|
|
38
|
+
id: int
|
|
39
|
+
login: str
|
|
40
|
+
type: Literal["User", "Bot", "Organization"]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class GitHubEvent(Generic[_Payload]):
|
|
45
|
+
key: SupportedEventKey
|
|
46
|
+
name: str
|
|
47
|
+
action: str
|
|
48
|
+
delivery_id: str
|
|
49
|
+
installation_id: int
|
|
50
|
+
repository: GitHubRepository
|
|
51
|
+
sender: GitHubSender
|
|
52
|
+
payload: _Payload
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class _ChannelName:
|
|
57
|
+
name: str
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class GitHubChannelRuntime:
|
|
62
|
+
channel: _ChannelName
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class GitHubAppOptions(TypedDict, total=False):
|
|
66
|
+
"""What the agent may do with the GitHub App ``mda deploy`` sets up.
|
|
67
|
+
|
|
68
|
+
Deploy applies changes to these on every run. The App's name, owner and
|
|
69
|
+
description are not options: deploy names a new App after the agent, and
|
|
70
|
+
GitHub only lets them be changed on the App's settings page.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
permissions: dict[str, Literal["read", "write"]]
|
|
74
|
+
"""Permissions the agent's GitHub token needs beyond those the handled
|
|
75
|
+
events need, e.g. ``{"contents": "read"}``. The App asks for both."""
|
|
76
|
+
repositories: list[str]
|
|
77
|
+
"""Repositories (``owner/name``, one owner) the channel is limited to: events
|
|
78
|
+
from other repositories start nothing, and the agent's token covers only
|
|
79
|
+
these. Defaults to every repository the App is installed on."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
GitHubEventCallback = Callable[
|
|
83
|
+
[GitHubEvent[_Payload], GitHubChannelRuntime], str | Awaitable[str | None] | None
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
__all__ = [
|
|
88
|
+
"GitHubAppOptions",
|
|
89
|
+
"GitHubChannelRuntime",
|
|
90
|
+
"GitHubEvent",
|
|
91
|
+
"GitHubEventCallback",
|
|
92
|
+
"GitHubHandlers",
|
|
93
|
+
"GitHubLabeledIssuePayload",
|
|
94
|
+
"GitHubPayload",
|
|
95
|
+
"GitHubPullRequestPayload",
|
|
96
|
+
"GitHubRepository",
|
|
97
|
+
"GitHubSender",
|
|
98
|
+
"GitHubWorkflowPayload",
|
|
99
|
+
"SupportedEventKey",
|
|
100
|
+
]
|
|
101
|
+
|
|
102
|
+
GitHubHandlers = TypedDict(
|
|
103
|
+
"GitHubHandlers",
|
|
104
|
+
{
|
|
105
|
+
"issues.opened": GitHubEventCallback[_IssuePayload],
|
|
106
|
+
"issues.labeled": GitHubEventCallback[_LabeledIssuePayload],
|
|
107
|
+
"issue_comment.created": GitHubEventCallback[_IssueCommentPayload],
|
|
108
|
+
"pull_request.opened": GitHubEventCallback[_PullRequestPayload],
|
|
109
|
+
"pull_request.ready_for_review": GitHubEventCallback[_PullRequestPayload],
|
|
110
|
+
"pull_request.synchronize": GitHubEventCallback[_PullRequestPayload],
|
|
111
|
+
"pull_request.labeled": GitHubEventCallback[_LabeledPullRequestPayload],
|
|
112
|
+
"pull_request.closed": GitHubEventCallback[_PullRequestPayload],
|
|
113
|
+
"pull_request_review.submitted": GitHubEventCallback[_ReviewPayload],
|
|
114
|
+
"pull_request_review_comment.created": GitHubEventCallback[_ReviewCommentPayload],
|
|
115
|
+
"workflow_run.completed": GitHubEventCallback[_WorkflowPayload],
|
|
116
|
+
},
|
|
117
|
+
total=False,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
GitHubLabeledIssuePayload = _LabeledIssuePayload
|
|
122
|
+
GitHubPullRequestPayload = _PullRequestPayload
|
|
123
|
+
GitHubWorkflowPayload = _WorkflowPayload
|