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.
Files changed (86) hide show
  1. agentjam/__init__.py +435 -0
  2. agentjam/_adapters/__init__.py +0 -0
  3. agentjam/_adapters/responses.py +73 -0
  4. agentjam/_adapters/shared.py +435 -0
  5. agentjam/_agent.py +1032 -0
  6. agentjam/_agent_access.py +360 -0
  7. agentjam/_agent_delegations.py +376 -0
  8. agentjam/_agent_executions.py +566 -0
  9. agentjam/_agent_judging.py +288 -0
  10. agentjam/_agent_options.py +122 -0
  11. agentjam/_agent_routing.py +214 -0
  12. agentjam/_agent_session.py +195 -0
  13. agentjam/_agent_support.py +415 -0
  14. agentjam/_artifacts.py +565 -0
  15. agentjam/_attachments.py +112 -0
  16. agentjam/_connections.py +1282 -0
  17. agentjam/_content.py +29 -0
  18. agentjam/_cron.py +302 -0
  19. agentjam/_errors.py +238 -0
  20. agentjam/_events.py +113 -0
  21. agentjam/_files.py +55 -0
  22. agentjam/_github.py +742 -0
  23. agentjam/_idempotency.py +68 -0
  24. agentjam/_inputs.py +79 -0
  25. agentjam/_models.py +21 -0
  26. agentjam/_polling.py +139 -0
  27. agentjam/_profile.py +244 -0
  28. agentjam/_protocol.py +480 -0
  29. agentjam/_providers.py +365 -0
  30. agentjam/_recaps.py +67 -0
  31. agentjam/_relay/__init__.py +0 -0
  32. agentjam/_relay/actions.py +234 -0
  33. agentjam/_relay/artifacts.py +96 -0
  34. agentjam/_relay/base.py +387 -0
  35. agentjam/_relay/commits.py +77 -0
  36. agentjam/_relay/copies.py +66 -0
  37. agentjam/_relay/credentials.py +127 -0
  38. agentjam/_relay/endpoints.py +39 -0
  39. agentjam/_relay/follow_ups.py +548 -0
  40. agentjam/_relay/frames.py +443 -0
  41. agentjam/_relay/guest_store.py +114 -0
  42. agentjam/_relay/guests.py +55 -0
  43. agentjam/_relay/inputs.py +119 -0
  44. agentjam/_relay/lineage.py +294 -0
  45. agentjam/_relay/memory.py +1045 -0
  46. agentjam/_relay/payments.py +204 -0
  47. agentjam/_relay/profiles.py +95 -0
  48. agentjam/_relay/remote.py +826 -0
  49. agentjam/_relay/resumptions.py +65 -0
  50. agentjam/_relay/revisions.py +43 -0
  51. agentjam/_relay/schedule_follow_ups.py +274 -0
  52. agentjam/_relay/schedules.py +547 -0
  53. agentjam/_relay/secrets.py +275 -0
  54. agentjam/_relay/sessions.py +640 -0
  55. agentjam/_relay/uploads.py +71 -0
  56. agentjam/_requests.py +178 -0
  57. agentjam/_screening.py +368 -0
  58. agentjam/_secrets.py +153 -0
  59. agentjam/_sentry.py +233 -0
  60. agentjam/_signals.py +98 -0
  61. agentjam/_slack.py +468 -0
  62. agentjam/_stripe.py +93 -0
  63. agentjam/_tasks/__init__.py +0 -0
  64. agentjam/_tasks/access.py +142 -0
  65. agentjam/_tasks/incoming.py +952 -0
  66. agentjam/_tasks/outgoing.py +472 -0
  67. agentjam/_tasks/scheduled.py +206 -0
  68. agentjam/_tasks/serial.py +40 -0
  69. agentjam/_tasks/triggers.py +258 -0
  70. agentjam/_tasks/watches.py +77 -0
  71. agentjam/_tools.py +1035 -0
  72. agentjam/_types.py +965 -0
  73. agentjam/_utils.py +75 -0
  74. agentjam/_verdicts.py +21 -0
  75. agentjam/_watermarks.py +59 -0
  76. agentjam/anthropic.py +442 -0
  77. agentjam/mpp.py +233 -0
  78. agentjam/openai.py +141 -0
  79. agentjam/openai_agents.py +253 -0
  80. agentjam/py.typed +0 -0
  81. agentjam/pydantic_ai.py +301 -0
  82. agentjam/skills.py +69 -0
  83. agentjam-0.1.0.dist-info/METADATA +210 -0
  84. agentjam-0.1.0.dist-info/RECORD +86 -0
  85. agentjam-0.1.0.dist-info/WHEEL +4 -0
  86. agentjam-0.1.0.dist-info/licenses/LICENSE +21 -0
