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
@@ -0,0 +1,40 @@
1
+ import asyncio
2
+ from collections.abc import Awaitable, Callable
3
+ from typing import Any
4
+
5
+ from agentjam._utils import spawn
6
+
7
+
8
+ def retrieve(future: asyncio.Future[Any]) -> None:
9
+ """Marks a finished future's error as handled, so asyncio doesn't log it as never retrieved."""
10
+ if not future.cancelled():
11
+ future.exception()
12
+
13
+
14
+ class SerialQueue:
15
+ """Runs steps one at a time, in the order they were queued, whether or not earlier ones failed."""
16
+
17
+ def __init__(self) -> None:
18
+ self._last: asyncio.Task[None] | None = None
19
+
20
+ def enqueue(self, step: Callable[[], Awaitable[None]]) -> asyncio.Task[None]:
21
+ """Queues `step` after every earlier one, returning the task that runs it."""
22
+ task = spawn(self._run_after(self._last, step))
23
+ task.add_done_callback(retrieve)
24
+ self._last = task
25
+
26
+ return task
27
+
28
+ async def wait(self) -> None:
29
+ """Waits for every step queued so far to finish, without raising their errors."""
30
+ if self._last is not None:
31
+ await asyncio.wait([self._last])
32
+
33
+ @staticmethod
34
+ async def _run_after(
35
+ previous: asyncio.Task[None] | None, step: Callable[[], Awaitable[None]]
36
+ ) -> None:
37
+ if previous is not None:
38
+ await asyncio.wait([previous])
39
+
40
+ await step()
@@ -0,0 +1,258 @@
1
+ import asyncio
2
+ from collections.abc import Awaitable, Callable, Sequence
3
+ from dataclasses import dataclass
4
+ from typing import Any
5
+
6
+ from agentjam._errors import AgentJamError
7
+ from agentjam._protocol import TriggerFireDraft, TriggerSubscribeDraft
8
+ from agentjam._tasks.incoming import ConnectionAccess
9
+ from agentjam._tasks.serial import SerialQueue
10
+ from agentjam._types import (
11
+ Account,
12
+ ConnectionFetch,
13
+ SkillHandler,
14
+ StopReason,
15
+ TriggerActivation,
16
+ TriggerEvent,
17
+ TriggerHandler,
18
+ TriggerSchedule,
19
+ )
20
+ from agentjam._utils import create_id, resolve_value, spawn
21
+
22
+ STOP_TIMEOUT = 30.0
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class TriggerLink:
27
+ post: Callable[[TriggerFireDraft | TriggerSubscribeDraft], Awaitable[None]]
28
+ access_of: Callable[[TriggerSchedule], ConnectionAccess]
29
+ on_error: Callable[[Exception], None]
30
+
31
+
32
+ class Watch:
33
+ def __init__(self) -> None:
34
+ self.stopped = False
35
+ self.activation: asyncio.Task[TriggerActivation | None] | None = None
36
+
37
+
38
+ class ScheduleContext:
39
+ """What a trigger's `on_schedule_active` can use on behalf of its schedule."""
40
+
41
+ def __init__(
42
+ self, access: ConnectionAccess, fire: Callable[[TriggerEvent], Awaitable[None]]
43
+ ) -> None:
44
+ self._access = access
45
+ self._fire = fire
46
+
47
+ async def fire(self, event: TriggerEvent) -> None:
48
+ await self._fire(event)
49
+
50
+ async def credentials(self, provider: str, name: str | None = None) -> str:
51
+ return await self._access.credentials(provider, name)
52
+
53
+ async def account(self, provider: str) -> Account | None:
54
+ return await self._access.account(provider)
55
+
56
+ def connection_fetch(self, provider: str) -> ConnectionFetch:
57
+ return self._access.connection_fetch(provider)
58
+
59
+ async def connection_config(self, provider: str) -> dict[str, str]:
60
+ return await self._access.connection_config(provider)
61
+
62
+
63
+ def compute_key(requester: str, schedule_id: str) -> str:
64
+ return f"{requester}/{schedule_id}"
65
+
66
+
67
+ class TriggerRunner:
68
+ """Activates the triggers of the schedules this agent executes, until each schedule ends or this agent closes.
69
+
70
+ Each trigger runs from when its schedule becomes active or this agent connects, and dropped connections don't stop it.
71
+ Invariant: `watches` holds every schedule whose `on_schedule_active` was called and hasn't stopped or raised.
72
+ """
73
+
74
+ def __init__(
75
+ self, skills: Sequence[SkillHandler[Any, Any]], link: TriggerLink
76
+ ) -> None:
77
+ self._skills = skills
78
+ self._link = link
79
+ self._watches: dict[str, Watch] = {}
80
+ self._syncing = SerialQueue()
81
+ self._endings: list[set[str]] = []
82
+ """For each pending sync, the schedules that ended since it was requested, which it mustn't restart."""
83
+
84
+ @property
85
+ def declared(self) -> bool:
86
+ """Whether any skill declares a trigger."""
87
+ return any(skill.triggers for skill in self._skills)
88
+
89
+ def offers(self, skill: str | None, trigger: str) -> bool:
90
+ return self._find_trigger(skill, trigger) is not None
91
+
92
+ def activate(self, schedule: TriggerSchedule) -> None:
93
+ """Activates the schedule's trigger, unless this session already watches the schedule."""
94
+ key = compute_key(schedule.sender, schedule.id)
95
+ if key in self._watches:
96
+ return
97
+
98
+ trigger = self._find_trigger(schedule.skill, schedule.trigger)
99
+ if trigger is None:
100
+ self._link.on_error(
101
+ AgentJamError(
102
+ f'Schedule {schedule.id} runs on the "{schedule.trigger}" trigger, which the "{schedule.skill}" skill doesn\'t declare'
103
+ )
104
+ )
105
+
106
+ return
107
+
108
+ watch = Watch()
109
+
110
+ async def fire(event: TriggerEvent) -> None:
111
+ if watch.stopped:
112
+ return
113
+
114
+ await self._link.post(
115
+ TriggerFireDraft(
116
+ id=create_id(),
117
+ to=schedule.sender,
118
+ schedule_id=schedule.id,
119
+ event_id=event.id,
120
+ summary=event.summary,
121
+ data=event.data,
122
+ )
123
+ )
124
+
125
+ context = ScheduleContext(self._link.access_of(schedule), fire)
126
+ self._watches[key] = watch
127
+ watch.activation = spawn(
128
+ self._run_activation(key, watch, trigger, schedule, context)
129
+ )
130
+ spawn(self._subscribe(schedule, watch))
131
+
132
+ async def stop(self, requester: str, schedule_id: str, reason: StopReason) -> bool:
133
+ """Stops watching the schedule `schedule_id` that `requester` requested, waiting up to 30 seconds for its `stop`.
134
+
135
+ Returns whether this session watched the schedule.
136
+ """
137
+ key = compute_key(requester, schedule_id)
138
+ for ended in self._endings:
139
+ ended.add(key)
140
+
141
+ return await self._halt(key, reason)
142
+
143
+ async def stop_all(self, reason: StopReason) -> None:
144
+ await asyncio.gather(*(self._halt(key, reason) for key in list(self._watches)))
145
+
146
+ def sync(
147
+ self, list_schedules: Callable[[], Awaitable[list[TriggerSchedule] | None]]
148
+ ) -> asyncio.Task[None]:
149
+ """Activates the triggers of the listed schedules, and stops watching those that were watched but aren't listed.
150
+
151
+ A `list_schedules` that returns None can't list schedules, so nothing changes.
152
+ """
153
+ ended: set[str] = set()
154
+ self._endings.append(ended)
155
+
156
+ return self._syncing.enqueue(lambda: self._reconcile(list_schedules, ended))
157
+
158
+ async def _run_activation(
159
+ self,
160
+ key: str,
161
+ watch: Watch,
162
+ trigger: TriggerHandler,
163
+ schedule: TriggerSchedule,
164
+ context: ScheduleContext,
165
+ ) -> TriggerActivation | None:
166
+ try:
167
+ return await resolve_value(trigger.on_schedule_active(schedule, context))
168
+ except Exception as error:
169
+ if self._watches.get(key) is watch:
170
+ del self._watches[key]
171
+
172
+ self._link.on_error(error)
173
+
174
+ return None
175
+
176
+ async def _subscribe(self, schedule: TriggerSchedule, watch: Watch) -> None:
177
+ assert watch.activation is not None, (
178
+ "A watch's activation starts before it subscribes"
179
+ )
180
+ activation = await watch.activation
181
+ if activation is None or activation.event_keys is None or watch.stopped:
182
+ return
183
+
184
+ try:
185
+ await self._link.post(
186
+ TriggerSubscribeDraft(
187
+ id=create_id(),
188
+ to=schedule.sender,
189
+ schedule_id=schedule.id,
190
+ event_keys=activation.event_keys,
191
+ )
192
+ )
193
+ except Exception as error:
194
+ self._link.on_error(error)
195
+
196
+ async def _reconcile(
197
+ self,
198
+ list_schedules: Callable[[], Awaitable[list[TriggerSchedule] | None]],
199
+ ended: set[str],
200
+ ) -> None:
201
+ running = set(self._watches)
202
+
203
+ try:
204
+ schedules = await list_schedules()
205
+ if schedules is None:
206
+ return
207
+
208
+ listed = {
209
+ compute_key(schedule.sender, schedule.id) for schedule in schedules
210
+ }
211
+ for schedule in schedules:
212
+ if compute_key(schedule.sender, schedule.id) not in ended:
213
+ self.activate(schedule)
214
+
215
+ await asyncio.gather(
216
+ *(self._halt(key, "handover") for key in running if key not in listed)
217
+ )
218
+ except Exception as error:
219
+ self._link.on_error(error)
220
+ finally:
221
+ self._endings = [
222
+ pending for pending in self._endings if pending is not ended
223
+ ]
224
+
225
+ async def _halt(self, key: str, reason: StopReason) -> bool:
226
+ watch = self._watches.pop(key, None)
227
+ if watch is None:
228
+ return False
229
+
230
+ watch.stopped = True
231
+ stopping = spawn(self._stop_activation(watch, reason))
232
+ _, pending = await asyncio.wait([stopping], timeout=STOP_TIMEOUT)
233
+ if pending:
234
+ self._link.on_error(
235
+ AgentJamError(
236
+ f"The trigger of schedule {key} didn't stop within {STOP_TIMEOUT:g} seconds"
237
+ )
238
+ )
239
+
240
+ return True
241
+
242
+ async def _stop_activation(self, watch: Watch, reason: StopReason) -> None:
243
+ try:
244
+ assert watch.activation is not None, (
245
+ "A watch's activation starts once it's stored"
246
+ )
247
+ activation = await watch.activation
248
+ if activation is not None and activation.stop is not None:
249
+ await resolve_value(activation.stop(reason))
250
+ except Exception as error:
251
+ self._link.on_error(error)
252
+
253
+ def _find_trigger(self, skill: str | None, trigger: str) -> TriggerHandler | None:
254
+ handler = next((known for known in self._skills if known.name == skill), None)
255
+ if handler is None or handler.triggers is None:
256
+ return None
257
+
258
+ return handler.triggers.get(trigger)
@@ -0,0 +1,77 @@
1
+ from collections.abc import Awaitable, Callable
2
+ from dataclasses import dataclass, field
3
+
4
+ from agentjam._tasks.outgoing import OutgoingTask
5
+ from agentjam._types import CompletedOutcome, FailedOutcome, TaskOutcome, TaskWatch
6
+ from agentjam._utils import spawn
7
+
8
+
9
+ @dataclass
10
+ class Group:
11
+ """Invariant: a group holds the keys of its open tasks and the outcomes of its ended ones, and is dropped once none are open."""
12
+
13
+ open: set[str] = field(default_factory=set)
14
+ outcomes: list[TaskOutcome] = field(default_factory=list)
15
+
16
+
17
+ async def settle_outcome(
18
+ agent: str, task_id: str, proposal: Awaitable[OutgoingTask]
19
+ ) -> TaskOutcome:
20
+ try:
21
+ task = await proposal
22
+
23
+ return CompletedOutcome(
24
+ task_id=task_id, agent=agent, artifacts=await task.result()
25
+ )
26
+ except Exception as error:
27
+ return FailedOutcome(task_id=task_id, agent=agent, error=error)
28
+
29
+
30
+ class TaskWatches:
31
+ """Follows watched tasks from their proposal on, resolving each on its own, or each group once its last task ends."""
32
+
33
+ def __init__(self, resolve: Callable[[list[TaskOutcome]], None]) -> None:
34
+ self._resolve = resolve
35
+ self._groups: dict[str, Group] = {}
36
+ self._watched: set[str] = set()
37
+
38
+ def watch(
39
+ self,
40
+ agent: str,
41
+ task_id: str,
42
+ proposal: Awaitable[OutgoingTask],
43
+ watch: TaskWatch,
44
+ ) -> None:
45
+ """Follows the task proposed to `agent` as `task_id`, counting a rejected proposal as a failed task."""
46
+ key = f"{agent}/{task_id}"
47
+ if watch is False or key in self._watched:
48
+ return
49
+
50
+ self._watched.add(key)
51
+ outcome = settle_outcome(agent, task_id, proposal)
52
+
53
+ if watch is True:
54
+ spawn(self._resolve_alone(key, outcome))
55
+ return
56
+
57
+ group = self._groups.setdefault(watch, Group())
58
+ group.open.add(key)
59
+ spawn(self._settle_group(watch, group, key, outcome))
60
+
61
+ async def _resolve_alone(self, key: str, outcome: Awaitable[TaskOutcome]) -> None:
62
+ ended = await outcome
63
+ self._watched.discard(key)
64
+ self._resolve([ended])
65
+
66
+ async def _settle_group(
67
+ self, name: str, group: Group, key: str, outcome: Awaitable[TaskOutcome]
68
+ ) -> None:
69
+ ended = await outcome
70
+ self._watched.discard(key)
71
+ group.open.discard(key)
72
+ group.outcomes.append(ended)
73
+ if group.open:
74
+ return
75
+
76
+ self._groups.pop(name, None)
77
+ self._resolve(group.outcomes)