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/_content.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from collections.abc import AsyncIterable
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
|
|
4
|
+
from agentjam._files import File
|
|
5
|
+
|
|
6
|
+
Content = str | bytes | File | AsyncIterable[str | bytes]
|
|
7
|
+
"""Content an artifact or attachment can carry. Async iterables, such as LLM text streams, stream as artifacts."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, slots=True)
|
|
11
|
+
class LabeledContent:
|
|
12
|
+
"""Content with metadata attached. Build one with `artifact()` or `attachment()`."""
|
|
13
|
+
|
|
14
|
+
content: Content
|
|
15
|
+
"""The content to send."""
|
|
16
|
+
name: str | None = None
|
|
17
|
+
"""The content's name, such as a file name, which takes precedence over a `File`'s."""
|
|
18
|
+
mime_type: str | None = None
|
|
19
|
+
"""The content's MIME type, which takes precedence over a `File`'s."""
|
|
20
|
+
key: str | None = None
|
|
21
|
+
"""A stable key of 1 to 256 characters. A later delivery with the same key replaces the artifact for requesters."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
ContentSource = Content | LabeledContent
|
|
25
|
+
"""Content, optionally labeled with a name and MIME type."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def unlabel(source: ContentSource) -> LabeledContent:
|
|
29
|
+
return source if isinstance(source, LabeledContent) else LabeledContent(source)
|
agentjam/_cron.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from collections.abc import Callable, Iterator
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import UTC, datetime, timedelta
|
|
5
|
+
from itertools import takewhile
|
|
6
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
7
|
+
|
|
8
|
+
from croniter import CroniterBadDateError, CroniterError, croniter
|
|
9
|
+
|
|
10
|
+
from agentjam._types import Cron
|
|
11
|
+
|
|
12
|
+
DEFAULT_TIME_ZONE = "UTC"
|
|
13
|
+
|
|
14
|
+
SECOND = timedelta(seconds=1)
|
|
15
|
+
|
|
16
|
+
MINUTE = 60.0
|
|
17
|
+
|
|
18
|
+
YEAR = 365 * 24 * 60 * MINUTE
|
|
19
|
+
|
|
20
|
+
SEARCH_LIMIT = timedelta(days=100 * 366)
|
|
21
|
+
|
|
22
|
+
NICKNAMES = {
|
|
23
|
+
"@yearly": "0 0 1 1 *",
|
|
24
|
+
"@annually": "0 0 1 1 *",
|
|
25
|
+
"@monthly": "0 0 1 * *",
|
|
26
|
+
"@weekly": "0 0 * * 0",
|
|
27
|
+
"@daily": "0 0 * * *",
|
|
28
|
+
"@midnight": "0 0 * * *",
|
|
29
|
+
"@hourly": "0 * * * *",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def is_wild(part: str) -> bool:
|
|
34
|
+
return any(marker in part for marker in "*?/")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def load_zone(time_zone: str) -> ZoneInfo:
|
|
38
|
+
try:
|
|
39
|
+
return ZoneInfo(time_zone)
|
|
40
|
+
except (ZoneInfoNotFoundError, ValueError):
|
|
41
|
+
raise ValueError(
|
|
42
|
+
f'Time zone "{time_zone}" isn\'t an IANA time zone, such as "America/New_York"'
|
|
43
|
+
) from None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Timetable:
|
|
48
|
+
"""The instants a cron runs at in its time zone, following Vixie cron across daylight saving changes.
|
|
49
|
+
|
|
50
|
+
A fixed-time cron, with no wildcard or step in its minutes and hours, runs once at the first pass of a
|
|
51
|
+
repeated time, and at the end of a gap on the same day. Any other cron runs on both passes and skips gaps.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
expression: str
|
|
55
|
+
zone: ZoneInfo
|
|
56
|
+
fixed: bool
|
|
57
|
+
|
|
58
|
+
def find_next(self, after: datetime) -> datetime | None:
|
|
59
|
+
wall = self.convert_to_wall(after)
|
|
60
|
+
repeat = None if self.fixed else self.measure_repeat(after, fold=0)
|
|
61
|
+
if repeat is None:
|
|
62
|
+
return self.find_first(wall, after, forward=True)
|
|
63
|
+
|
|
64
|
+
runs = [
|
|
65
|
+
run for run in self.list_runs(wall - repeat, wall + repeat) if run > after
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
return (
|
|
69
|
+
min(runs) if runs else self.find_first(wall + repeat, after, forward=True)
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
def find_previous(self, before: datetime) -> datetime | None:
|
|
73
|
+
wall = self.convert_to_wall(before)
|
|
74
|
+
repeat = self.measure_repeat(before, fold=1)
|
|
75
|
+
if repeat is None:
|
|
76
|
+
return self.find_first(wall, before, forward=False)
|
|
77
|
+
|
|
78
|
+
runs = [
|
|
79
|
+
run for run in self.list_runs(wall - repeat, wall + repeat) if run < before
|
|
80
|
+
]
|
|
81
|
+
|
|
82
|
+
return (
|
|
83
|
+
max(runs) if runs else self.find_first(wall - repeat, before, forward=False)
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def list_runs(self, first: datetime, last: datetime) -> list[datetime]:
|
|
87
|
+
"""Lists every instant the wall-clock matches from `first` to `last` run at, around a repeated span."""
|
|
88
|
+
walls = takewhile(
|
|
89
|
+
lambda wall: wall <= last, self.iterate_walls(first, forward=True)
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
return [instant for wall in walls for instant in self.list_instants(wall)]
|
|
93
|
+
|
|
94
|
+
def find_first(
|
|
95
|
+
self, wall: datetime, bound: datetime, *, forward: bool
|
|
96
|
+
) -> datetime | None:
|
|
97
|
+
"""Finds the first run past `bound`, walking wall-clock matches from `wall` in the given direction."""
|
|
98
|
+
for candidate in self.iterate_walls(wall, forward=forward):
|
|
99
|
+
if abs(candidate - wall) > SEARCH_LIMIT:
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
instants = self.list_instants(candidate)
|
|
103
|
+
for instant in instants if forward else reversed(instants):
|
|
104
|
+
if (instant > bound) if forward else (instant < bound):
|
|
105
|
+
return instant
|
|
106
|
+
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
def iterate_walls(self, wall: datetime, *, forward: bool) -> Iterator[datetime]:
|
|
110
|
+
walls = croniter(self.expression, wall - SECOND if forward else wall + SECOND)
|
|
111
|
+
try:
|
|
112
|
+
while True:
|
|
113
|
+
yield walls.get_next(datetime) if forward else walls.get_prev(datetime)
|
|
114
|
+
except CroniterBadDateError:
|
|
115
|
+
return
|
|
116
|
+
|
|
117
|
+
def list_instants(self, wall: datetime) -> list[datetime]:
|
|
118
|
+
"""Lists the instants a matching wall-clock time runs at, oldest first."""
|
|
119
|
+
earlier = wall.replace(tzinfo=self.zone, fold=0)
|
|
120
|
+
later = wall.replace(tzinfo=self.zone, fold=1)
|
|
121
|
+
if self.convert_to_wall(earlier) != wall:
|
|
122
|
+
end = self.find_gap_end(wall)
|
|
123
|
+
|
|
124
|
+
return [end] if self.fixed and end is not None else []
|
|
125
|
+
|
|
126
|
+
if self.fixed or earlier.utcoffset() == later.utcoffset():
|
|
127
|
+
return [earlier.astimezone(UTC)]
|
|
128
|
+
|
|
129
|
+
return [earlier.astimezone(UTC), later.astimezone(UTC)]
|
|
130
|
+
|
|
131
|
+
def find_gap_end(self, wall: datetime) -> datetime | None:
|
|
132
|
+
"""Finds the first instant after the gap `wall` falls in, if it's on the same day."""
|
|
133
|
+
low = int(wall.replace(tzinfo=self.zone, fold=1).timestamp())
|
|
134
|
+
high = int(wall.replace(tzinfo=self.zone, fold=0).timestamp())
|
|
135
|
+
shifted = self.read_offset(datetime.fromtimestamp(high, UTC))
|
|
136
|
+
while high - low > 1:
|
|
137
|
+
middle = (low + high) // 2
|
|
138
|
+
if self.read_offset(datetime.fromtimestamp(middle, UTC)) == shifted:
|
|
139
|
+
high = middle
|
|
140
|
+
else:
|
|
141
|
+
low = middle
|
|
142
|
+
|
|
143
|
+
end = datetime.fromtimestamp(high, UTC)
|
|
144
|
+
|
|
145
|
+
return end if self.convert_to_wall(end).date() == wall.date() else None
|
|
146
|
+
|
|
147
|
+
def measure_repeat(self, instant: datetime, *, fold: int) -> timedelta | None:
|
|
148
|
+
"""Measures the repeated wall-clock span `instant` falls in, while it's on the pass `fold` of it."""
|
|
149
|
+
local = instant.astimezone(UTC).astimezone(self.zone)
|
|
150
|
+
earlier = local.replace(fold=0).utcoffset()
|
|
151
|
+
later = local.replace(fold=1).utcoffset()
|
|
152
|
+
if local.fold != fold or earlier is None or later is None:
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
return earlier - later if earlier > later else None
|
|
156
|
+
|
|
157
|
+
def read_offset(self, instant: datetime) -> timedelta | None:
|
|
158
|
+
return instant.astimezone(self.zone).utcoffset()
|
|
159
|
+
|
|
160
|
+
def convert_to_wall(self, instant: datetime) -> datetime:
|
|
161
|
+
return instant.astimezone(UTC).astimezone(self.zone).replace(tzinfo=None)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def construct_timetable(cron: Cron) -> Timetable:
|
|
165
|
+
time_zone = DEFAULT_TIME_ZONE if cron.time_zone is None else cron.time_zone
|
|
166
|
+
zone = load_zone(time_zone)
|
|
167
|
+
expression = NICKNAMES.get(cron.expression.strip().lower(), cron.expression)
|
|
168
|
+
parts = expression.split()
|
|
169
|
+
if len(parts) != 5:
|
|
170
|
+
raise ValueError(
|
|
171
|
+
f"CronPattern: mode '5-part' requires exactly 5 parts, but pattern "
|
|
172
|
+
f"'{expression}' has {len(parts)} parts."
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
try:
|
|
176
|
+
croniter(expression)
|
|
177
|
+
except CroniterError as error:
|
|
178
|
+
raise ValueError(str(error)) from None
|
|
179
|
+
|
|
180
|
+
minute, hour = parts[:2]
|
|
181
|
+
|
|
182
|
+
return Timetable(expression, zone, not is_wild(minute) and not is_wild(hour))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def cron_problem(cron: Cron, now: datetime | None = None) -> str | None:
|
|
186
|
+
"""Explains why a cron can't run a schedule, or returns None when it can."""
|
|
187
|
+
try:
|
|
188
|
+
timetable = construct_timetable(cron)
|
|
189
|
+
except ValueError as error:
|
|
190
|
+
return str(error)
|
|
191
|
+
|
|
192
|
+
if timetable.find_next(now or datetime.now(UTC)) is not None:
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
return f'The cron expression "{cron.expression}" never runs'
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def compute_next_run(cron: Cron, after: datetime) -> datetime | None:
|
|
199
|
+
return construct_timetable(cron).find_next(after)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def compute_shortest_within(
|
|
203
|
+
timetable: Timetable, first: datetime, last: datetime
|
|
204
|
+
) -> float:
|
|
205
|
+
shortest = math.inf
|
|
206
|
+
run = first
|
|
207
|
+
next_run = timetable.find_next(run)
|
|
208
|
+
while next_run is not None and next_run <= last:
|
|
209
|
+
shortest = min(shortest, (next_run - run).total_seconds())
|
|
210
|
+
run = next_run
|
|
211
|
+
next_run = timetable.find_next(run)
|
|
212
|
+
|
|
213
|
+
return shortest
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def scan_shortest_gap(
|
|
217
|
+
cron: Cron,
|
|
218
|
+
start: datetime | None,
|
|
219
|
+
horizon: float,
|
|
220
|
+
is_short_enough: Callable[[float], bool],
|
|
221
|
+
) -> float | None:
|
|
222
|
+
"""Finds the shortest gap between runs, stopping early once `is_short_enough` holds for it.
|
|
223
|
+
|
|
224
|
+
Every day's runs share one time of day pattern, so only days a time zone shift or the horizon reshapes are walked run by run.
|
|
225
|
+
"""
|
|
226
|
+
timetable = construct_timetable(cron)
|
|
227
|
+
midnight = Timetable("0 0 * * *", timetable.zone, fixed=True)
|
|
228
|
+
since = start or datetime.now(UTC)
|
|
229
|
+
until = since + timedelta(seconds=horizon)
|
|
230
|
+
shortest = math.inf
|
|
231
|
+
ordinary: float | None = None
|
|
232
|
+
previous: datetime | None = None
|
|
233
|
+
first = timetable.find_next(since)
|
|
234
|
+
while first is not None and first <= until and not is_short_enough(shortest):
|
|
235
|
+
day_end = midnight.find_next(first) or until
|
|
236
|
+
day_last = timetable.find_previous(day_end - SECOND) or first
|
|
237
|
+
is_truncated = day_last > until
|
|
238
|
+
last = until if is_truncated else day_last
|
|
239
|
+
is_ordinary = (
|
|
240
|
+
previous is not None
|
|
241
|
+
and not is_truncated
|
|
242
|
+
and timetable.read_offset(first) == timetable.read_offset(day_last)
|
|
243
|
+
)
|
|
244
|
+
if previous is not None:
|
|
245
|
+
shortest = min(shortest, (first - previous).total_seconds())
|
|
246
|
+
|
|
247
|
+
if not is_ordinary or ordinary is None:
|
|
248
|
+
within = compute_shortest_within(timetable, first, last)
|
|
249
|
+
if is_ordinary:
|
|
250
|
+
ordinary = within
|
|
251
|
+
|
|
252
|
+
shortest = min(shortest, within)
|
|
253
|
+
else:
|
|
254
|
+
shortest = min(shortest, ordinary)
|
|
255
|
+
|
|
256
|
+
previous = last
|
|
257
|
+
first = timetable.find_next(last)
|
|
258
|
+
|
|
259
|
+
return None if shortest == math.inf else shortest
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def compute_shortest_interval(
|
|
263
|
+
cron: Cron, *, start: datetime | None = None, horizon: float = YEAR
|
|
264
|
+
) -> float | None:
|
|
265
|
+
"""Computes the shortest gap between consecutive runs of a cron, read in its time zone across daylight saving changes.
|
|
266
|
+
|
|
267
|
+
Use it to refuse schedules that would run more often than an agent allows.
|
|
268
|
+
|
|
269
|
+
Args:
|
|
270
|
+
cron: The cron expression and its time zone.
|
|
271
|
+
start: When to start looking, as a timezone-aware datetime. Defaults to now.
|
|
272
|
+
horizon: How far past `start` to look, in seconds. Defaults to a year.
|
|
273
|
+
Returns:
|
|
274
|
+
The shortest gap in seconds, or None if the cron runs at most once in that span.
|
|
275
|
+
Raises:
|
|
276
|
+
ValueError: If the expression or time zone is invalid.
|
|
277
|
+
"""
|
|
278
|
+
return scan_shortest_gap(cron, start, horizon, lambda gap: gap <= MINUTE)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def is_interval_at_least(
|
|
282
|
+
cron: Cron,
|
|
283
|
+
minimum: float,
|
|
284
|
+
*,
|
|
285
|
+
start: datetime | None = None,
|
|
286
|
+
horizon: float = YEAR,
|
|
287
|
+
) -> bool:
|
|
288
|
+
"""Checks that no two consecutive runs of a cron are closer than `minimum`, such as in `on_proposal` before accepting a schedule.
|
|
289
|
+
|
|
290
|
+
Args:
|
|
291
|
+
cron: The cron expression and its time zone.
|
|
292
|
+
minimum: The shortest gap allowed between runs, in seconds.
|
|
293
|
+
start: When to start looking, as a timezone-aware datetime. Defaults to now.
|
|
294
|
+
horizon: How far past `start` to look, in seconds. Defaults to a year.
|
|
295
|
+
Returns:
|
|
296
|
+
Whether every gap in that span is at least `minimum`.
|
|
297
|
+
Raises:
|
|
298
|
+
ValueError: If the expression or time zone is invalid.
|
|
299
|
+
"""
|
|
300
|
+
shortest = scan_shortest_gap(cron, start, horizon, lambda gap: gap < minimum)
|
|
301
|
+
|
|
302
|
+
return shortest is None or shortest >= minimum
|
agentjam/_errors.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import builtins
|
|
2
|
+
import math
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
from agentjam._protocol import LimitCode, TaskEndCode
|
|
6
|
+
|
|
7
|
+
ADDRESS_MISTAKE = "Either the username or the agent name is wrong (agents are addressed as username/agent-name)"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AgentJamError(Exception):
|
|
11
|
+
"""Base class for every error raised by the AgentJam SDK."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AgentNotFoundError(AgentJamError):
|
|
15
|
+
"""Raised when a message or proposal is addressed to an agent that isn't connected.
|
|
16
|
+
|
|
17
|
+
Either the username or the agent name in its `username/agent-name` address is wrong, or it's offline.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, agent: str) -> None:
|
|
21
|
+
super().__init__(
|
|
22
|
+
f'No agent named "{agent}" is connected. {ADDRESS_MISTAKE}, or the agent is offline'
|
|
23
|
+
)
|
|
24
|
+
self.agent = agent
|
|
25
|
+
"""The address of the agent that isn't connected."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class InstanceTakenError(AgentJamError):
|
|
29
|
+
"""Raised by `connect()` when another connection holds its `instance_id` past the connect timeout.
|
|
30
|
+
|
|
31
|
+
A connection that ended without saying bye holds it until its lease lapses, `retry_after` seconds from now.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, agent: str, instance_id: str, retry_after: float) -> None:
|
|
35
|
+
super().__init__(
|
|
36
|
+
f'Instance "{instance_id}" of "{agent}" is already connected. If that '
|
|
37
|
+
f"connection is gone, its lease lapses in {math.ceil(retry_after)}s"
|
|
38
|
+
)
|
|
39
|
+
self.agent = agent
|
|
40
|
+
"""The name of the agent being connected."""
|
|
41
|
+
self.instance_id = instance_id
|
|
42
|
+
"""The instance another connection holds."""
|
|
43
|
+
self.retry_after = retry_after
|
|
44
|
+
"""How long until the held instance's lease lapses, in seconds."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class AgentExistsError(AgentJamError):
|
|
48
|
+
"""Raised by `create()` when an agent with that name exists. Pass `upsert=True` to update it instead."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class TimeoutError(AgentJamError, builtins.TimeoutError):
|
|
52
|
+
"""Raised when a request gets no response within its timeout."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class TaskRejectedError(AgentJamError):
|
|
56
|
+
"""Raised by `propose()` when the recipient declines the task, or by a task's `result()` if it declines after restarting."""
|
|
57
|
+
|
|
58
|
+
def __init__(self, agent: str, reason: str) -> None:
|
|
59
|
+
super().__init__(f"{agent} rejected the task: {reason}")
|
|
60
|
+
self.agent = agent
|
|
61
|
+
"""The agent that rejected the task."""
|
|
62
|
+
self.reason = reason
|
|
63
|
+
"""Why the agent rejected the task."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class TaskFailedError(AgentJamError):
|
|
67
|
+
"""Raised by a task's `result()` and `events()` when the executor fails it.
|
|
68
|
+
|
|
69
|
+
It has a `code` once the task failed because its requester couldn't fund a commit.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def __init__(self, message: str, code: LimitCode | None = None) -> None:
|
|
73
|
+
super().__init__(message)
|
|
74
|
+
self.code = code
|
|
75
|
+
"""Why the requester couldn't fund the action its executor committed to, when that's why it failed."""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class TriggerFailedError(AgentJamError):
|
|
79
|
+
"""Passed to an executor's `on_error` when the relay gives up on a fired event that never started a run, so it may be fired again."""
|
|
80
|
+
|
|
81
|
+
def __init__(
|
|
82
|
+
self, requester: str, schedule_id: str, event_id: str, reason: str
|
|
83
|
+
) -> None:
|
|
84
|
+
super().__init__(
|
|
85
|
+
f"Event {event_id} of {requester}'s schedule {schedule_id} didn't start "
|
|
86
|
+
f"a run: {reason}"
|
|
87
|
+
)
|
|
88
|
+
self.requester = requester
|
|
89
|
+
"""The agent that requested the schedule."""
|
|
90
|
+
self.schedule_id = schedule_id
|
|
91
|
+
"""The schedule the event was fired for."""
|
|
92
|
+
self.event_id = event_id
|
|
93
|
+
"""The `id` of the event that didn't start a run."""
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class FollowUpFailedError(AgentJamError):
|
|
97
|
+
"""Passed to a requester's `on_error` when a run met its schedule's follow-up condition, but the relay couldn't propose the follow-up."""
|
|
98
|
+
|
|
99
|
+
def __init__(self, agent: str, schedule_id: str, run_id: str, reason: str) -> None:
|
|
100
|
+
super().__init__(
|
|
101
|
+
f"Run {run_id} of schedule {schedule_id} wasn't followed up with "
|
|
102
|
+
f"{agent}: {reason}"
|
|
103
|
+
)
|
|
104
|
+
self.agent = agent
|
|
105
|
+
"""The agent the follow-up was for."""
|
|
106
|
+
self.schedule_id = schedule_id
|
|
107
|
+
"""The schedule whose run wasn't followed up."""
|
|
108
|
+
self.run_id = run_id
|
|
109
|
+
"""The run that wasn't followed up."""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class DispatchFailedError(AgentJamError):
|
|
113
|
+
"""Raised by `dispatch()` when the relay never received the event, so it may be dispatched again."""
|
|
114
|
+
|
|
115
|
+
def __init__(self, event_id: str, reason: str) -> None:
|
|
116
|
+
super().__init__(f"Event {event_id} wasn't dispatched: {reason}")
|
|
117
|
+
self.event_id = event_id
|
|
118
|
+
"""The `id` of the event that wasn't dispatched."""
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class TaskCanceledError(AgentJamError):
|
|
122
|
+
"""Raised by a task's `result()` and `events()` once it has been canceled, and why an executor's task stops.
|
|
123
|
+
|
|
124
|
+
A task the relay canceled once its requester could fund no more of it has a `code`.
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
def __init__(self, message: str, code: TaskEndCode | None = None) -> None:
|
|
128
|
+
super().__init__(message)
|
|
129
|
+
self.code = code
|
|
130
|
+
"""Why the relay ended the task, such as `insufficient_credits`."""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class TaskCommittedError(AgentJamError):
|
|
134
|
+
"""Raised by a task's `cancel()` once its executor committed to an action it can't undo, so the task keeps running."""
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class UncoveredCostError(AgentJamError):
|
|
138
|
+
"""Raised by a task's `commit()` when its requester can't fund the cost plus the skill's markup."""
|
|
139
|
+
|
|
140
|
+
def __init__(self, message: str, required_cents: float, code: LimitCode) -> None:
|
|
141
|
+
super().__init__(message)
|
|
142
|
+
self.required_cents = required_cents
|
|
143
|
+
"""The cents the relay must hold from the requester to cover the cost."""
|
|
144
|
+
self.code = code
|
|
145
|
+
"""Why the requester can't fund it, such as `reload_failed` once their wallet's auto-reload failed."""
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
PaymentRequiredReason = Literal[
|
|
149
|
+
"unclaimed",
|
|
150
|
+
"no_payment_method",
|
|
151
|
+
"insufficient_credits",
|
|
152
|
+
"cap_reached",
|
|
153
|
+
"exceeds_cap",
|
|
154
|
+
"invalid_payment",
|
|
155
|
+
"price_too_high",
|
|
156
|
+
"below_card_minimum",
|
|
157
|
+
"payment_failed",
|
|
158
|
+
]
|
|
159
|
+
"""Why a proposal to a priced skill or a top-up went unpaid.
|
|
160
|
+
|
|
161
|
+
The relay reports `unclaimed` for a guest, which can only run free tasks, and the others when it can't
|
|
162
|
+
reserve the price from your credits. Top-ups through `payments` report the last two.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class PaymentRequiredError(AgentJamError):
|
|
167
|
+
"""Raised by `propose()` when the task's skill is priced and the agent couldn't pay for it.
|
|
168
|
+
|
|
169
|
+
`setup_url` opens the page where the agent's human fixes it: the claim page for an unclaimed guest, or billing settings.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
def __init__(
|
|
173
|
+
self,
|
|
174
|
+
reason: PaymentRequiredReason,
|
|
175
|
+
message: str | None = None,
|
|
176
|
+
setup_url: str | None = None,
|
|
177
|
+
) -> None:
|
|
178
|
+
super().__init__(message or f"The task requires payment ({reason})")
|
|
179
|
+
self.reason: PaymentRequiredReason = reason
|
|
180
|
+
"""Why the task couldn't be paid for."""
|
|
181
|
+
self.setup_url = setup_url
|
|
182
|
+
"""The page where the agent's human fixes the payment, if there is one."""
|
|
183
|
+
|
|
184
|
+
@property
|
|
185
|
+
def claim_url(self) -> str | None:
|
|
186
|
+
"""The single-use link where a guest's human claims it, set only when `reason` is `unclaimed`."""
|
|
187
|
+
return self.setup_url if self.reason == "unclaimed" else None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class SkillRequiredError(AgentJamError):
|
|
191
|
+
"""Raised by `propose()` when the agent charges for its skills and the proposal doesn't name one of them."""
|
|
192
|
+
|
|
193
|
+
def __init__(self, agent: str, message: str | None = None) -> None:
|
|
194
|
+
super().__init__(
|
|
195
|
+
message
|
|
196
|
+
or f"{agent} charges for its skills, so the proposal must name one of them"
|
|
197
|
+
)
|
|
198
|
+
self.agent = agent
|
|
199
|
+
"""The agent that charges for its skills."""
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class InvalidInputError(AgentJamError):
|
|
203
|
+
"""Raised by `propose()` and `schedule()` when the input doesn't match the skill's input schema."""
|
|
204
|
+
|
|
205
|
+
def __init__(self, agent: str, message: str) -> None:
|
|
206
|
+
super().__init__(message)
|
|
207
|
+
self.agent = agent
|
|
208
|
+
"""The agent whose skill refused the input."""
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class ConnectionRevokedError(AgentJamError):
|
|
212
|
+
"""Raised once the requester's account with `provider` is no longer connected, such as after its human revoked access."""
|
|
213
|
+
|
|
214
|
+
def __init__(self, provider: str, reason: str) -> None:
|
|
215
|
+
super().__init__(f"The {provider} account is no longer connected: {reason}")
|
|
216
|
+
self.provider = provider
|
|
217
|
+
"""The provider of the account that is no longer connected."""
|
|
218
|
+
self.reason = reason
|
|
219
|
+
"""Why the account is no longer connected."""
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class RequestRefusedError(AgentJamError):
|
|
223
|
+
"""Raised by a `connection_fetch()` function when the platform refuses to send a request, such as one the skill's allowlist doesn't permit."""
|
|
224
|
+
|
|
225
|
+
def __init__(self, provider: str, reason: str, message: str) -> None:
|
|
226
|
+
super().__init__(message)
|
|
227
|
+
self.provider = provider
|
|
228
|
+
"""The provider of the secret connection the request was for."""
|
|
229
|
+
self.reason = reason
|
|
230
|
+
"""Why the platform refused, such as `unlisted_request`, `invalid_target` or `rate_limited`."""
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class ReassignedError(AgentJamError):
|
|
234
|
+
"""Raised once the relay moved the work this session answered to another of its agent's sessions, which answers it instead."""
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def describe_error(error: BaseException | object) -> str:
|
|
238
|
+
return str(error)
|
agentjam/_events.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
from collections.abc import Mapping
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from typing import Literal, Protocol, TypeAlias
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from agentjam._providers import AccountRevocation
|
|
8
|
+
from agentjam._types import TriggerEvent
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True, kw_only=True)
|
|
12
|
+
class SourceRequest:
|
|
13
|
+
"""A provider's webhook request, as the headers and raw body any server framework hands over."""
|
|
14
|
+
|
|
15
|
+
headers: Mapping[str, str]
|
|
16
|
+
"""The request's headers, whose names are read case-insensitively."""
|
|
17
|
+
body: str | bytes
|
|
18
|
+
"""The body exactly as the provider sent it, since providers sign the raw bytes."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, kw_only=True)
|
|
22
|
+
class ReceivedRequest:
|
|
23
|
+
"""A webhook request's headers and raw body, read the same way whichever shape it came in."""
|
|
24
|
+
|
|
25
|
+
headers: httpx.Headers
|
|
26
|
+
"""The request's headers, read case-insensitively."""
|
|
27
|
+
body: str
|
|
28
|
+
"""The request's body, decoded as UTF-8."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, kw_only=True)
|
|
32
|
+
class SourceResponse:
|
|
33
|
+
"""The answer an event source's endpoint sends back to the provider."""
|
|
34
|
+
|
|
35
|
+
status: int
|
|
36
|
+
headers: Mapping[str, str] | None = None
|
|
37
|
+
body: str | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, kw_only=True)
|
|
41
|
+
class ReportedEvent:
|
|
42
|
+
"""An event a provider's webhook reported, to dispatch under `event_keys`."""
|
|
43
|
+
|
|
44
|
+
event_keys: list[str]
|
|
45
|
+
"""The keys of the schedules the event starts runs of."""
|
|
46
|
+
event: TriggerEvent
|
|
47
|
+
"""The event to dispatch."""
|
|
48
|
+
type: Literal["event"] = "event"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True, kw_only=True)
|
|
52
|
+
class RevokedAccount:
|
|
53
|
+
"""An account that lost access with `provider`, such as a workspace that uninstalled the app."""
|
|
54
|
+
|
|
55
|
+
provider: str
|
|
56
|
+
"""The provider whose connections hold the account's grants."""
|
|
57
|
+
revocation: AccountRevocation
|
|
58
|
+
"""The account, and why its access ended."""
|
|
59
|
+
type: Literal["revoked"] = "revoked"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
SourceEvent: TypeAlias = ReportedEvent | RevokedAccount
|
|
63
|
+
"""What a provider's webhook reported: an event to dispatch under its keys, or an account that lost access."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True, kw_only=True)
|
|
67
|
+
class SourceDelivery:
|
|
68
|
+
"""The answer to a webhook request and the events it carried."""
|
|
69
|
+
|
|
70
|
+
response: SourceResponse
|
|
71
|
+
events: list[SourceEvent] = field(default_factory=list)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class EventSource(Protocol):
|
|
75
|
+
"""Reads a provider's webhook requests into events, such as `slack_events()`. Pass one to `agent.receive_events()`.
|
|
76
|
+
|
|
77
|
+
It verifies each request itself, answering one it can't verify with an error response and no events.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
async def receive(self, request: SourceRequest | httpx.Request) -> SourceDelivery:
|
|
81
|
+
"""Verifies a webhook request and reads the events it carries.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
request: The provider's request, as a `SourceRequest` or an `httpx.Request`.
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
The answer to send the provider, and the events to dispatch or revoke.
|
|
88
|
+
"""
|
|
89
|
+
...
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
async def read_source_request(
|
|
93
|
+
request: SourceRequest | httpx.Request,
|
|
94
|
+
) -> ReceivedRequest:
|
|
95
|
+
"""Reads a webhook request's headers and raw body, whichever shape it came in, for an `EventSource` to verify.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
request: An `httpx.Request`, or the headers and raw body a server framework hands over.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
The request's headers and its body as text.
|
|
102
|
+
"""
|
|
103
|
+
if isinstance(request, httpx.Request):
|
|
104
|
+
body: str | bytes = await request.aread()
|
|
105
|
+
headers = request.headers
|
|
106
|
+
else:
|
|
107
|
+
body = request.body
|
|
108
|
+
headers = httpx.Headers(request.headers)
|
|
109
|
+
|
|
110
|
+
return ReceivedRequest(
|
|
111
|
+
headers=headers,
|
|
112
|
+
body=body if isinstance(body, str) else body.decode(errors="replace"),
|
|
113
|
+
)
|