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,376 @@
1
+ import asyncio
2
+ from collections.abc import Awaitable, Callable, Coroutine, Sequence, Set
3
+ from dataclasses import dataclass
4
+ from typing import Any
5
+
6
+ from agentjam._agent_support import compute_key, construct_event, is_run, list_actions
7
+ from agentjam._errors import FollowUpFailedError, TaskFailedError, TaskRejectedError
8
+ from agentjam._protocol import (
9
+ AcceptEnvelope,
10
+ ActionsEnvelope,
11
+ CancelEnvelope,
12
+ CollectDraft,
13
+ CompleteEnvelope,
14
+ ConnectionReadyEnvelope,
15
+ ConnectionRequiredEnvelope,
16
+ ErrorEnvelope,
17
+ FailEnvelope,
18
+ FollowUpEnvelope,
19
+ ParentRef,
20
+ ReattachDraft,
21
+ RecurEnvelope,
22
+ RejectEnvelope,
23
+ Reply,
24
+ RequireEnvelope,
25
+ ScheduleEndEnvelope,
26
+ TaskEnvelope,
27
+ )
28
+ from agentjam._relay.base import Draft
29
+ from agentjam._tasks.incoming import TaskSender
30
+ from agentjam._tasks.outgoing import OutgoingTask, RunDetails, TaskHandle, TaskLink
31
+ from agentjam._tasks.scheduled import ScheduleHandle, ScheduleLink
32
+ from agentjam._types import ActionRequest, ProposalAction
33
+ from agentjam._utils import create_id, spawn
34
+
35
+ WITHDRAWN = "The proposal is no longer pending"
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class DelegationLink:
40
+ name: str
41
+ post: Callable[[Draft], Awaitable[None]]
42
+ send_about: Callable[[str, str], TaskSender]
43
+ """Builds how a task's handle messages the agent on its other side."""
44
+ hand_run: Callable[[OutgoingTask], Coroutine[Any, Any, None]]
45
+ """Passes a run no `Schedule` follows to `on_run`, reporting what it raises."""
46
+ hand_follow_up: Callable[[OutgoingTask], Coroutine[Any, Any, None]]
47
+ """Passes a follow-up no `Schedule` follows to `on_follow_up`, reporting what it raises."""
48
+ request_actions: Callable[[ActionRequest], None]
49
+ on_error: Callable[[Exception], None]
50
+
51
+
52
+ class Delegations:
53
+ """The tasks and schedules this agent delegated, which follow what their executors send back."""
54
+
55
+ def __init__(self, link: DelegationLink) -> None:
56
+ self.schedules: dict[str, ScheduleHandle] = {}
57
+ self._outgoing: dict[str, TaskHandle] = {}
58
+ self._scheduling: set[str] = set()
59
+ self._link = link
60
+
61
+ def find(self, executor: str, task_id: str) -> TaskHandle | None:
62
+ return self._outgoing.get(compute_key(executor, task_id))
63
+
64
+ def track(
65
+ self,
66
+ to: str,
67
+ task_id: str,
68
+ *,
69
+ attempt: str | None = None,
70
+ actions: Sequence[ProposalAction] = (),
71
+ run: RunDetails | None = None,
72
+ parent: ParentRef | None = None,
73
+ ) -> TaskHandle:
74
+ """Follows the task `task_id` delegated to `to`, restarting the existing handle on a new `attempt`."""
75
+ id = compute_key(to, task_id)
76
+ if (existing := self._outgoing.get(id)) is not None:
77
+ if attempt is not None:
78
+ existing.restart(attempt, actions)
79
+
80
+ return existing
81
+
82
+ def release() -> None:
83
+ self._outgoing.pop(id, None)
84
+
85
+ handle = TaskHandle(
86
+ task_id,
87
+ to,
88
+ attempt,
89
+ TaskLink(
90
+ post=self._link.post,
91
+ send=self._link.send_about(to, task_id),
92
+ release=release,
93
+ ),
94
+ run=run,
95
+ parent=parent,
96
+ actions=actions,
97
+ )
98
+
99
+ self._outgoing[id] = handle
100
+
101
+ return handle
102
+
103
+ def track_accepted(
104
+ self, verdict: AcceptEnvelope | RequireEnvelope, parent: ParentRef | None = None
105
+ ) -> TaskHandle:
106
+ return self.track(
107
+ verdict.sender,
108
+ verdict.reply_to,
109
+ attempt=verdict.id,
110
+ actions=list_actions(verdict),
111
+ parent=parent,
112
+ )
113
+
114
+ def begin_scheduling(self, executor: str, schedule_id: str) -> None:
115
+ self._scheduling.add(compute_key(executor, schedule_id))
116
+
117
+ def end_scheduling(self, executor: str, schedule_id: str) -> None:
118
+ self._scheduling.discard(compute_key(executor, schedule_id))
119
+
120
+ def follow(
121
+ self,
122
+ to: str,
123
+ schedule_id: str,
124
+ actions: list[ProposalAction],
125
+ parent: ParentRef | None = None,
126
+ ) -> ScheduleHandle:
127
+ """Follows the accepted schedule `schedule_id` delegated to `to`."""
128
+ id = compute_key(to, schedule_id)
129
+
130
+ def hand(run: OutgoingTask) -> None:
131
+ self.collect_after(run, schedule_id)
132
+
133
+ def release() -> None:
134
+ self.schedules.pop(id, None)
135
+
136
+ schedule = ScheduleHandle(
137
+ schedule_id,
138
+ to,
139
+ ScheduleLink(post=self._link.post, hand=hand, release=release),
140
+ actions,
141
+ parent,
142
+ )
143
+
144
+ self.schedules[id] = schedule
145
+
146
+ return schedule
147
+
148
+ async def restart(self, verdict: AcceptEnvelope | RequireEnvelope) -> None:
149
+ """Restarts the task a repeated acceptance answers, or withdraws a proposal nothing awaits anymore."""
150
+ task = self.find(verdict.sender, verdict.reply_to)
151
+ if task is not None:
152
+ await task.restart(verdict.id, list_actions(verdict))
153
+ return
154
+
155
+ await self._withdraw(verdict.sender, verdict.reply_to)
156
+
157
+ def refuse(self, verdict: ErrorEnvelope | RejectEnvelope) -> None:
158
+ """Fails the task or closes the schedule an executor refused after accepting it."""
159
+ id = compute_key(verdict.sender, verdict.reply_to)
160
+ error = (
161
+ TaskFailedError(verdict.error)
162
+ if isinstance(verdict, ErrorEnvelope)
163
+ else TaskRejectedError(verdict.sender, verdict.reason)
164
+ )
165
+
166
+ if (task := self._outgoing.get(id)) is not None:
167
+ task.fail(error)
168
+
169
+ if (schedule := self.schedules.get(id)) is not None:
170
+ schedule.close(str(error))
171
+
172
+ async def progress(self, envelope: TaskEnvelope) -> TaskHandle | None:
173
+ """Passes an executor's progress to the task's handle, returning it, or cancels a task nothing tracks."""
174
+ task = self.find(envelope.sender, envelope.task_id)
175
+ if task is not None:
176
+ await task.receive(envelope)
177
+ return task
178
+
179
+ if isinstance(envelope, CompleteEnvelope | FailEnvelope):
180
+ return None
181
+
182
+ await self._link.post(
183
+ CancelEnvelope(
184
+ id=create_id(),
185
+ to=envelope.sender,
186
+ task_id=envelope.task_id,
187
+ reason=f"{self._link.name} is no longer tracking this task",
188
+ )
189
+ )
190
+
191
+ return None
192
+
193
+ def abandon(self, peer: str, abandoned: Set[str] | None) -> None:
194
+ """Fails the tasks delegated to a disconnected peer, or only those among `abandoned`."""
195
+ for task in list(self._outgoing.values()):
196
+ if task.to == peer and (abandoned is None or task.id in abandoned):
197
+ task.fail(TaskFailedError(f"{peer} disconnected"))
198
+
199
+ def close_schedule(self, envelope: ScheduleEndEnvelope) -> None:
200
+ schedule = self.schedules.get(
201
+ compute_key(envelope.sender, envelope.schedule_id)
202
+ )
203
+ if schedule is None:
204
+ return
205
+
206
+ schedule.close(
207
+ envelope.reason
208
+ if envelope.reason is not None
209
+ else f"{envelope.sender} ended the schedule"
210
+ )
211
+
212
+ def complete(self, envelope: ConnectionReadyEnvelope) -> None:
213
+ """Marks the human's action for the envelope's provider as taken."""
214
+ id = compute_key(envelope.sender, envelope.proposal_id)
215
+ if (task := self._outgoing.get(id)) is not None:
216
+ task.complete(envelope.provider)
217
+
218
+ if (schedule := self.schedules.get(id)) is not None:
219
+ schedule.complete(envelope.provider, envelope.origin)
220
+
221
+ def require(self, peer: str, verdict: Reply) -> None:
222
+ """Asks the human for the actions an accepted proposal still waits on."""
223
+ if not isinstance(verdict, RequireEnvelope):
224
+ return
225
+
226
+ self._link.request_actions(
227
+ ActionRequest(
228
+ peer=peer, proposal_id=verdict.reply_to, actions=verdict.actions
229
+ )
230
+ )
231
+
232
+ def require_access(self, envelope: ConnectionRequiredEnvelope) -> None:
233
+ """Asks the human for access a running delegated task or schedule lacks."""
234
+ id = compute_key(envelope.sender, envelope.proposal_id)
235
+ awaiting = self._outgoing.get(id) or self.schedules.get(id)
236
+ action = ProposalAction(
237
+ kind="oauth",
238
+ provider=envelope.provider,
239
+ url=envelope.url,
240
+ reason=envelope.reason,
241
+ )
242
+
243
+ if awaiting is None or not awaiting.require_access(action) or awaiting.parent:
244
+ return
245
+
246
+ self._link.request_actions(
247
+ ActionRequest(
248
+ peer=envelope.sender, proposal_id=envelope.proposal_id, actions=[action]
249
+ )
250
+ )
251
+
252
+ def inherit(self, envelope: ActionsEnvelope) -> None:
253
+ """Takes on the actions a delegated task's own delegates wait on."""
254
+ task = self.find(envelope.sender, envelope.task_id)
255
+ pending = [] if task is None else task.inherit(envelope.actions)
256
+ if (task is not None and task.parent) or not pending:
257
+ return
258
+
259
+ self._link.request_actions(
260
+ ActionRequest(
261
+ peer=envelope.sender, proposal_id=envelope.task_id, actions=pending
262
+ )
263
+ )
264
+
265
+ def notice(self, executor: str, notice: RecurEnvelope) -> TaskHandle:
266
+ """Follows a run of one of this agent's schedules, which its `Schedule` or `on_run` receives."""
267
+ if (existing := self.find(executor, notice.task_id)) is not None:
268
+ return existing
269
+
270
+ schedule = self.schedules.get(compute_key(executor, notice.schedule_id))
271
+ run = self.track(
272
+ executor,
273
+ notice.task_id,
274
+ attempt=notice.id,
275
+ run=RunDetails(notice.schedule_id, construct_event(notice)),
276
+ parent=None if schedule is None else schedule.parent,
277
+ )
278
+
279
+ if schedule is not None:
280
+ schedule.add(run)
281
+ else:
282
+ handled = spawn(self._link.hand_run(run))
283
+ self.collect_after(run, notice.schedule_id, handled)
284
+
285
+ return run
286
+
287
+ def follow_up(self, notice: FollowUpEnvelope) -> None:
288
+ """Follows a follow-up the relay proposed after a run, which its `Schedule` or `on_follow_up` receives."""
289
+ if notice.error is not None:
290
+ self._link.on_error(
291
+ FollowUpFailedError(
292
+ notice.sender, notice.schedule_id, notice.run_id, notice.error
293
+ )
294
+ )
295
+ return
296
+
297
+ assert notice.task_id is not None, "A follow-up without an error names its task"
298
+ task = self.track(notice.sender, notice.task_id)
299
+ schedule = next(
300
+ (
301
+ schedule
302
+ for schedule in self.schedules.values()
303
+ if schedule.id == notice.schedule_id
304
+ ),
305
+ None,
306
+ )
307
+
308
+ if schedule is not None:
309
+ schedule.add_follow_up(task)
310
+ else:
311
+ spawn(self._link.hand_follow_up(task))
312
+
313
+ def collect_after(
314
+ self,
315
+ run: OutgoingTask,
316
+ schedule_id: str,
317
+ handled: Awaitable[None] | None = None,
318
+ ) -> None:
319
+ """Tells the relay it may forget a run once it ended and `handled` finished."""
320
+ spawn(self._collect_when_settled(run, schedule_id, handled))
321
+
322
+ def list_delegated(self) -> list[TaskHandle]:
323
+ """Lists the delegated tasks that aren't runs, since the relay keeps runs going and replays them on reconnecting."""
324
+ return [task for task in self._outgoing.values() if not is_run(task)]
325
+
326
+ def fail_delegated(self, error: Exception) -> None:
327
+ for task in self.list_delegated():
328
+ task.fail(error)
329
+
330
+ def reattach_delegated(self) -> None:
331
+ for task in self.list_delegated():
332
+ spawn(self.reattach(task))
333
+
334
+ async def reattach(self, task: TaskHandle) -> None:
335
+ """Asks the task's executor to replay what it sent, failing the handle if the request can't be sent."""
336
+ try:
337
+ await self._link.post(
338
+ ReattachDraft(id=create_id(), to=task.to, task_id=task.id)
339
+ )
340
+ except Exception as error:
341
+ task.fail(error)
342
+
343
+ async def _withdraw(self, executor: str, proposal_id: str) -> None:
344
+ id = compute_key(executor, proposal_id)
345
+ if id not in self._scheduling:
346
+ await self._link.post(
347
+ CancelEnvelope(
348
+ id=create_id(), to=executor, task_id=proposal_id, reason=WITHDRAWN
349
+ )
350
+ )
351
+ return
352
+
353
+ self._scheduling.discard(id)
354
+ await self._link.post(
355
+ ScheduleEndEnvelope(
356
+ id=create_id(), to=executor, schedule_id=proposal_id, reason=WITHDRAWN
357
+ )
358
+ )
359
+
360
+ async def _collect_when_settled(
361
+ self, run: OutgoingTask, schedule_id: str, handled: Awaitable[None] | None
362
+ ) -> None:
363
+ await asyncio.gather(
364
+ run.result(),
365
+ *([] if handled is None else [handled]),
366
+ return_exceptions=True,
367
+ )
368
+
369
+ try:
370
+ await self._link.post(
371
+ CollectDraft(
372
+ id=create_id(), to=run.to, schedule_id=schedule_id, task_id=run.id
373
+ )
374
+ )
375
+ except Exception as error:
376
+ self._link.on_error(error)