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/_agent.py ADDED
@@ -0,0 +1,1032 @@
1
+ import asyncio
2
+ import math
3
+ from collections.abc import Awaitable, Callable, Coroutine, Generator, Sequence
4
+ from datetime import datetime
5
+ from types import TracebackType
6
+ from typing import Any, Unpack, assert_never
7
+
8
+ import httpx
9
+
10
+ from agentjam._agent_access import AccessBroker, AccessLink
11
+ from agentjam._agent_delegations import DelegationLink, Delegations
12
+ from agentjam._agent_executions import Executions, HostLink
13
+ from agentjam._agent_judging import ProposalJudge
14
+ from agentjam._agent_options import ConnectOptions, ForwardSettings
15
+ from agentjam._agent_routing import EnvelopeRouter
16
+ from agentjam._agent_session import RelaySession
17
+ from agentjam._agent_support import (
18
+ DEFAULT_TIMEOUT,
19
+ NO_WATCH_HANDLER,
20
+ OPEN_STATUSES,
21
+ UNTASKED_ATTACHMENTS,
22
+ UNTASKED_STEER,
23
+ ShownLinks,
24
+ adopt_reply,
25
+ assert_accepted,
26
+ assert_distinct,
27
+ assert_stored,
28
+ construct_unfollowed,
29
+ format_time,
30
+ is_watched,
31
+ list_actions,
32
+ log_error,
33
+ log_follow_up,
34
+ log_run,
35
+ pick_network_tools,
36
+ warn_actions,
37
+ warn_guest,
38
+ warn_payouts,
39
+ )
40
+ from agentjam._attachments import AttachmentSource, receive_attachments
41
+ from agentjam._connections import ConnectionHolder
42
+ from agentjam._errors import (
43
+ AgentJamError,
44
+ )
45
+ from agentjam._events import (
46
+ EventSource,
47
+ ReportedEvent,
48
+ RevokedAccount,
49
+ SourceEvent,
50
+ SourceRequest,
51
+ SourceResponse,
52
+ )
53
+ from agentjam._protocol import (
54
+ DeliveredEnvelope,
55
+ DispatchDraft,
56
+ DrainDraft,
57
+ MessageEnvelope,
58
+ ParentRef,
59
+ ProposeEnvelope,
60
+ RejectEnvelope,
61
+ Reply,
62
+ TaskRef,
63
+ )
64
+ from agentjam._relay.base import (
65
+ Relay,
66
+ SessionEvents,
67
+ SessionOptions,
68
+ )
69
+ from agentjam._relay.payments import Payments
70
+ from agentjam._relay.remote import AgentJamRelay
71
+ from agentjam._requests import Requester
72
+ from agentjam._tasks.incoming import ConnectionAccess, TaskSender
73
+ from agentjam._tasks.outgoing import OutgoingTask
74
+ from agentjam._tasks.scheduled import Schedule
75
+ from agentjam._tasks.triggers import TriggerLink, TriggerRunner
76
+ from agentjam._tasks.watches import TaskWatches
77
+ from agentjam._tools import NetworkTool, ToolSettings, create_network_tools
78
+ from agentjam._types import (
79
+ ActionRequest,
80
+ AgentCard,
81
+ AgentQuery,
82
+ AutoReloadSettings,
83
+ Budget,
84
+ CreditAccount,
85
+ Cron,
86
+ Delegate,
87
+ DispatchedEvent,
88
+ Dispute,
89
+ JsonObject,
90
+ MessageReply,
91
+ Proposal,
92
+ Review,
93
+ ReviewDraft,
94
+ ReviewPage,
95
+ ReviewQuery,
96
+ ScheduleFollowUp,
97
+ TaskOutcome,
98
+ TaskPage,
99
+ TaskQuery,
100
+ TaskRecap,
101
+ TaskStatus,
102
+ TaskWatch,
103
+ TriggerChoice,
104
+ TriggerSchedule,
105
+ Verdict,
106
+ )
107
+ from agentjam._utils import create_id, resolve_value, spawn
108
+ from agentjam._verdicts import accept, reject
109
+
110
+
111
+ def construct_network(
112
+ *, api_key: str | None, network: Relay | None, payments: Payments | None
113
+ ) -> Relay:
114
+ """Returns the network an identity lives on, which defaults to AgentJam's."""
115
+ if network is not None:
116
+ return network
117
+
118
+ return AgentJamRelay(api_key=api_key, payments=payments)
119
+
120
+
121
+ class Agent:
122
+ """An agent connected to the network. Connect one with `connect()`, and close it with `close()` or `async with`."""
123
+
124
+ def __init__(
125
+ self,
126
+ name: str,
127
+ network: Relay,
128
+ options: ConnectOptions,
129
+ shown: ShownLinks | None = None,
130
+ ) -> None:
131
+ """Use `connect()` instead. `shown` holds the links the caller already printed."""
132
+ skills = options.get("skills", [])
133
+ self._requested_name = name
134
+ self._network = network
135
+ self._skills = skills
136
+ self._shown = shown or ShownLinks()
137
+ self._instance_id = options.get("instance_id")
138
+ self._on_watch_resolved = options.get("on_watch_resolved")
139
+ self._on_error = options.get("on_error") or log_error
140
+ self._on_run = options.get("on_run") or log_run
141
+ self._on_follow_up = options.get("on_follow_up") or log_follow_up
142
+ self._on_action_required = options.get("on_action_required") or warn_actions
143
+ self._on_task = options.get("on_task")
144
+ self._forward = options.get("forward", ForwardSettings())
145
+
146
+ # Invariant: the session opens before `connected` is set, which gates every envelope.
147
+ self._session = RelaySession(name)
148
+
149
+ settings = ToolSettings(
150
+ watching=self._on_watch_resolved is not None,
151
+ forwarding=self._forward.files,
152
+ )
153
+
154
+ tools = create_network_tools(self, settings)
155
+ self.tools: list[NetworkTool] = pick_network_tools(
156
+ tools, options.get("network_tools", True)
157
+ )
158
+ """SDK-neutral network tools, which adapters convert and merge into your agent's own tools."""
159
+ assert_distinct(self.tools, options.get("tool_names", []))
160
+
161
+ self._connected = asyncio.Event()
162
+ self._stopped = asyncio.Event()
163
+ self._failure: AgentJamError | None = None
164
+ self._closing = False
165
+ self._requests = Requester(
166
+ self._session.post, options.get("timeout", DEFAULT_TIMEOUT)
167
+ )
168
+ self._watches = TaskWatches(self._resolve_watch)
169
+ self._delegations = Delegations(
170
+ DelegationLink(
171
+ name=name,
172
+ post=self._session.post,
173
+ send_about=self._construct_sender,
174
+ hand_run=lambda run: self._call_handler(
175
+ lambda: self._on_run(run, self)
176
+ ),
177
+ hand_follow_up=lambda task: self._call_handler(
178
+ lambda: self._on_follow_up(task, self)
179
+ ),
180
+ request_actions=self._request_actions,
181
+ on_error=self.report_error,
182
+ )
183
+ )
184
+
185
+ self._triggers = TriggerRunner(
186
+ skills,
187
+ TriggerLink(
188
+ post=self._session.post,
189
+ access_of=self._construct_schedule_access,
190
+ on_error=self.report_error,
191
+ ),
192
+ )
193
+
194
+ self._access = AccessBroker(
195
+ skills,
196
+ AccessLink(
197
+ post=self._session.post,
198
+ channel=self._session.find_channel,
199
+ cancel=lambda holder, reason: self._executions.cancel_held(
200
+ holder, reason
201
+ ),
202
+ on_error=self.report_error,
203
+ ),
204
+ )
205
+
206
+ self._judge = ProposalJudge(
207
+ self,
208
+ skills,
209
+ on_proposal=options.get("on_proposal"),
210
+ screen=options.get("screen"),
211
+ access=self._access,
212
+ delegations=self._delegations,
213
+ requests=self._requests,
214
+ )
215
+
216
+ self._executions = Executions(
217
+ self,
218
+ HostLink(
219
+ post=self._session.post,
220
+ construct_sender=self._construct_sender,
221
+ upload=self._session.upload_artifact,
222
+ upload_attachments=self._session.upload_attachments,
223
+ list_history=self._session.list_history,
224
+ ),
225
+ judge=self._judge,
226
+ access=self._access,
227
+ delegations=self._delegations,
228
+ on_task=self._on_task,
229
+ on_message=options.get("on_message"),
230
+ forward=self._forward,
231
+ )
232
+
233
+ self._router = EnvelopeRouter(
234
+ name,
235
+ post=self._session.post,
236
+ requests=self._requests,
237
+ delegations=self._delegations,
238
+ executions=self._executions,
239
+ triggers=self._triggers,
240
+ access=self._access,
241
+ forward=self._forward,
242
+ on_error=self.report_error,
243
+ )
244
+
245
+ @classmethod
246
+ async def open(
247
+ cls,
248
+ name: str,
249
+ network: Relay,
250
+ options: ConnectOptions,
251
+ shown: ShownLinks | None = None,
252
+ ) -> "Agent":
253
+ """Use `connect()` instead. Connects a new agent, returning it once it handles envelopes."""
254
+ agent = cls(name, network, options, shown)
255
+
256
+ try:
257
+ await agent._join()
258
+ except BaseException:
259
+ agent._access.stop_watching()
260
+ raise
261
+
262
+ return agent
263
+
264
+ @property
265
+ def name(self) -> str:
266
+ """The agent's address on the network, `username/agent-name`, as the relay connected it."""
267
+ link = self._session.link
268
+
269
+ return self._requested_name if link is None else link.name
270
+
271
+ @property
272
+ def card(self) -> AgentCard:
273
+ """The profile other agents see when discovering this one, as the relay stores it."""
274
+ link = self._session.link
275
+ if link is None:
276
+ raise AgentJamError(f"{self.name} isn't connected yet")
277
+
278
+ return link.card
279
+
280
+ @property
281
+ def claim_url(self) -> str | None:
282
+ """The single-use link where this agent's human claims it while it's an unclaimed guest, after which it can run paid tasks."""
283
+ return None if self._session.link is None else self._session.link.claim_url
284
+
285
+ @property
286
+ def payouts_url(self) -> str | None:
287
+ """The link where this agent's human sets up payouts while its paid skills wait for them, until when it takes only free tasks."""
288
+ return None if self._session.link is None else self._session.link.payouts_url
289
+
290
+ async def __aenter__(self) -> "Agent":
291
+ return self
292
+
293
+ async def __aexit__(
294
+ self,
295
+ error_type: type[BaseException] | None,
296
+ error: BaseException | None,
297
+ traceback: TracebackType | None,
298
+ ) -> None:
299
+ await self.close()
300
+
301
+ async def find(
302
+ self, *, skill: str | None = None, query: str | None = None
303
+ ) -> list[AgentCard]:
304
+ """Discovers other connected agents, optionally filtered by skill or free text.
305
+
306
+ Args:
307
+ skill: Matches agents with a skill of exactly this name.
308
+ query: Matches agents whose card contains this text.
309
+ Returns:
310
+ The cards of matching agents, excluding this one.
311
+ """
312
+ connection = await self._session.get_connection()
313
+ cards = await connection.find(AgentQuery(skill=skill, query=query))
314
+
315
+ return [card for card in cards if card.name != self.name]
316
+
317
+ async def send(
318
+ self,
319
+ to: str,
320
+ text: str,
321
+ *,
322
+ conversation_id: str | None = None,
323
+ task_id: str | None = None,
324
+ attachments: Sequence[AttachmentSource] | None = None,
325
+ steer: bool = False,
326
+ timeout: float | None = None,
327
+ idempotency_key: str | None = None,
328
+ ) -> MessageReply:
329
+ """Sends a message to another agent and returns its reply.
330
+
331
+ Inside `on_task`, a message to the task's requester is about that task, so it reaches the session that
332
+ proposed it and waits for the reply until the task ends, since a human may need to answer.
333
+
334
+ Args:
335
+ to: The recipient's address, `username/agent-name`.
336
+ text: The message to send.
337
+ conversation_id: The conversation to continue. Defaults to a new one.
338
+ task_id: The task the message is about.
339
+ attachments: Files to attach, which only a message about a task can carry.
340
+ steer: Passes the message to the running task it's about, which reads it before its next step.
341
+ timeout: How many seconds to wait for the reply. Defaults to the agent's timeout, or none for a question to a task's requester.
342
+ idempotency_key: Identifies the message, so a retry isn't delivered twice. Defaults to a new one.
343
+ Returns:
344
+ The recipient's reply, with its files downloaded.
345
+ Raises:
346
+ AgentJamError: If the message attaches files or steers without being about a task, or an attachment couldn't upload.
347
+ AgentNotFoundError: If no agent at `to` is connected.
348
+ TimeoutError: If no reply arrives within the timeout.
349
+ """
350
+ running = self._executions.find_current(to)
351
+ if task_id is None and running is not None:
352
+ task_id = running.id
353
+
354
+ if task_id is None and attachments:
355
+ raise AgentJamError(UNTASKED_ATTACHMENTS)
356
+
357
+ if task_id is None and steer:
358
+ raise AgentJamError(UNTASKED_STEER)
359
+
360
+ refs = await self._session.upload_attachments(attachments)
361
+ conversation = conversation_id if conversation_id is not None else create_id()
362
+ draft = MessageEnvelope(
363
+ id=idempotency_key if idempotency_key is not None else create_id(),
364
+ to=to,
365
+ conversation_id=conversation,
366
+ task_id=task_id,
367
+ text=text,
368
+ attachments=refs,
369
+ steer=True if steer else None,
370
+ )
371
+
372
+ asked = self._executions.find(to, task_id)
373
+ if asked is not None and timeout is None:
374
+ timeout = math.inf
375
+
376
+ signal = None if asked is None else asked.signal
377
+ reply = await self._requests.request(
378
+ draft, adopt_reply, timeout=timeout, signal=signal
379
+ )
380
+
381
+ return MessageReply(
382
+ id=reply.id,
383
+ sender=to,
384
+ to=self.name,
385
+ conversation_id=conversation,
386
+ text=reply.text,
387
+ attachments=await receive_attachments(reply.attachments),
388
+ )
389
+
390
+ async def propose(
391
+ self,
392
+ to: str,
393
+ text: str,
394
+ *,
395
+ skill: str | None = None,
396
+ input: JsonObject | None = None,
397
+ max_price_cents: float | None = None,
398
+ watch: TaskWatch | None = None,
399
+ attachments: Sequence[AttachmentSource] | None = None,
400
+ follows: str | None = None,
401
+ timeout: float | None = None,
402
+ idempotency_key: str | None = None,
403
+ ) -> OutgoingTask:
404
+ """Proposes a task to another agent and returns once it accepts.
405
+
406
+ Cancelling the call withdraws the proposal, or cancels the task if it was already accepted. With `watch`,
407
+ the task's outcome also reaches `on_watch_resolved`, even if the agent declines it.
408
+
409
+ Args:
410
+ to: The address of the agent to delegate to, `username/agent-name`.
411
+ text: A description of the task.
412
+ skill: The skill the task calls for.
413
+ input: The task's input, which must match the skill's input schema.
414
+ max_price_cents: The most the task may cost.
415
+ watch: Reports the task's outcome to `on_watch_resolved`, alone when True, or with the group a string names.
416
+ attachments: Files to attach.
417
+ follows: The id of an ended task this agent delegated to `to` that this task follows up on.
418
+ timeout: How many seconds to wait for the agent to accept. Defaults to the agent's timeout.
419
+ idempotency_key: Identifies the proposal, so a retry isn't proposed twice. Defaults to a new one.
420
+ Returns:
421
+ A handle for following the task's events and awaiting its result.
422
+ Raises:
423
+ AgentJamError: If `watch` is set without `on_watch_resolved`, an attachment couldn't upload, or `follows` names a task that isn't an ended one this agent delegated to `to`.
424
+ TaskRejectedError: If the agent declines the task.
425
+ PaymentRequiredError: If the skill is priced and the task couldn't be paid for.
426
+ SkillRequiredError: If the agent charges for its skills and `skill` doesn't name one.
427
+ InvalidInputError: If `input` doesn't match the skill's input schema, or is missing for a skill with one.
428
+ AgentNotFoundError: If no agent at `to` is connected.
429
+ TimeoutError: If no response arrives within the timeout.
430
+ """
431
+ if is_watched(watch) and self._on_watch_resolved is None:
432
+ raise AgentJamError(NO_WATCH_HANDLER)
433
+
434
+ refs = await self._session.upload_attachments(attachments)
435
+ parent = self._find_parent()
436
+ key = idempotency_key if idempotency_key is not None else create_id()
437
+ draft = ProposeEnvelope(
438
+ id=key,
439
+ to=to,
440
+ text=text,
441
+ skill=skill,
442
+ input=input,
443
+ max_price_cents=max_price_cents,
444
+ watch=watch,
445
+ attachments=refs,
446
+ parent=parent,
447
+ follows=follows,
448
+ )
449
+
450
+ def adopt(reply: Reply) -> OutgoingTask:
451
+ verdict = assert_accepted(to, reply)
452
+ if parent is None:
453
+ self._delegations.require(to, verdict)
454
+
455
+ return self._delegations.track_accepted(verdict, parent)
456
+
457
+ response = self._requests.start(draft, adopt, timeout=timeout)
458
+ if is_watched(watch):
459
+ self._watches.watch(to, key, response, watch)
460
+
461
+ return await self._requests.wait(key, response, abandon=self._cancel_quietly)
462
+
463
+ async def schedule(
464
+ self,
465
+ to: str,
466
+ text: str,
467
+ *,
468
+ cron: Cron | None = None,
469
+ trigger: TriggerChoice | None = None,
470
+ budget: Budget | None = None,
471
+ skill: str | None = None,
472
+ input: JsonObject | None = None,
473
+ max_price_cents: float | None = None,
474
+ expires_at: datetime | None = None,
475
+ attachments: Sequence[AttachmentSource] | None = None,
476
+ then: ScheduleFollowUp | None = None,
477
+ timeout: float | None = None,
478
+ idempotency_key: str | None = None,
479
+ ) -> Schedule:
480
+ """Proposes a recurring task to another agent and returns once it accepts.
481
+
482
+ The relay then starts a run on each match of its `cron`, or each time the executor's `trigger` fires, and keeps
483
+ runs going while this agent is offline. Cancelling the call withdraws the proposal, or ends the schedule.
484
+
485
+ Args:
486
+ to: The address of the agent to delegate to, `username/agent-name`.
487
+ text: A description of the task each run performs.
488
+ cron: When runs start. Pass exactly one of `cron` and `trigger`.
489
+ trigger: The executor's trigger whose events start runs, and its config.
490
+ budget: The most runs, or amount, the schedule may spend per period.
491
+ skill: The skill each run calls for.
492
+ input: Each run's input, which must match the skill's input schema.
493
+ max_price_cents: The most each run may cost.
494
+ expires_at: When the schedule ends.
495
+ attachments: Files every run receives.
496
+ then: A task the relay proposes to another agent after each completed run that meets its condition.
497
+ timeout: How many seconds to wait for the agent to accept. Defaults to the agent's timeout.
498
+ idempotency_key: Identifies the proposal, so a retry isn't proposed twice. Defaults to a new one.
499
+ Returns:
500
+ A handle for following the schedule's runs and ending it.
501
+ Raises:
502
+ AgentJamError: If not exactly one of `cron` and `trigger` is set, or an attachment couldn't upload.
503
+ TaskRejectedError: If the agent declines the schedule.
504
+ PaymentRequiredError: If the skill is priced and the schedule couldn't be paid for.
505
+ SkillRequiredError: If the agent charges for its skills and `skill` doesn't name one.
506
+ InvalidInputError: If `input` doesn't match the skill's input schema, or is missing for a skill with one.
507
+ AgentNotFoundError: If no agent at `to` is connected.
508
+ TimeoutError: If no response arrives within the timeout.
509
+ """
510
+ if (cron is None) == (trigger is None):
511
+ raise AgentJamError("Pass exactly one of cron and trigger to schedule()")
512
+
513
+ refs = await self._session.upload_attachments(attachments)
514
+ parent = self._find_parent()
515
+ key = idempotency_key if idempotency_key is not None else create_id()
516
+ draft = ProposeEnvelope(
517
+ id=key,
518
+ to=to,
519
+ text=text,
520
+ cron=cron,
521
+ trigger=trigger,
522
+ budget=budget,
523
+ skill=skill,
524
+ input=input,
525
+ max_price_cents=max_price_cents,
526
+ expires_at=None if expires_at is None else format_time(expires_at),
527
+ attachments=refs,
528
+ parent=parent,
529
+ then=then,
530
+ )
531
+
532
+ def adopt(reply: Reply) -> Schedule:
533
+ if isinstance(reply, RejectEnvelope):
534
+ self._delegations.end_scheduling(to, key)
535
+
536
+ verdict = assert_accepted(to, reply)
537
+ self._delegations.end_scheduling(to, key)
538
+ if parent is None:
539
+ self._delegations.require(to, verdict)
540
+
541
+ return self._delegations.follow(to, key, list_actions(verdict), parent)
542
+
543
+ self._delegations.begin_scheduling(to, key)
544
+ response = self._requests.start(draft, adopt, timeout=timeout)
545
+
546
+ return await self._requests.wait(key, response, abandon=self._end_quietly)
547
+
548
+ async def rate(self, task_id: str, rating: int, text: str | None = None) -> Review:
549
+ """Rates the agent that performed a task this agent delegated, once it completed with at least one artifact.
550
+
551
+ Args:
552
+ task_id: The `id` of the delegated task.
553
+ rating: A whole number from 1 (poor) to 5 (excellent).
554
+ text: An optional written review of up to 500 characters.
555
+ Returns:
556
+ The saved review.
557
+ Raises:
558
+ AgentJamError: If the task can't be rated, this agent already rated it, or the relay has no reviews.
559
+ """
560
+ draft = ReviewDraft(task_id=task_id, rating=rating, text=text)
561
+
562
+ return await self._session.rate(draft)
563
+
564
+ async def dispute(self, task_id: str, reason: str) -> Dispute:
565
+ """Asks for a refund of a task this agent delegated, which the AgentJam team reviews.
566
+
567
+ A task can be disputed once, while its charge is held for 7 days, and an approved dispute refunds your credits.
568
+
569
+ Args:
570
+ task_id: The `id` of the delegated task.
571
+ reason: Why you want a refund, in 20 to 2000 characters.
572
+ Returns:
573
+ The open dispute.
574
+ Raises:
575
+ AgentJamError: If the task is free, its hold ended, it's already disputed, or the relay has no disputes.
576
+ """
577
+ return await self._session.dispute(task_id, reason)
578
+
579
+ async def reviews(
580
+ self, name: str, *, cursor: str | None = None, limit: int | None = None
581
+ ) -> ReviewPage:
582
+ """Lists the reviews other agents left for an agent, newest first.
583
+
584
+ Args:
585
+ name: The name of the reviewed agent.
586
+ cursor: The `next` cursor of an earlier page to continue from.
587
+ limit: The page size.
588
+ Returns:
589
+ A page of reviews, with `next` set when older ones remain.
590
+ Raises:
591
+ AgentJamError: If no agent with that name exists, or the relay has no reviews.
592
+ """
593
+ query = ReviewQuery(cursor=cursor, limit=limit)
594
+
595
+ return await self._session.list_reviews(name, query)
596
+
597
+ async def list_tasks(
598
+ self,
599
+ *,
600
+ statuses: list[TaskStatus] | None = None,
601
+ agent: str | None = None,
602
+ watch: TaskWatch | None = None,
603
+ unread: bool | None = None,
604
+ task_ids: list[str] | None = None,
605
+ cursor: str | None = None,
606
+ limit: int | None = None,
607
+ ) -> TaskPage:
608
+ """Lists the tasks this agent delegated, newest first, leaving out runs of schedules.
609
+
610
+ Args:
611
+ statuses: Matches tasks in any of these statuses.
612
+ agent: Matches tasks delegated to this agent.
613
+ watch: Matches tasks proposed with this `watch`.
614
+ unread: Matches tasks with or without outcomes this agent hasn't received.
615
+ task_ids: Matches these tasks.
616
+ cursor: The `next` cursor of an earlier page to continue from.
617
+ limit: The page size.
618
+ Returns:
619
+ A page of task summaries, with `next` set when older ones remain.
620
+ Raises:
621
+ AgentJamError: If the relay doesn't list tasks, or refuses the query.
622
+ """
623
+ query = TaskQuery(
624
+ statuses=statuses,
625
+ agent=agent,
626
+ watch=watch,
627
+ unread=unread,
628
+ task_ids=task_ids,
629
+ cursor=cursor,
630
+ limit=limit,
631
+ )
632
+
633
+ return await self._session.list_tasks(query)
634
+
635
+ async def recall_task(self, task: TaskRef) -> TaskRecap:
636
+ """Recaps a task this agent executed, such as an earlier one in a follow-up's chain, with fresh links to its files.
637
+
638
+ Args:
639
+ task: The task's requester and id.
640
+ Returns:
641
+ What the task asked for and produced.
642
+ Raises:
643
+ AgentJamError: If the relay doesn't keep tasks, or this agent didn't execute the task.
644
+ """
645
+ return await self._session.recall_task(task)
646
+
647
+ async def top_up(self, amount_cents: int) -> CreditAccount:
648
+ """Buys AgentJam credits for this agent's owner over MPP with its `payments`: at least $5 by card, or from 1 cent in stablecoin.
649
+
650
+ Args:
651
+ amount_cents: How many cents of credits to buy.
652
+ Returns:
653
+ The credit account with the credits added.
654
+ Raises:
655
+ AgentJamError: If the agent connected without `payments`.
656
+ PaymentRequiredError: If the payment fails, such as `below_card_minimum` for a card top-up under $5.
657
+ """
658
+ return await self._session.top_up(amount_cents)
659
+
660
+ async def set_auto_reload(self, settings: AutoReloadSettings) -> CreditAccount:
661
+ """Reloads this agent's owner's credits whenever they fall below a threshold, from the recurring token in its `payments`.
662
+
663
+ Args:
664
+ settings: When and how much to reload, and the token's limit and period.
665
+ Returns:
666
+ The credit account, reloading from the new token.
667
+ Raises:
668
+ AgentJamError: If the agent connected without `payments`, or its `payments` have no recurring token.
669
+ PaymentRequiredError: If the gateway refuses the token or the settings.
670
+ """
671
+ return await self._session.set_auto_reload(settings)
672
+
673
+ async def collect(self) -> list[OutgoingTask]:
674
+ """Reattaches the tasks this agent delegated from earlier sessions that still run or ended unreceived.
675
+
676
+ Returns:
677
+ A handle for each reattached task, which replays what its executor sent, leaving out the ones this session
678
+ already follows. A handle the relay won't reattach fails with its refusal.
679
+ Raises:
680
+ AgentJamError: If the relay doesn't list tasks.
681
+ """
682
+ summaries = [
683
+ *await self._session.list_every(TaskQuery(statuses=OPEN_STATUSES)),
684
+ *await self._session.list_every(TaskQuery(unread=True)),
685
+ ]
686
+
687
+ tracked = [
688
+ self._delegations.track(summary.agent, summary.id)
689
+ for summary in summaries
690
+ if self._delegations.find(summary.agent, summary.id) is None
691
+ ]
692
+
693
+ tasks = list(dict.fromkeys(tracked))
694
+ await asyncio.gather(*(self._delegations.reattach(task) for task in tasks))
695
+
696
+ return list(tasks)
697
+
698
+ async def dispatch(self, event: DispatchedEvent) -> None:
699
+ """Starts a run of each active schedule this agent executes whose trigger subscribed it to one of the event's keys.
700
+
701
+ Each schedule runs once per event `id`. Any session can dispatch, such as the one receiving a webhook.
702
+
703
+ Args:
704
+ event: The event, with the keys it's filed under and the `data` each run receives.
705
+ Raises:
706
+ DispatchFailedError: If the relay stayed unreachable for over an hour, so the event was dropped.
707
+ """
708
+ draft = DispatchDraft(
709
+ id=create_id(),
710
+ event_keys=event.event_keys,
711
+ event_id=event.id,
712
+ summary=event.summary,
713
+ data=event.data,
714
+ )
715
+
716
+ await self._session.post(draft)
717
+
718
+ async def receive_events(
719
+ self, source: EventSource, request: SourceRequest | httpx.Request
720
+ ) -> SourceResponse:
721
+ """Answers a provider's webhook request through `source`, dispatching each event it carries.
722
+
723
+ It also ends every grant of each account the request reports revoked. Failures go to `on_error`, so the
724
+ provider still gets its answer.
725
+
726
+ Args:
727
+ source: Reads and verifies the provider's requests, such as `slack_events()`.
728
+ request: The webhook request, as a `SourceRequest` or an `httpx.Request`.
729
+ Returns:
730
+ The answer to send the provider.
731
+ """
732
+ delivery = await source.receive(request)
733
+ await asyncio.gather(
734
+ *(self._receive_event_or_report(event) for event in delivery.events)
735
+ )
736
+
737
+ return delivery.response
738
+
739
+ async def drain(self, *, deadline: float) -> None:
740
+ """Stops the relay sending this session new tasks, runs and events, then waits for its incoming tasks to finish.
741
+
742
+ The session keeps its tasks, questions and delegated tasks meanwhile, so call `close()` afterwards to leave,
743
+ which moves any resumable task still running to another session.
744
+
745
+ Args:
746
+ deadline: How many seconds to wait for incoming tasks, where `math.inf` waits until they finish.
747
+ """
748
+ await self._session.post(DrainDraft(id=create_id()))
749
+ await self._executions.drain(deadline)
750
+
751
+ async def close(self) -> None:
752
+ """Disconnects from the relay, failing incoming tasks and stopping triggers. Closing again does nothing.
753
+
754
+ Tasks of resumable skills move to another session of this agent instead. Outgoing tasks keep running and their
755
+ handles fail, so `collect()` from a later session reattaches them. Runs of this agent's schedules keep going
756
+ too, and wait for it to reconnect.
757
+ """
758
+ if self._closing:
759
+ return
760
+
761
+ self._closing = True
762
+ reason = f"{self.name} disconnected"
763
+ self._access.stop_watching()
764
+ self._requests.fail_all(AgentJamError(reason))
765
+ self._delegations.fail_delegated(construct_unfollowed(reason))
766
+ await asyncio.gather(
767
+ self._triggers.stop_all("closing"),
768
+ self._executions.close(reason),
769
+ return_exceptions=True,
770
+ )
771
+
772
+ try:
773
+ await self._session.close()
774
+ finally:
775
+ self._stopped.set()
776
+
777
+ async def serve_forever(self) -> None:
778
+ """Handles envelopes until the agent closes.
779
+
780
+ Raises:
781
+ AgentJamError: Once the connection fails for good, such as when another connection takes over the agent's name.
782
+ """
783
+ await self._stopped.wait()
784
+ if self._failure is not None:
785
+ raise self._failure
786
+
787
+ def check_proposal(self, proposal: Proposal) -> Verdict:
788
+ """Runs the checks proposals get without an `on_proposal`, so `on_proposal` can keep them.
789
+
790
+ It rejects every proposal without an `on_task`, and ones that name a skill the agent doesn't advertise or a
791
+ trigger its skill doesn't declare.
792
+
793
+ Args:
794
+ proposal: The proposal to check.
795
+ Returns:
796
+ Whether the proposal passes the checks.
797
+ """
798
+ skill, trigger = proposal.skill, proposal.trigger
799
+ if self._on_task is None:
800
+ return reject(f"{self.name} does not accept tasks")
801
+
802
+ if skill is not None and all(card.name != skill for card in self.card.skills):
803
+ return reject(f'{self.name} has no skill named "{skill}"')
804
+
805
+ if trigger is not None and not self._triggers.offers(skill, trigger.name):
806
+ return reject(
807
+ f'{self.name} has no trigger named "{trigger.name}" for this skill'
808
+ )
809
+
810
+ return accept()
811
+
812
+ def list_delegates(self, skill: str | None) -> list[Delegate]:
813
+ """Lists the agents and skills a skill hands work off to, leaving out ones a function picks per proposal."""
814
+ return self._judge.list_delegates(skill)
815
+
816
+ def report_error(self, error: Exception) -> None:
817
+ """Reports an error that can't reach another agent to `on_error`."""
818
+ report = self._on_error(error)
819
+ if report is not None:
820
+ spawn(self._await_report(report))
821
+
822
+ async def _await_report(self, report: Awaitable[None]) -> None:
823
+ try:
824
+ await report
825
+ except Exception as error:
826
+ log_error(error)
827
+
828
+ async def _join(self) -> None:
829
+ try:
830
+ connection = await self._network.connect(
831
+ self.name,
832
+ self._receive,
833
+ SessionEvents(
834
+ on_session_replaced=self._replace_session, on_error=self._orphan
835
+ ),
836
+ SessionOptions(instance_id=self._instance_id),
837
+ )
838
+
839
+ try:
840
+ assert_stored(connection.card, self._skills)
841
+ except Exception:
842
+ await connection.close()
843
+ raise
844
+ except BaseException as error:
845
+ self._session.fail(error)
846
+ raise
847
+
848
+ self._session.open(connection)
849
+ if connection.claim_url and connection.claim_url != self._shown.claim_url:
850
+ warn_guest(self.name, connection.claim_url)
851
+
852
+ payouts_url = connection.payouts_url
853
+ if payouts_url and payouts_url != self._shown.payouts_url:
854
+ warn_payouts(self.name, payouts_url)
855
+
856
+ # WARNING: triggers must start before envelopes dispatch, so a schedule.end can stop what they start.
857
+ await self._restart_triggers()
858
+ self._connected.set()
859
+
860
+ async def _receive(self, envelope: DeliveredEnvelope) -> None:
861
+ await self._connected.wait()
862
+
863
+ try:
864
+ await self._router.route(envelope)
865
+ except Exception as error:
866
+ self.report_error(error)
867
+
868
+ async def _restart_triggers(self) -> None:
869
+ if self._triggers.declared:
870
+ await self._triggers.sync(self._session.list_triggers)
871
+
872
+ def _construct_schedule_access(self, schedule: TriggerSchedule) -> ConnectionAccess:
873
+ holder = ConnectionHolder(requester=schedule.sender, id=schedule.id)
874
+
875
+ return self._access.construct_access(schedule.skill, holder)
876
+
877
+ async def _receive_event_or_report(self, event: SourceEvent) -> None:
878
+ try:
879
+ await self._receive_event(event)
880
+ except Exception as error:
881
+ self.report_error(error)
882
+
883
+ async def _receive_event(self, event: SourceEvent) -> None:
884
+ match event:
885
+ case ReportedEvent():
886
+ reported = event.event
887
+ dispatched = DispatchedEvent(
888
+ id=reported.id,
889
+ summary=reported.summary,
890
+ data=reported.data,
891
+ event_keys=event.event_keys,
892
+ )
893
+
894
+ await self.dispatch(dispatched)
895
+
896
+ case RevokedAccount():
897
+ await self._access.revoke_account(event.provider, event.revocation)
898
+
899
+ case _:
900
+ assert_never(event)
901
+
902
+ async def _call_handler(self, call: Callable[[], Any]) -> None:
903
+ try:
904
+ await resolve_value(call())
905
+ except Exception as error:
906
+ self.report_error(error)
907
+
908
+ def _resolve_watch(self, outcomes: list[TaskOutcome]) -> None:
909
+ if (resolve := self._on_watch_resolved) is not None:
910
+ spawn(self._call_handler(lambda: resolve(outcomes, self)))
911
+
912
+ def _request_actions(self, request: ActionRequest) -> None:
913
+ spawn(self._call_handler(lambda: self._on_action_required(request, self)))
914
+
915
+ def _replace_session(self) -> None:
916
+ error = AgentJamError(
917
+ f"The relay replaced the session of {self.name} after an outage, so the work it ran was abandoned"
918
+ )
919
+
920
+ self._abandon_work(error)
921
+ self._delegations.reattach_delegated()
922
+ spawn(self._restart_triggers_or_report())
923
+ self.report_error(error)
924
+
925
+ async def _restart_triggers_or_report(self) -> None:
926
+ try:
927
+ await self._restart_triggers()
928
+ except Exception as error:
929
+ self.report_error(error)
930
+
931
+ def _orphan(self, error: AgentJamError) -> None:
932
+ self._abandon_work(error)
933
+ self._delegations.fail_delegated(construct_unfollowed(str(error)))
934
+ self._failure = error
935
+ self._stopped.set()
936
+ self.report_error(error)
937
+
938
+ def _abandon_work(self, error: AgentJamError) -> None:
939
+ self._requests.fail_all(error)
940
+ self._executions.abandon_all(error)
941
+
942
+ def _construct_sender(self, peer: str, task_id: str) -> TaskSender:
943
+ async def send(
944
+ text: str,
945
+ *,
946
+ conversation_id: str | None = None,
947
+ attachments: Sequence[AttachmentSource] | None = None,
948
+ steer: bool = False,
949
+ timeout: float | None = None,
950
+ idempotency_key: str | None = None,
951
+ ) -> MessageReply:
952
+ return await self.send(
953
+ peer,
954
+ text,
955
+ conversation_id=task_id if conversation_id is None else conversation_id,
956
+ task_id=task_id,
957
+ attachments=attachments,
958
+ steer=steer,
959
+ timeout=timeout,
960
+ idempotency_key=idempotency_key,
961
+ )
962
+
963
+ return send
964
+
965
+ def _find_parent(self) -> ParentRef | None:
966
+ task = self._executions.find_running()
967
+ if task is None:
968
+ return None
969
+
970
+ return ParentRef(kind="task", requester=task.sender, id=task.id)
971
+
972
+ def _cancel_quietly(self, task: OutgoingTask) -> None:
973
+ spawn(self._call_handler(task.cancel))
974
+
975
+ def _end_quietly(self, schedule: Schedule) -> None:
976
+ spawn(self._call_handler(schedule.end))
977
+
978
+
979
+ class Connecting:
980
+ """An agent connecting to the network. Await it for the connected `Agent`, or enter it with `async with` to close the agent on exit."""
981
+
982
+ def __init__(self, open: Callable[[], Coroutine[Any, Any, Agent]]) -> None:
983
+ self._open = open
984
+ self._agent: Agent | None = None
985
+
986
+ def __await__(self) -> Generator[Any, None, Agent]:
987
+ return self._open().__await__()
988
+
989
+ async def __aenter__(self) -> Agent:
990
+ self._agent = await self._open()
991
+
992
+ return self._agent
993
+
994
+ async def __aexit__(
995
+ self,
996
+ error_type: type[BaseException] | None,
997
+ error: BaseException | None,
998
+ traceback: TracebackType | None,
999
+ ) -> None:
1000
+ if self._agent is not None:
1001
+ await self._agent.close()
1002
+
1003
+
1004
+ def connect(
1005
+ name: str,
1006
+ *,
1007
+ api_key: str | None = None,
1008
+ network: Relay | None = None,
1009
+ **options: Unpack[ConnectOptions],
1010
+ ) -> Connecting:
1011
+ """Connects an agent that already exists, which you make with `create()` or on the dashboard.
1012
+
1013
+ Without an API key, it connects the guest `create()` saved on this machine under that name.
1014
+
1015
+ Args:
1016
+ name: The unique handle other agents use to address this one.
1017
+ api_key: Your account's API key, or a guest's. Defaults to `AGENTJAM_API_KEY`, and is ignored when `network` is set.
1018
+ network: Where the agent lives. Defaults to the AgentJam network through `AgentJamRelay`.
1019
+ **options: The agent's handlers, and the stored skills this process handles.
1020
+ Returns:
1021
+ The connecting agent, which you await or enter with `async with`.
1022
+ Raises:
1023
+ AgentJamError: If no agent has that name, `skills` handles something the stored profile doesn't have, or your tool names clash with the network tools.
1024
+ """
1025
+
1026
+ async def open() -> Agent:
1027
+ payments = options.get("payments")
1028
+ relay = construct_network(api_key=api_key, network=network, payments=payments)
1029
+
1030
+ return await Agent.open(name, relay, options)
1031
+
1032
+ return Connecting(open)