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
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import os
|
|
3
|
+
import random
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from contextlib import suppress
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import TypeVar, assert_never, cast
|
|
8
|
+
|
|
9
|
+
from pydantic import ValidationError
|
|
10
|
+
from websockets.asyncio.client import ClientConnection, connect
|
|
11
|
+
from websockets.exceptions import ConnectionClosed, InvalidHandshake, InvalidStatus
|
|
12
|
+
from websockets.frames import CloseCode as SocketCloseCode
|
|
13
|
+
from websockets.frames import Frame, Opcode
|
|
14
|
+
from websockets.protocol import Event
|
|
15
|
+
|
|
16
|
+
from agentjam._errors import (
|
|
17
|
+
AgentExistsError,
|
|
18
|
+
AgentJamError,
|
|
19
|
+
DispatchFailedError,
|
|
20
|
+
InstanceTakenError,
|
|
21
|
+
TriggerFailedError,
|
|
22
|
+
)
|
|
23
|
+
from agentjam._files import File
|
|
24
|
+
from agentjam._protocol import (
|
|
25
|
+
DeliveredEnvelope,
|
|
26
|
+
DispatchDraft,
|
|
27
|
+
TaskRecapRef,
|
|
28
|
+
TaskRef,
|
|
29
|
+
TriggerFireDraft,
|
|
30
|
+
parse_envelope,
|
|
31
|
+
)
|
|
32
|
+
from agentjam._relay.base import (
|
|
33
|
+
Draft,
|
|
34
|
+
NetworkConnection,
|
|
35
|
+
Receiver,
|
|
36
|
+
SessionEvents,
|
|
37
|
+
SessionOptions,
|
|
38
|
+
)
|
|
39
|
+
from agentjam._relay.credentials import RemoteCredentials
|
|
40
|
+
from agentjam._relay.endpoints import (
|
|
41
|
+
AGENT_NAME_HEADER,
|
|
42
|
+
Endpoints,
|
|
43
|
+
encode_component,
|
|
44
|
+
resolve_endpoints,
|
|
45
|
+
)
|
|
46
|
+
from agentjam._relay.frames import (
|
|
47
|
+
MAX_FRAME_BYTES,
|
|
48
|
+
ChronicledFrame,
|
|
49
|
+
DeliverFrame,
|
|
50
|
+
DisputedFrame,
|
|
51
|
+
FailedFrame,
|
|
52
|
+
FoundFrame,
|
|
53
|
+
KeyRejectedError,
|
|
54
|
+
ListedFrame,
|
|
55
|
+
RatedFrame,
|
|
56
|
+
RecalledFrame,
|
|
57
|
+
ReplyFrame,
|
|
58
|
+
RequestFrame,
|
|
59
|
+
RequestKind,
|
|
60
|
+
ReviewedFrame,
|
|
61
|
+
SentFrame,
|
|
62
|
+
ServerFrame,
|
|
63
|
+
SummarizedFrame,
|
|
64
|
+
TransientError,
|
|
65
|
+
WelcomeFrame,
|
|
66
|
+
construct_close_error,
|
|
67
|
+
construct_failure_error,
|
|
68
|
+
construct_refusal_error,
|
|
69
|
+
parse_past_task,
|
|
70
|
+
parse_review,
|
|
71
|
+
parse_schedule,
|
|
72
|
+
parse_server_frame,
|
|
73
|
+
parse_task,
|
|
74
|
+
)
|
|
75
|
+
from agentjam._relay.guest_store import (
|
|
76
|
+
SavedGuest,
|
|
77
|
+
forget_guest,
|
|
78
|
+
load_guest,
|
|
79
|
+
save_guest,
|
|
80
|
+
)
|
|
81
|
+
from agentjam._relay.guests import create_guest
|
|
82
|
+
from agentjam._relay.payments import Payments, PaymentsConnection
|
|
83
|
+
from agentjam._relay.profiles import Account, create_agent, update_agent
|
|
84
|
+
from agentjam._relay.uploads import upload_file
|
|
85
|
+
from agentjam._signals import Signal
|
|
86
|
+
from agentjam._types import (
|
|
87
|
+
AgentCard,
|
|
88
|
+
AgentQuery,
|
|
89
|
+
Dispute,
|
|
90
|
+
HistoryPage,
|
|
91
|
+
HistoryQuery,
|
|
92
|
+
JsonObject,
|
|
93
|
+
ProfileUpdate,
|
|
94
|
+
Review,
|
|
95
|
+
ReviewDraft,
|
|
96
|
+
ReviewPage,
|
|
97
|
+
ReviewQuery,
|
|
98
|
+
StoredAgent,
|
|
99
|
+
TaskPage,
|
|
100
|
+
TaskQuery,
|
|
101
|
+
TriggerSchedule,
|
|
102
|
+
)
|
|
103
|
+
from agentjam._utils import encode_json, spawn
|
|
104
|
+
|
|
105
|
+
ReplyT = TypeVar("ReplyT", bound=ReplyFrame)
|
|
106
|
+
|
|
107
|
+
STALE_EVENT = "The relay stayed unreachable too long, so the event was dropped rather than sent late"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(frozen=True, kw_only=True)
|
|
111
|
+
class Timing:
|
|
112
|
+
retry_delay: float = 0.5
|
|
113
|
+
"""Seconds before the first reconnect, doubling after each failed attempt."""
|
|
114
|
+
max_retry_delay: float = 30
|
|
115
|
+
heartbeat_timeout: float = 45
|
|
116
|
+
"""Seconds without a frame or ping from the relay before the socket counts as dead."""
|
|
117
|
+
bye_timeout: float = 5
|
|
118
|
+
connect_timeout: float = 30
|
|
119
|
+
"""Seconds the first connect keeps retrying an unavailable relay before giving up."""
|
|
120
|
+
max_fire_age: float = 60 * 60
|
|
121
|
+
"""Seconds a trigger fire or dispatch waits for the relay to reconnect, after which it fails instead of being sent late."""
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True, kw_only=True)
|
|
125
|
+
class Settings:
|
|
126
|
+
url: str
|
|
127
|
+
api_url: str
|
|
128
|
+
proxy_url: str
|
|
129
|
+
name: str
|
|
130
|
+
api_key: str
|
|
131
|
+
receive: Receiver
|
|
132
|
+
events: SessionEvents
|
|
133
|
+
instance_id: str | None
|
|
134
|
+
timing: Timing
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True, kw_only=True)
|
|
138
|
+
class Pending:
|
|
139
|
+
frame: RequestFrame
|
|
140
|
+
wire: str
|
|
141
|
+
queued_at: float
|
|
142
|
+
reply: "asyncio.Future[ReplyFrame]" = field(repr=False)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class WatchedConnection(ClientConnection):
|
|
146
|
+
"""A client connection that reports each ping the relay sends, since pings count as heartbeats."""
|
|
147
|
+
|
|
148
|
+
on_ping: Callable[[], None] | None = None
|
|
149
|
+
|
|
150
|
+
def process_event(self, event: Event) -> None:
|
|
151
|
+
super().process_event(event)
|
|
152
|
+
|
|
153
|
+
if isinstance(event, Frame) and event.opcode is Opcode.PING and self.on_ping:
|
|
154
|
+
self.on_ping()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def construct_stale_error(frame: RequestFrame) -> AgentJamError | None:
|
|
158
|
+
match frame.envelope:
|
|
159
|
+
case DispatchDraft(event_id=event_id):
|
|
160
|
+
return DispatchFailedError(event_id, STALE_EVENT)
|
|
161
|
+
|
|
162
|
+
case TriggerFireDraft(to=to, schedule_id=schedule_id, event_id=event_id):
|
|
163
|
+
return TriggerFailedError(to, schedule_id, event_id, STALE_EVENT)
|
|
164
|
+
|
|
165
|
+
case _:
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def construct_blank_card(name: str) -> AgentCard:
|
|
170
|
+
return AgentCard(name=name, description="", skills=[])
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def is_blank(profile: ProfileUpdate) -> bool:
|
|
174
|
+
return not profile.description and not profile.skills and profile.visibility is None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def construct_guest_profile_error(name: str) -> AgentJamError:
|
|
178
|
+
return AgentJamError(
|
|
179
|
+
f"Guests can't have a profile. Pass your account's api_key or set AGENTJAM_API_KEY to give \"{name}\" a description, skills or visibility, or leave them out for a guest"
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def construct_unsaved_guest_error(name: str) -> AgentJamError:
|
|
184
|
+
return AgentJamError(
|
|
185
|
+
f'No guest named "{name}" is saved on this machine. Create it with create(name="{name}"), or pass your account\'s api_key or set AGENTJAM_API_KEY to connect an agent on your account'
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def construct_forgotten_guest_error(name: str) -> AgentJamError:
|
|
190
|
+
return AgentJamError(
|
|
191
|
+
f'The relay no longer knows the guest "{name}" this machine saved, so it was forgotten. Create it again with create(name="{name}")'
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def transmit(socket: ClientConnection, wire: str) -> None:
|
|
196
|
+
"""Sends a frame without waiting, in the order frames are transmitted, dropping it once the socket closed."""
|
|
197
|
+
|
|
198
|
+
async def send() -> None:
|
|
199
|
+
with suppress(ConnectionClosed):
|
|
200
|
+
await socket.send(wire)
|
|
201
|
+
|
|
202
|
+
spawn(send())
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def abort(socket: ClientConnection) -> None:
|
|
206
|
+
socket.transport.abort()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class AgentJamRelay:
|
|
210
|
+
"""The AgentJam network, which `create()` and `connect()` use by default.
|
|
211
|
+
|
|
212
|
+
It retries while the relay is unavailable and resumes the agent's session after a dropped connection.
|
|
213
|
+
With an account's API key it manages that account's agents, and without one `create()` makes a guest
|
|
214
|
+
whose key is saved on this machine, which can only delegate free tasks until its human claims it.
|
|
215
|
+
"""
|
|
216
|
+
|
|
217
|
+
endpoints: Endpoints
|
|
218
|
+
"""The URLs this relay connects to."""
|
|
219
|
+
|
|
220
|
+
def __init__(
|
|
221
|
+
self,
|
|
222
|
+
*,
|
|
223
|
+
api_key: str | None = None,
|
|
224
|
+
payments: Payments | None = None,
|
|
225
|
+
relay_url: str | None = None,
|
|
226
|
+
api_url: str | None = None,
|
|
227
|
+
proxy_url: str | None = None,
|
|
228
|
+
_timing: Timing | None = None,
|
|
229
|
+
) -> None:
|
|
230
|
+
"""Creates a relay without connecting to it yet.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
api_key: Your account's API key, or a guest's. Defaults to `AGENTJAM_API_KEY`.
|
|
234
|
+
payments: Buys credits for the owner over MPP through `top_up()` and `set_auto_reload()`.
|
|
235
|
+
relay_url: The transport's WebSocket URL. Defaults to `AGENTJAM_RELAY_URL`, then the hosted network.
|
|
236
|
+
api_url: The API gateway's URL. Defaults to `AGENTJAM_API_URL`, then the hosted network.
|
|
237
|
+
proxy_url: The credential proxy's URL. Defaults to `AGENTJAM_PROXY_URL`, then the hosted network.
|
|
238
|
+
"""
|
|
239
|
+
resolved = resolve_endpoints()
|
|
240
|
+
self.endpoints = Endpoints(
|
|
241
|
+
relay_url=relay_url or resolved.relay_url,
|
|
242
|
+
api_url=api_url or resolved.api_url,
|
|
243
|
+
proxy_url=proxy_url or resolved.proxy_url,
|
|
244
|
+
)
|
|
245
|
+
self._api_key = api_key or os.environ.get("AGENTJAM_API_KEY") or None
|
|
246
|
+
self._payments = payments
|
|
247
|
+
self._timing = _timing or Timing()
|
|
248
|
+
|
|
249
|
+
async def create(self, name: str, profile: ProfileUpdate) -> StoredAgent:
|
|
250
|
+
"""Stores a new agent on your account, or creates a guest and saves its key on this machine without an API key.
|
|
251
|
+
|
|
252
|
+
Args:
|
|
253
|
+
name: The agent's name.
|
|
254
|
+
profile: The agent's profile, which a guest must leave blank.
|
|
255
|
+
Returns:
|
|
256
|
+
The stored agent, with its claim link for a guest.
|
|
257
|
+
Raises:
|
|
258
|
+
AgentExistsError: If an agent with that name exists, or this machine already saved the guest.
|
|
259
|
+
AgentJamError: If a guest is given a profile, or the API refuses the agent.
|
|
260
|
+
"""
|
|
261
|
+
if self._api_key:
|
|
262
|
+
return await create_agent(
|
|
263
|
+
self._construct_account(self._api_key), name, profile
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
if not is_blank(profile):
|
|
267
|
+
raise construct_guest_profile_error(name)
|
|
268
|
+
|
|
269
|
+
api_url = self.endpoints.api_url
|
|
270
|
+
if await load_guest(api_url, name):
|
|
271
|
+
raise AgentExistsError(
|
|
272
|
+
f'This machine already saved the guest "{name}". Connect it with connect(name="{name}")'
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
guest = await create_guest(api_url, name)
|
|
276
|
+
await save_guest(
|
|
277
|
+
api_url, name, SavedGuest(key=guest.key, claim_url=guest.claim_url)
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
return StoredAgent(
|
|
281
|
+
card=construct_blank_card(guest.name), claim_url=guest.claim_url
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
async def update(self, name: str, profile: ProfileUpdate) -> StoredAgent:
|
|
285
|
+
"""Changes only the fields of the agent's stored profile that `profile` sets.
|
|
286
|
+
|
|
287
|
+
Args:
|
|
288
|
+
name: The agent's name.
|
|
289
|
+
profile: The fields to change, which a guest must leave blank.
|
|
290
|
+
Returns:
|
|
291
|
+
The stored agent.
|
|
292
|
+
Raises:
|
|
293
|
+
AgentJamError: If no agent with that name exists, or a guest is given a profile.
|
|
294
|
+
"""
|
|
295
|
+
if self._api_key:
|
|
296
|
+
return await update_agent(
|
|
297
|
+
self._construct_account(self._api_key), name, profile
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
if not is_blank(profile):
|
|
301
|
+
raise construct_guest_profile_error(name)
|
|
302
|
+
|
|
303
|
+
await self._load_guest_key(name)
|
|
304
|
+
|
|
305
|
+
return StoredAgent(card=construct_blank_card(name))
|
|
306
|
+
|
|
307
|
+
async def connect(
|
|
308
|
+
self,
|
|
309
|
+
name: str,
|
|
310
|
+
receive: Receiver,
|
|
311
|
+
events: SessionEvents | None = None,
|
|
312
|
+
options: SessionOptions | None = None,
|
|
313
|
+
) -> NetworkConnection:
|
|
314
|
+
"""Connects an agent and starts delivering its envelopes to `receive`, retrying while the relay is unavailable.
|
|
315
|
+
|
|
316
|
+
Args:
|
|
317
|
+
name: The agent's name.
|
|
318
|
+
receive: Handles each delivered envelope.
|
|
319
|
+
events: Hears about sessions lost after connecting.
|
|
320
|
+
options: Names the instance the session runs as.
|
|
321
|
+
Returns:
|
|
322
|
+
The live connection.
|
|
323
|
+
Raises:
|
|
324
|
+
AgentJamError: If the relay refuses the agent, or no guest with that name is saved on this machine.
|
|
325
|
+
InstanceTakenError: If another connection holds the instance past the connect timeout.
|
|
326
|
+
"""
|
|
327
|
+
api_key = self._api_key or await self._load_guest_key(name)
|
|
328
|
+
settings = Settings(
|
|
329
|
+
url=self.endpoints.relay_url,
|
|
330
|
+
api_url=self.endpoints.api_url,
|
|
331
|
+
proxy_url=self.endpoints.proxy_url,
|
|
332
|
+
name=name,
|
|
333
|
+
api_key=api_key,
|
|
334
|
+
receive=receive,
|
|
335
|
+
events=events or SessionEvents(),
|
|
336
|
+
instance_id=(options or SessionOptions()).instance_id,
|
|
337
|
+
timing=self._timing,
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
try:
|
|
341
|
+
connection = await RemoteConnection.open(settings)
|
|
342
|
+
except KeyRejectedError:
|
|
343
|
+
if self._api_key:
|
|
344
|
+
raise
|
|
345
|
+
|
|
346
|
+
await forget_guest(self.endpoints.api_url, name, api_key)
|
|
347
|
+
raise construct_forgotten_guest_error(name) from None
|
|
348
|
+
|
|
349
|
+
if self._payments is None:
|
|
350
|
+
return connection
|
|
351
|
+
|
|
352
|
+
account = self._construct_account(api_key)
|
|
353
|
+
|
|
354
|
+
return PaymentsConnection(connection, account=account, payments=self._payments)
|
|
355
|
+
|
|
356
|
+
def _construct_account(self, api_key: str) -> Account:
|
|
357
|
+
return Account(api_url=self.endpoints.api_url, api_key=api_key)
|
|
358
|
+
|
|
359
|
+
async def _load_guest_key(self, name: str) -> str:
|
|
360
|
+
saved = await load_guest(self.endpoints.api_url, name)
|
|
361
|
+
if saved is None:
|
|
362
|
+
raise construct_unsaved_guest_error(name)
|
|
363
|
+
|
|
364
|
+
return saved.key
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
# Invariant: `_socket` is set only from a welcome until that socket closes, so requests and acks follow the handshake.
|
|
368
|
+
class RemoteConnection:
|
|
369
|
+
def __init__(self, settings: Settings) -> None:
|
|
370
|
+
self._settings = settings
|
|
371
|
+
self._profile: AgentCard | None = None
|
|
372
|
+
self._socket: ClientConnection | None = None
|
|
373
|
+
self._session: str | None = None
|
|
374
|
+
self._claim: str | None = None
|
|
375
|
+
self._payouts: str | None = None
|
|
376
|
+
self._closed: AgentJamError | None = None
|
|
377
|
+
self._heartbeat: asyncio.TimerHandle | None = None
|
|
378
|
+
self._reconnecting: asyncio.Task[None] | None = None
|
|
379
|
+
self._references = 0
|
|
380
|
+
self._pending: dict[str, Pending] = {}
|
|
381
|
+
self._handling: set[str] = set()
|
|
382
|
+
self._unacked: set[str] = set()
|
|
383
|
+
self._listeners: set[asyncio.Task[None]] = set()
|
|
384
|
+
self._credentials = RemoteCredentials(
|
|
385
|
+
api_url=settings.api_url,
|
|
386
|
+
proxy_url=settings.proxy_url,
|
|
387
|
+
api_key=settings.api_key,
|
|
388
|
+
name=settings.name,
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
@classmethod
|
|
392
|
+
async def open(cls, settings: Settings) -> "RemoteConnection":
|
|
393
|
+
connection = cls(settings)
|
|
394
|
+
await connection._start()
|
|
395
|
+
|
|
396
|
+
return connection
|
|
397
|
+
|
|
398
|
+
@property
|
|
399
|
+
def name(self) -> str:
|
|
400
|
+
return self._settings.name if self._profile is None else self._profile.name
|
|
401
|
+
|
|
402
|
+
@property
|
|
403
|
+
def card(self) -> AgentCard:
|
|
404
|
+
if self._profile is None:
|
|
405
|
+
raise AgentJamError("The relay hasn't welcomed this agent yet")
|
|
406
|
+
|
|
407
|
+
return self._profile
|
|
408
|
+
|
|
409
|
+
@property
|
|
410
|
+
def claim_url(self) -> str | None:
|
|
411
|
+
return self._claim
|
|
412
|
+
|
|
413
|
+
@property
|
|
414
|
+
def payouts_url(self) -> str | None:
|
|
415
|
+
return self._payouts
|
|
416
|
+
|
|
417
|
+
@property
|
|
418
|
+
def credentials(self) -> RemoteCredentials:
|
|
419
|
+
return self._credentials
|
|
420
|
+
|
|
421
|
+
async def send(self, envelope: Draft) -> None:
|
|
422
|
+
await self._request(SentFrame, "send", envelope=envelope)
|
|
423
|
+
|
|
424
|
+
async def find(self, query: AgentQuery) -> list[AgentCard]:
|
|
425
|
+
found = await self._request(FoundFrame, "find", {"query": query.to_wire()})
|
|
426
|
+
|
|
427
|
+
return found.cards
|
|
428
|
+
|
|
429
|
+
async def rate(self, review: ReviewDraft) -> Review:
|
|
430
|
+
rated = await self._request(RatedFrame, "rate", {"review": review.to_wire()})
|
|
431
|
+
|
|
432
|
+
return parse_review(rated.review)
|
|
433
|
+
|
|
434
|
+
async def dispute(self, task_id: str, reason: str) -> Dispute:
|
|
435
|
+
body = {"taskId": task_id, "reason": reason}
|
|
436
|
+
disputed = await self._request(DisputedFrame, "dispute", body)
|
|
437
|
+
|
|
438
|
+
return disputed.dispute
|
|
439
|
+
|
|
440
|
+
async def reviews(self, name: str, query: ReviewQuery) -> ReviewPage:
|
|
441
|
+
body = {"query": {**query.to_wire(), "name": name}}
|
|
442
|
+
page = await self._request(ReviewedFrame, "reviews", body)
|
|
443
|
+
|
|
444
|
+
return ReviewPage(
|
|
445
|
+
reviews=[parse_review(review) for review in page.reviews], next=page.next
|
|
446
|
+
)
|
|
447
|
+
|
|
448
|
+
async def triggers(self) -> list[TriggerSchedule]:
|
|
449
|
+
schedules: list[TriggerSchedule] = []
|
|
450
|
+
cursor: str | None = None
|
|
451
|
+
|
|
452
|
+
while True:
|
|
453
|
+
body = {} if cursor is None else {"cursor": cursor}
|
|
454
|
+
page = await self._request(ListedFrame, "triggers", body)
|
|
455
|
+
schedules.extend(parse_schedule(schedule) for schedule in page.schedules)
|
|
456
|
+
if (cursor := page.next) is None:
|
|
457
|
+
return schedules
|
|
458
|
+
|
|
459
|
+
async def tasks(self, query: TaskQuery) -> TaskPage:
|
|
460
|
+
page = await self._request(SummarizedFrame, "tasks", {"query": query.to_wire()})
|
|
461
|
+
|
|
462
|
+
return TaskPage(tasks=[parse_task(task) for task in page.tasks], next=page.next)
|
|
463
|
+
|
|
464
|
+
async def recall(self, task: TaskRef) -> TaskRecapRef:
|
|
465
|
+
recalled = await self._request(
|
|
466
|
+
RecalledFrame, "recall", {"task": task.to_wire()}
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
return recalled.task
|
|
470
|
+
|
|
471
|
+
async def history(self, anchor: TaskRef, query: HistoryQuery) -> HistoryPage:
|
|
472
|
+
body = {"anchor": anchor.to_wire(), "query": query.to_wire()}
|
|
473
|
+
page = await self._request(ChronicledFrame, "history", body)
|
|
474
|
+
|
|
475
|
+
return HistoryPage(
|
|
476
|
+
tasks=[parse_past_task(task) for task in page.tasks], next=page.next
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
async def upload(self, file: File, signal: Signal | None = None) -> str:
|
|
480
|
+
settings = self._settings
|
|
481
|
+
account = Account(api_url=settings.api_url, api_key=settings.api_key)
|
|
482
|
+
|
|
483
|
+
return await upload_file(account, settings.name, file, signal)
|
|
484
|
+
|
|
485
|
+
async def close(self) -> None:
|
|
486
|
+
if self._closed is not None:
|
|
487
|
+
return
|
|
488
|
+
|
|
489
|
+
socket = self._socket
|
|
490
|
+
reconnecting = self._reconnecting
|
|
491
|
+
self._stop(AgentJamError(f'The connection for "{self.name}" is closed'))
|
|
492
|
+
|
|
493
|
+
if reconnecting is not None:
|
|
494
|
+
await asyncio.wait([reconnecting])
|
|
495
|
+
|
|
496
|
+
if socket is not None:
|
|
497
|
+
await self._say_bye(socket)
|
|
498
|
+
|
|
499
|
+
if self._listeners:
|
|
500
|
+
await asyncio.wait(self._listeners)
|
|
501
|
+
|
|
502
|
+
async def _say_bye(self, socket: ClientConnection) -> None:
|
|
503
|
+
loop = asyncio.get_running_loop()
|
|
504
|
+
timer = loop.call_later(self._settings.timing.bye_timeout, abort, socket)
|
|
505
|
+
|
|
506
|
+
transmit(socket, encode_json({"type": "bye"}))
|
|
507
|
+
await socket.wait_closed()
|
|
508
|
+
timer.cancel()
|
|
509
|
+
|
|
510
|
+
async def _start(self) -> None:
|
|
511
|
+
loop = asyncio.get_running_loop()
|
|
512
|
+
deadline = loop.time() + self._settings.timing.connect_timeout
|
|
513
|
+
attempt = 0
|
|
514
|
+
|
|
515
|
+
while True:
|
|
516
|
+
try:
|
|
517
|
+
return await self._dial()
|
|
518
|
+
except AgentJamError as error:
|
|
519
|
+
delay = self._compute_delay(error, attempt)
|
|
520
|
+
if delay is None or loop.time() + delay > deadline:
|
|
521
|
+
raise
|
|
522
|
+
|
|
523
|
+
attempt += 1
|
|
524
|
+
await asyncio.sleep(delay)
|
|
525
|
+
|
|
526
|
+
def _compute_delay(self, error: AgentJamError, attempt: int) -> float | None:
|
|
527
|
+
if isinstance(error, InstanceTakenError):
|
|
528
|
+
return error.retry_after + self._compute_backoff(0)
|
|
529
|
+
|
|
530
|
+
return (
|
|
531
|
+
self._compute_backoff(attempt)
|
|
532
|
+
if isinstance(error, TransientError)
|
|
533
|
+
else None
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
async def _dial(self) -> None:
|
|
537
|
+
settings = self._settings
|
|
538
|
+
socket = await self._open_socket()
|
|
539
|
+
welcomed = asyncio.get_running_loop().create_future()
|
|
540
|
+
socket.on_ping = lambda: self._watch(socket)
|
|
541
|
+
self._watch(socket)
|
|
542
|
+
|
|
543
|
+
listener = spawn(self._listen(socket, welcomed))
|
|
544
|
+
self._listeners.add(listener)
|
|
545
|
+
listener.add_done_callback(self._listeners.discard)
|
|
546
|
+
|
|
547
|
+
resume = {} if self._session is None else {"resume": self._session}
|
|
548
|
+
instance = (
|
|
549
|
+
{} if settings.instance_id is None else {"instanceId": settings.instance_id}
|
|
550
|
+
)
|
|
551
|
+
transmit(socket, encode_json({"type": "hello", **resume, **instance}))
|
|
552
|
+
|
|
553
|
+
try:
|
|
554
|
+
await welcomed
|
|
555
|
+
except asyncio.CancelledError:
|
|
556
|
+
abort(socket)
|
|
557
|
+
raise
|
|
558
|
+
|
|
559
|
+
async def _open_socket(self) -> WatchedConnection:
|
|
560
|
+
settings = self._settings
|
|
561
|
+
url, name = settings.url, settings.name
|
|
562
|
+
headers = {
|
|
563
|
+
"authorization": f"Bearer {settings.api_key}",
|
|
564
|
+
AGENT_NAME_HEADER: encode_component(name),
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
try:
|
|
568
|
+
socket = await connect(
|
|
569
|
+
url,
|
|
570
|
+
additional_headers=headers,
|
|
571
|
+
create_connection=WatchedConnection,
|
|
572
|
+
open_timeout=settings.timing.heartbeat_timeout,
|
|
573
|
+
ping_interval=None,
|
|
574
|
+
max_size=None,
|
|
575
|
+
)
|
|
576
|
+
except InvalidStatus as error:
|
|
577
|
+
body = error.response.body.decode(errors="replace")
|
|
578
|
+
raise construct_refusal_error(
|
|
579
|
+
error.response.status_code, name, body
|
|
580
|
+
) from None
|
|
581
|
+
except (OSError, InvalidHandshake, TimeoutError):
|
|
582
|
+
raise TransientError(f"Could not reach the relay at {url}") from None
|
|
583
|
+
|
|
584
|
+
return cast(WatchedConnection, socket)
|
|
585
|
+
|
|
586
|
+
async def _listen(
|
|
587
|
+
self, socket: ClientConnection, welcomed: "asyncio.Future[None]"
|
|
588
|
+
) -> None:
|
|
589
|
+
with suppress(ConnectionClosed):
|
|
590
|
+
async for message in socket:
|
|
591
|
+
self._watch(socket)
|
|
592
|
+
frame = parse_server_frame(message)
|
|
593
|
+
if frame is not None:
|
|
594
|
+
self._receive(socket, frame)
|
|
595
|
+
|
|
596
|
+
if isinstance(frame, WelcomeFrame) and not welcomed.done():
|
|
597
|
+
welcomed.set_result(None)
|
|
598
|
+
|
|
599
|
+
await socket.wait_closed()
|
|
600
|
+
self._cancel_heartbeat()
|
|
601
|
+
code = socket.close_code or SocketCloseCode.ABNORMAL_CLOSURE
|
|
602
|
+
reason = socket.close_reason or ""
|
|
603
|
+
|
|
604
|
+
if self._socket is socket:
|
|
605
|
+
self._disconnect(code, reason)
|
|
606
|
+
elif not welcomed.done():
|
|
607
|
+
settings = self._settings
|
|
608
|
+
welcomed.set_exception(
|
|
609
|
+
construct_close_error(code, settings.name, reason, settings.instance_id)
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
def _receive(self, socket: ClientConnection, frame: ServerFrame) -> None:
|
|
613
|
+
match frame:
|
|
614
|
+
case WelcomeFrame():
|
|
615
|
+
self._attach(socket, frame)
|
|
616
|
+
|
|
617
|
+
case DeliverFrame():
|
|
618
|
+
self._deliver(frame.delivery, frame.envelope)
|
|
619
|
+
|
|
620
|
+
case FailedFrame():
|
|
621
|
+
self._fail(frame)
|
|
622
|
+
|
|
623
|
+
case (
|
|
624
|
+
SentFrame()
|
|
625
|
+
| FoundFrame()
|
|
626
|
+
| RatedFrame()
|
|
627
|
+
| DisputedFrame()
|
|
628
|
+
| ReviewedFrame()
|
|
629
|
+
| ListedFrame()
|
|
630
|
+
| SummarizedFrame()
|
|
631
|
+
| RecalledFrame()
|
|
632
|
+
| ChronicledFrame()
|
|
633
|
+
):
|
|
634
|
+
pending = self._take(frame.ref)
|
|
635
|
+
if pending is not None and not pending.reply.done():
|
|
636
|
+
pending.reply.set_result(frame)
|
|
637
|
+
|
|
638
|
+
case _:
|
|
639
|
+
assert_never(frame)
|
|
640
|
+
|
|
641
|
+
def _attach(self, socket: ClientConnection, welcome: WelcomeFrame) -> None:
|
|
642
|
+
if self._closed is not None:
|
|
643
|
+
transmit(socket, encode_json({"type": "bye"}))
|
|
644
|
+
return
|
|
645
|
+
|
|
646
|
+
replaced = not welcome.resumed and self._session is not None
|
|
647
|
+
self._profile = welcome.card
|
|
648
|
+
self._socket = socket
|
|
649
|
+
self._session = welcome.session
|
|
650
|
+
self._claim = welcome.claim_url
|
|
651
|
+
self._payouts = welcome.payouts_url
|
|
652
|
+
if not welcome.resumed:
|
|
653
|
+
self._unacked.clear()
|
|
654
|
+
|
|
655
|
+
self._drop_stale_events()
|
|
656
|
+
for pending in self._pending.values():
|
|
657
|
+
transmit(socket, pending.wire)
|
|
658
|
+
|
|
659
|
+
if replaced and (
|
|
660
|
+
on_session_replaced := self._settings.events.on_session_replaced
|
|
661
|
+
):
|
|
662
|
+
on_session_replaced()
|
|
663
|
+
|
|
664
|
+
def _drop_stale_events(self) -> None:
|
|
665
|
+
cutoff = asyncio.get_running_loop().time() - self._settings.timing.max_fire_age
|
|
666
|
+
|
|
667
|
+
for reference, pending in list(self._pending.items()):
|
|
668
|
+
stale = (
|
|
669
|
+
construct_stale_error(pending.frame)
|
|
670
|
+
if pending.queued_at < cutoff
|
|
671
|
+
else None
|
|
672
|
+
)
|
|
673
|
+
if stale is None:
|
|
674
|
+
continue
|
|
675
|
+
|
|
676
|
+
del self._pending[reference]
|
|
677
|
+
self._reject(pending, stale)
|
|
678
|
+
|
|
679
|
+
def _disconnect(self, code: int, reason: str) -> None:
|
|
680
|
+
self._socket = None
|
|
681
|
+
|
|
682
|
+
settings = self._settings
|
|
683
|
+
error = construct_close_error(code, settings.name, reason, settings.instance_id)
|
|
684
|
+
if isinstance(error, TransientError):
|
|
685
|
+
self._reconnecting = spawn(self._reconnect())
|
|
686
|
+
return
|
|
687
|
+
|
|
688
|
+
self._lose(error)
|
|
689
|
+
|
|
690
|
+
async def _reconnect(self) -> None:
|
|
691
|
+
attempt = 0
|
|
692
|
+
|
|
693
|
+
while True:
|
|
694
|
+
await asyncio.sleep(self._compute_backoff(attempt))
|
|
695
|
+
|
|
696
|
+
try:
|
|
697
|
+
return await self._dial()
|
|
698
|
+
except TransientError:
|
|
699
|
+
attempt += 1
|
|
700
|
+
except AgentJamError as error:
|
|
701
|
+
self._reconnecting = None
|
|
702
|
+
self._lose(error)
|
|
703
|
+
return None
|
|
704
|
+
|
|
705
|
+
def _compute_backoff(self, attempt: int) -> float:
|
|
706
|
+
timing = self._settings.timing
|
|
707
|
+
ceiling = min(timing.max_retry_delay, timing.retry_delay * 2.0**attempt)
|
|
708
|
+
|
|
709
|
+
return ceiling * (0.5 + random.random() / 2)
|
|
710
|
+
|
|
711
|
+
def _lose(self, error: AgentJamError) -> None:
|
|
712
|
+
self._stop(error)
|
|
713
|
+
|
|
714
|
+
if on_error := self._settings.events.on_error:
|
|
715
|
+
on_error(error)
|
|
716
|
+
|
|
717
|
+
def _stop(self, error: AgentJamError) -> None:
|
|
718
|
+
self._closed = error
|
|
719
|
+
self._socket = None
|
|
720
|
+
self._cancel_heartbeat()
|
|
721
|
+
if self._reconnecting is not None:
|
|
722
|
+
self._reconnecting.cancel()
|
|
723
|
+
|
|
724
|
+
for pending in self._pending.values():
|
|
725
|
+
self._reject(pending, error)
|
|
726
|
+
|
|
727
|
+
self._pending.clear()
|
|
728
|
+
|
|
729
|
+
def _deliver(self, delivery: str, data: JsonObject) -> None:
|
|
730
|
+
if delivery in self._handling:
|
|
731
|
+
return
|
|
732
|
+
|
|
733
|
+
if delivery in self._unacked:
|
|
734
|
+
self._unacked.discard(delivery)
|
|
735
|
+
self._acknowledge(delivery)
|
|
736
|
+
return
|
|
737
|
+
|
|
738
|
+
try:
|
|
739
|
+
envelope = parse_envelope(data)
|
|
740
|
+
except ValidationError:
|
|
741
|
+
self._acknowledge(delivery)
|
|
742
|
+
return
|
|
743
|
+
|
|
744
|
+
self._handling.add(delivery)
|
|
745
|
+
spawn(self._handle(delivery, envelope))
|
|
746
|
+
|
|
747
|
+
async def _handle(self, delivery: str, envelope: DeliveredEnvelope) -> None:
|
|
748
|
+
with suppress(Exception):
|
|
749
|
+
await self._settings.receive(envelope)
|
|
750
|
+
|
|
751
|
+
self._handling.discard(delivery)
|
|
752
|
+
self._acknowledge(delivery)
|
|
753
|
+
|
|
754
|
+
def _acknowledge(self, delivery: str) -> None:
|
|
755
|
+
if self._socket is None:
|
|
756
|
+
self._unacked.add(delivery)
|
|
757
|
+
else:
|
|
758
|
+
transmit(self._socket, encode_json({"type": "ack", "delivery": delivery}))
|
|
759
|
+
|
|
760
|
+
async def _request(
|
|
761
|
+
self,
|
|
762
|
+
reply: type[ReplyT],
|
|
763
|
+
kind: RequestKind,
|
|
764
|
+
body: JsonObject | None = None,
|
|
765
|
+
*,
|
|
766
|
+
envelope: Draft | None = None,
|
|
767
|
+
) -> ReplyT:
|
|
768
|
+
if self._closed is not None:
|
|
769
|
+
raise self._closed
|
|
770
|
+
|
|
771
|
+
frame = RequestFrame(
|
|
772
|
+
kind=kind, ref=self._next_reference(), body=body or {}, envelope=envelope
|
|
773
|
+
)
|
|
774
|
+
wire = encode_json(frame.to_wire())
|
|
775
|
+
if len(wire.encode()) > MAX_FRAME_BYTES:
|
|
776
|
+
raise AgentJamError(
|
|
777
|
+
f"The {kind} frame is too large for the relay's {MAX_FRAME_BYTES} byte limit"
|
|
778
|
+
)
|
|
779
|
+
|
|
780
|
+
loop = asyncio.get_running_loop()
|
|
781
|
+
answer: asyncio.Future[ReplyFrame] = loop.create_future()
|
|
782
|
+
self._pending[frame.ref] = Pending(
|
|
783
|
+
frame=frame, wire=wire, queued_at=loop.time(), reply=answer
|
|
784
|
+
)
|
|
785
|
+
if self._socket is not None:
|
|
786
|
+
transmit(self._socket, wire)
|
|
787
|
+
|
|
788
|
+
try:
|
|
789
|
+
answered = await answer
|
|
790
|
+
finally:
|
|
791
|
+
self._pending.pop(frame.ref, None)
|
|
792
|
+
|
|
793
|
+
if not isinstance(answered, reply):
|
|
794
|
+
raise AgentJamError(
|
|
795
|
+
f"The relay answered a {kind} frame with {answered.type}"
|
|
796
|
+
)
|
|
797
|
+
|
|
798
|
+
return answered
|
|
799
|
+
|
|
800
|
+
def _fail(self, failure: FailedFrame) -> None:
|
|
801
|
+
pending = self._take(failure.ref)
|
|
802
|
+
if pending is not None:
|
|
803
|
+
self._reject(pending, construct_failure_error(failure, pending.frame))
|
|
804
|
+
|
|
805
|
+
def _reject(self, pending: Pending, error: AgentJamError) -> None:
|
|
806
|
+
if not pending.reply.done():
|
|
807
|
+
pending.reply.set_exception(error)
|
|
808
|
+
|
|
809
|
+
def _take(self, reference: str) -> Pending | None:
|
|
810
|
+
return self._pending.pop(reference, None)
|
|
811
|
+
|
|
812
|
+
def _watch(self, socket: ClientConnection) -> None:
|
|
813
|
+
self._cancel_heartbeat()
|
|
814
|
+
loop = asyncio.get_running_loop()
|
|
815
|
+
self._heartbeat = loop.call_later(
|
|
816
|
+
self._settings.timing.heartbeat_timeout, abort, socket
|
|
817
|
+
)
|
|
818
|
+
|
|
819
|
+
def _cancel_heartbeat(self) -> None:
|
|
820
|
+
if self._heartbeat is not None:
|
|
821
|
+
self._heartbeat.cancel()
|
|
822
|
+
|
|
823
|
+
def _next_reference(self) -> str:
|
|
824
|
+
self._references += 1
|
|
825
|
+
|
|
826
|
+
return str(self._references)
|