agentjam/_sentry.py ADDED
@@ -0,0 +1,233 @@
1
+ from collections.abc import Callable
2
+ from dataclasses import dataclass
3
+ from datetime import datetime, timedelta
4
+ from typing import Literal, TypeAlias
5
+ from urllib.parse import urlencode
6
+
7
+ import httpx
8
+ from pydantic import BaseModel, ConfigDict
9
+ from pydantic.alias_generators import to_camel
10
+
11
+ from agentjam._errors import AgentJamError
12
+ from agentjam._models import WireModel
13
+ from agentjam._polling import (
14
+ Polling,
15
+ Watermark,
16
+ compute_now,
17
+ construct_interval_property,
18
+ format_time,
19
+ get_interval,
20
+ log_error,
21
+ parse_time,
22
+ poll_schedule,
23
+ truncate_summary,
24
+ )
25
+ from agentjam._types import (
26
+ JsonObject,
27
+ OnScheduleActive,
28
+ Trigger,
29
+ TriggerActivation,
30
+ TriggerContext,
31
+ TriggerEvent,
32
+ TriggerSchedule,
33
+ )
34
+ from agentjam._watermarks import MemoryWatermarkStore, WatermarkStore
35
+
36
+ SentryRegion: TypeAlias = Literal["us", "de"]
37
+ """The Sentry region an organization's data lives in, which picks its API's host."""
38
+
39
+ SLUG_PATTERN = "^[a-z0-9][a-z0-9_-]*$"
40
+
41
+ ISSUES_PAGE_SIZE = 100
42
+
43
+ OVERLAP = timedelta(minutes=2)
44
+
45
+
46
+ class SentryErrorData(WireModel):
47
+ """A new Sentry issue, as the `task.event.data` of an `error_reported` run."""
48
+
49
+ region: SentryRegion
50
+ organization: str
51
+ project: str
52
+ issue_id: str
53
+ short_id: str
54
+ """The issue's id as Sentry shows it, such as `SHOP-1A`."""
55
+ title: str
56
+ culprit: str | None
57
+ level: str
58
+ url: str
59
+ first_seen: str
60
+
61
+
62
+ class SentryIssue(BaseModel):
63
+ model_config = ConfigDict(alias_generator=to_camel)
64
+
65
+ id: str
66
+ short_id: str
67
+ title: str
68
+ culprit: str | None
69
+ permalink: str
70
+ level: str
71
+ first_seen: str
72
+
73
+
74
+ @dataclass(frozen=True, kw_only=True)
75
+ class SentryProject:
76
+ region: SentryRegion
77
+ organization: str
78
+ project: str
79
+
80
+
81
+ def read_project(config: JsonObject) -> SentryProject:
82
+ return SentryProject(
83
+ region=config.get("region") or "us",
84
+ organization=config["organization"],
85
+ project=config["project"],
86
+ )
87
+
88
+
89
+ async def list_new_issues(
90
+ token: str, project: SentryProject, first_seen_after: datetime
91
+ ) -> list[SentryIssue]:
92
+ query = urlencode(
93
+ {
94
+ "query": f"is:unresolved firstSeen:>{format_time(first_seen_after)}",
95
+ "sort": "new",
96
+ "limit": ISSUES_PAGE_SIZE,
97
+ }
98
+ )
99
+ path = f"/api/0/projects/{project.organization}/{project.project}/issues/?{query}"
100
+
101
+ async with httpx.AsyncClient(
102
+ base_url=f"https://{project.region}.sentry.io"
103
+ ) as client:
104
+ response = await client.get(
105
+ path,
106
+ headers={"accept": "application/json", "authorization": f"Bearer {token}"},
107
+ )
108
+
109
+ if not response.is_success:
110
+ raise AgentJamError(
111
+ f"Sentry answered {response.status_code} for {path}: {response.text}"
112
+ )
113
+
114
+ return [SentryIssue.model_validate(issue) for issue in response.json()]
115
+
116
+
117
+ def construct_error_event(project: SentryProject, issue: SentryIssue) -> TriggerEvent:
118
+ data = SentryErrorData(
119
+ region=project.region,
120
+ organization=project.organization,
121
+ project=project.project,
122
+ issue_id=issue.id,
123
+ short_id=issue.short_id,
124
+ title=issue.title,
125
+ culprit=issue.culprit,
126
+ level=issue.level,
127
+ url=issue.permalink,
128
+ first_seen=issue.first_seen,
129
+ )
130
+
131
+ return TriggerEvent(
132
+ id=f"sentry:{project.region}:{project.organization}:{issue.id}",
133
+ summary=truncate_summary(f"New Sentry error {issue.short_id}: {issue.title}"),
134
+ data=data.model_dump(mode="json"),
135
+ )
136
+
137
+
138
+ def watch_project(polling: Polling) -> OnScheduleActive:
139
+ async def activate(
140
+ schedule: TriggerSchedule, context: TriggerContext
141
+ ) -> TriggerActivation:
142
+ project = read_project(schedule.config)
143
+
144
+ async def poll(watermark: Watermark) -> None:
145
+ started_at = compute_now()
146
+ since = parse_time(watermark.current["since"])
147
+ checked_at = parse_time(watermark.current["checkedAt"])
148
+
149
+ issues = await list_new_issues(
150
+ await context.credentials(polling.provider),
151
+ project,
152
+ max(since, checked_at - OVERLAP),
153
+ )
154
+ fresh = sorted(
155
+ (issue for issue in issues if parse_time(issue.first_seen) > since),
156
+ key=lambda issue: parse_time(issue.first_seen),
157
+ )
158
+ for issue in fresh:
159
+ await context.fire(construct_error_event(project, issue))
160
+
161
+ await watermark.advance(checkedAt=started_at)
162
+
163
+ now = compute_now()
164
+ stop = await poll_schedule(
165
+ schedule=schedule,
166
+ watermarks=polling.watermarks,
167
+ initial={"since": now, "checkedAt": now},
168
+ interval_minutes=get_interval(schedule, polling),
169
+ target=f"{project.organization}/{project.project} for new Sentry errors",
170
+ on_error=polling.on_error,
171
+ poll=poll,
172
+ )
173
+
174
+ return TriggerActivation(stop=stop)
175
+
176
+ return activate
177
+
178
+
179
+ def sentry_triggers(
180
+ *,
181
+ provider: str = "sentry",
182
+ watermarks: WatermarkStore | None = None,
183
+ poll_interval_minutes: float = 1,
184
+ on_error: Callable[[Exception], None] = log_error,
185
+ ) -> dict[str, Trigger]:
186
+ """Triggers that run a schedule on a Sentry project's errors, for a skill with the Sentry connection `provider` names.
187
+
188
+ The connection needs the `event:read`, `project:read` and `org:read` scopes. Each schedule polls with its token
189
+ from where `watermarks` says it left off, once per new unresolved issue, which a regression doesn't repeat.
190
+
191
+ Args:
192
+ provider: The provider of the skill's Sentry connection.
193
+ watermarks: Where polls keep each schedule's progress. Defaults to a `MemoryWatermarkStore`, which forgets it on exit.
194
+ poll_interval_minutes: How often a schedule that doesn't set `pollIntervalMinutes` polls Sentry.
195
+ on_error: Handles a failed poll, which is tried again at the next interval. Defaults to logging it.
196
+
197
+ Returns:
198
+ The `error_reported` trigger, for a skill's `triggers`.
199
+ """
200
+ polling = Polling(
201
+ provider=provider,
202
+ watermarks=watermarks if watermarks is not None else MemoryWatermarkStore(),
203
+ poll_interval_minutes=poll_interval_minutes,
204
+ on_error=on_error,
205
+ )
206
+
207
+ return {
208
+ "error_reported": Trigger(
209
+ description="Sentry sees a new unresolved issue in a project",
210
+ config={
211
+ "type": "object",
212
+ "properties": {
213
+ "region": {
214
+ "enum": ["us", "de"],
215
+ "description": "The Sentry region the organization's data lives in. Defaults to us",
216
+ },
217
+ "organization": {
218
+ "type": "string",
219
+ "pattern": SLUG_PATTERN,
220
+ "description": "The Sentry organization's slug",
221
+ },
222
+ "project": {
223
+ "type": "string",
224
+ "pattern": SLUG_PATTERN,
225
+ "description": "The slug of the Sentry project to watch",
226
+ },
227
+ "pollIntervalMinutes": construct_interval_property("new errors"),
228
+ },
229
+ "required": ["organization", "project"],
230
+ },
231
+ on_schedule_active=watch_project(polling),
232
+ ),
233
+ }
agentjam/_signals.py ADDED
@@ -0,0 +1,98 @@
1
+ import asyncio
2
+ import inspect
3
+ from collections.abc import Awaitable, Callable, Iterable
4
+ from typing import TypeVar
5
+
6
+ T = TypeVar("T")
7
+
8
+ AbortListener = Callable[[BaseException], None]
9
+
10
+
11
+ class Signal:
12
+ """Fires once with the reason some work must stop, like a JS `AbortSignal`."""
13
+
14
+ def __init__(self) -> None:
15
+ self._reason: BaseException | None = None
16
+ self._listeners: list[AbortListener] = []
17
+ self._fired = asyncio.Event()
18
+
19
+ @property
20
+ def aborted(self) -> bool:
21
+ return self._reason is not None
22
+
23
+ @property
24
+ def reason(self) -> BaseException | None:
25
+ return self._reason
26
+
27
+ def abort(self, reason: BaseException) -> None:
28
+ if self._reason is not None:
29
+ return
30
+
31
+ self._reason = reason
32
+ self._fired.set()
33
+ for listener in self._listeners.copy():
34
+ listener(reason)
35
+
36
+ self._listeners.clear()
37
+
38
+ def on_abort(self, listener: AbortListener) -> Callable[[], None]:
39
+ """Calls `listener` once this signal aborts, and returns a function removing it."""
40
+ if self._reason is not None:
41
+ listener(self._reason)
42
+ return lambda: None
43
+
44
+ self._listeners.append(listener)
45
+
46
+ def remove() -> None:
47
+ if listener in self._listeners:
48
+ self._listeners.remove(listener)
49
+
50
+ return remove
51
+
52
+ def raise_if_aborted(self) -> None:
53
+ if self._reason is not None:
54
+ raise self._reason
55
+
56
+ async def wait(self) -> BaseException:
57
+ await self._fired.wait()
58
+ assert self._reason is not None, "A fired signal always has a reason"
59
+
60
+ return self._reason
61
+
62
+ @classmethod
63
+ def any(cls, signals: Iterable["Signal | None"]) -> "Signal":
64
+ """Returns a signal that aborts as soon as any of `signals` does."""
65
+ combined = cls()
66
+ for signal in signals:
67
+ if signal is not None:
68
+ signal.on_abort(combined.abort)
69
+
70
+ return combined
71
+
72
+
73
+ async def guard(work: Awaitable[T], signal: Signal | None) -> T:
74
+ """Awaits `work`, cancelling it and raising the signal's reason once `signal` aborts."""
75
+ if signal is None:
76
+ return await work
77
+
78
+ if signal.aborted and inspect.iscoroutine(work):
79
+ work.close()
80
+
81
+ signal.raise_if_aborted()
82
+ task = asyncio.ensure_future(work)
83
+
84
+ def cancel(_: BaseException) -> None:
85
+ task.cancel()
86
+
87
+ remove = signal.on_abort(cancel)
88
+
89
+ try:
90
+ return await task
91
+ except asyncio.CancelledError:
92
+ current = asyncio.current_task()
93
+ if signal.reason is None or (current is not None and current.cancelling()):
94
+ raise
95
+
96
+ raise signal.reason from None
97
+ finally:
98
+ remove()