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,443 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from enum import IntEnum
|
|
4
|
+
from typing import Annotated, Any, Literal, TypeAlias, cast
|
|
5
|
+
|
|
6
|
+
from pydantic import Field, TypeAdapter, ValidationError
|
|
7
|
+
|
|
8
|
+
from agentjam._errors import (
|
|
9
|
+
AgentJamError,
|
|
10
|
+
AgentNotFoundError,
|
|
11
|
+
InstanceTakenError,
|
|
12
|
+
InvalidInputError,
|
|
13
|
+
PaymentRequiredError,
|
|
14
|
+
PaymentRequiredReason,
|
|
15
|
+
ReassignedError,
|
|
16
|
+
SkillRequiredError,
|
|
17
|
+
TaskCommittedError,
|
|
18
|
+
UncoveredCostError,
|
|
19
|
+
)
|
|
20
|
+
from agentjam._models import WireModel
|
|
21
|
+
from agentjam._protocol import LimitCode, Routed, TaskRecapRef
|
|
22
|
+
from agentjam._relay.base import Draft
|
|
23
|
+
from agentjam._types import (
|
|
24
|
+
AgentCard,
|
|
25
|
+
Dispute,
|
|
26
|
+
JsonObject,
|
|
27
|
+
PastTask,
|
|
28
|
+
Review,
|
|
29
|
+
TaskStatus,
|
|
30
|
+
TaskSummary,
|
|
31
|
+
TaskWatch,
|
|
32
|
+
TriggerSchedule,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
RequestKind = Literal[
|
|
36
|
+
"send",
|
|
37
|
+
"find",
|
|
38
|
+
"rate",
|
|
39
|
+
"dispute",
|
|
40
|
+
"reviews",
|
|
41
|
+
"triggers",
|
|
42
|
+
"tasks",
|
|
43
|
+
"recall",
|
|
44
|
+
"history",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
FailureCode = Literal[
|
|
48
|
+
"agent_not_found",
|
|
49
|
+
"invalid_frame",
|
|
50
|
+
"forbidden",
|
|
51
|
+
"conflict",
|
|
52
|
+
"payment_required",
|
|
53
|
+
"skill_required",
|
|
54
|
+
"invalid_input",
|
|
55
|
+
"reassigned",
|
|
56
|
+
"committed",
|
|
57
|
+
"uncovered_cost",
|
|
58
|
+
"internal",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
MAX_FRAME_BYTES = 1024 * 1024
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class CloseCode(IntEnum):
|
|
65
|
+
POLICY_VIOLATION = 1008
|
|
66
|
+
NAME_TAKEN = 4409
|
|
67
|
+
SESSION_LOST = 4410
|
|
68
|
+
AGENT_CHANGED = 4205
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True, kw_only=True)
|
|
72
|
+
class RequestFrame:
|
|
73
|
+
"""A request frame the relay answers under its `ref`, with the envelope a send carries."""
|
|
74
|
+
|
|
75
|
+
kind: RequestKind
|
|
76
|
+
ref: str
|
|
77
|
+
body: JsonObject = field(default_factory=dict)
|
|
78
|
+
envelope: Draft | None = None
|
|
79
|
+
|
|
80
|
+
def to_wire(self) -> JsonObject:
|
|
81
|
+
envelope = (
|
|
82
|
+
{} if self.envelope is None else {"envelope": self.envelope.to_wire()}
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
return {"type": self.kind, "ref": self.ref, **self.body, **envelope}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class WireReview(WireModel):
|
|
89
|
+
id: str = Field(alias="_id")
|
|
90
|
+
task_id: str
|
|
91
|
+
requester: str
|
|
92
|
+
executor: str
|
|
93
|
+
rating: int
|
|
94
|
+
text: str | None = None
|
|
95
|
+
created_at: str
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class WireTriggerSchedule(WireModel):
|
|
99
|
+
schedule_id: str
|
|
100
|
+
requester: str
|
|
101
|
+
principal: str | None = None
|
|
102
|
+
text: str
|
|
103
|
+
skill: str
|
|
104
|
+
trigger: str
|
|
105
|
+
config: dict[str, Any]
|
|
106
|
+
input: JsonObject | None = None
|
|
107
|
+
expires_at: str | None = None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class WireTaskSummary(WireModel):
|
|
111
|
+
task_id: str
|
|
112
|
+
agent: str
|
|
113
|
+
status: TaskStatus
|
|
114
|
+
text: str
|
|
115
|
+
update: str | None = None
|
|
116
|
+
has_result: bool
|
|
117
|
+
unread: bool
|
|
118
|
+
watch: TaskWatch | None = None
|
|
119
|
+
created_at: str
|
|
120
|
+
ended_at: str | None = None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class WirePastTask(WireModel):
|
|
124
|
+
requester: str
|
|
125
|
+
task_id: str
|
|
126
|
+
run: int | None = None
|
|
127
|
+
skill: str | None = None
|
|
128
|
+
status: TaskStatus
|
|
129
|
+
has_result: bool
|
|
130
|
+
created_at: str
|
|
131
|
+
ended_at: str | None = None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class WelcomeFrame(WireModel):
|
|
135
|
+
type: Literal["welcome"]
|
|
136
|
+
name: str
|
|
137
|
+
card: AgentCard
|
|
138
|
+
session: str
|
|
139
|
+
resumed: bool
|
|
140
|
+
claim_url: str | None = None
|
|
141
|
+
payouts_url: str | None = None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class SentFrame(WireModel):
|
|
145
|
+
type: Literal["sent"]
|
|
146
|
+
ref: str
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class FailedFrame(WireModel):
|
|
150
|
+
type: Literal["failed"]
|
|
151
|
+
ref: str
|
|
152
|
+
code: str
|
|
153
|
+
message: str
|
|
154
|
+
reason: str | None = None
|
|
155
|
+
setup_url: str | None = None
|
|
156
|
+
required_cents: int | float | None = None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class FoundFrame(WireModel):
|
|
160
|
+
type: Literal["found"]
|
|
161
|
+
ref: str
|
|
162
|
+
cards: list[AgentCard]
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class RatedFrame(WireModel):
|
|
166
|
+
type: Literal["rated"]
|
|
167
|
+
ref: str
|
|
168
|
+
review: WireReview
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class DisputedFrame(WireModel):
|
|
172
|
+
type: Literal["disputed"]
|
|
173
|
+
ref: str
|
|
174
|
+
dispute: Dispute
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class ReviewedFrame(WireModel):
|
|
178
|
+
type: Literal["reviewed"]
|
|
179
|
+
ref: str
|
|
180
|
+
reviews: list[WireReview]
|
|
181
|
+
next: str | None = None
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class ListedFrame(WireModel):
|
|
185
|
+
type: Literal["listed"]
|
|
186
|
+
ref: str
|
|
187
|
+
schedules: list[WireTriggerSchedule]
|
|
188
|
+
next: str | None = None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class SummarizedFrame(WireModel):
|
|
192
|
+
type: Literal["summarized"]
|
|
193
|
+
ref: str
|
|
194
|
+
tasks: list[WireTaskSummary]
|
|
195
|
+
next: str | None = None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class RecalledFrame(WireModel):
|
|
199
|
+
type: Literal["recalled"]
|
|
200
|
+
ref: str
|
|
201
|
+
task: TaskRecapRef
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class ChronicledFrame(WireModel):
|
|
205
|
+
type: Literal["chronicled"]
|
|
206
|
+
ref: str
|
|
207
|
+
tasks: list[WirePastTask]
|
|
208
|
+
next: str | None = None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class DeliverFrame(WireModel):
|
|
212
|
+
type: Literal["deliver"]
|
|
213
|
+
delivery: str
|
|
214
|
+
envelope: JsonObject
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
ReplyFrame: TypeAlias = (
|
|
218
|
+
SentFrame
|
|
219
|
+
| FoundFrame
|
|
220
|
+
| RatedFrame
|
|
221
|
+
| DisputedFrame
|
|
222
|
+
| ReviewedFrame
|
|
223
|
+
| ListedFrame
|
|
224
|
+
| SummarizedFrame
|
|
225
|
+
| RecalledFrame
|
|
226
|
+
| ChronicledFrame
|
|
227
|
+
)
|
|
228
|
+
"""The server frame that answers a request frame."""
|
|
229
|
+
|
|
230
|
+
ServerFrame: TypeAlias = WelcomeFrame | FailedFrame | DeliverFrame | ReplyFrame
|
|
231
|
+
|
|
232
|
+
server_frame_adapter: TypeAdapter[ServerFrame] = TypeAdapter(
|
|
233
|
+
Annotated[ServerFrame, Field(discriminator="type")]
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
class TransientError(AgentJamError):
|
|
238
|
+
"""A connection failure that reconnecting can recover from."""
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class KeyRejectedError(AgentJamError):
|
|
242
|
+
"""The relay refused the API key, because no agent holds it anymore."""
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def parse_server_frame(data: str | bytes) -> ServerFrame | None:
|
|
246
|
+
"""Parses a frame from the relay, or returns None for one this SDK doesn't know."""
|
|
247
|
+
try:
|
|
248
|
+
return server_frame_adapter.validate_json(data)
|
|
249
|
+
except ValidationError:
|
|
250
|
+
return None
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def parse_retry_after(reason: str) -> float | None:
|
|
254
|
+
try:
|
|
255
|
+
retry_after = json.loads(reason).get("retryAfterMs")
|
|
256
|
+
except (ValueError, AttributeError):
|
|
257
|
+
return None
|
|
258
|
+
|
|
259
|
+
is_number = isinstance(retry_after, int | float) and not isinstance(
|
|
260
|
+
retry_after, bool
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
return retry_after / 1000 if is_number else None
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def construct_taken_error(
|
|
267
|
+
name: str, reason: str, instance_id: str | None = None
|
|
268
|
+
) -> AgentJamError:
|
|
269
|
+
retry_after = parse_retry_after(reason)
|
|
270
|
+
if instance_id is None or retry_after is None:
|
|
271
|
+
return AgentJamError(f'An agent named "{name}" is already connected')
|
|
272
|
+
|
|
273
|
+
return InstanceTakenError(name, instance_id, retry_after)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def describe_unclaimed(to: str, claim_url: str | None) -> str:
|
|
277
|
+
claim = f" at {claim_url}" if claim_url else ""
|
|
278
|
+
|
|
279
|
+
return f"{to} charges for this task, and guest agents can only run free tasks. Ask your human to claim this agent{claim}, then try again"
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def describe_setup(reason: str | None, setup_url: str) -> str:
|
|
283
|
+
match reason:
|
|
284
|
+
case "exceeds_cap":
|
|
285
|
+
return f"The task holds more up front than your whole monthly spending cap, so ask your human to raise the cap at {setup_url}"
|
|
286
|
+
|
|
287
|
+
case "cap_reached":
|
|
288
|
+
return f"This month's spending cap is used up, so ask your human to raise it at {setup_url}"
|
|
289
|
+
|
|
290
|
+
case "insufficient_credits":
|
|
291
|
+
return f"Ask your human to add credits for this agent at {setup_url}"
|
|
292
|
+
|
|
293
|
+
case (
|
|
294
|
+
"no_payment_method"
|
|
295
|
+
| "invalid_payment"
|
|
296
|
+
| "price_too_high"
|
|
297
|
+
| "below_card_minimum"
|
|
298
|
+
| "payment_failed"
|
|
299
|
+
):
|
|
300
|
+
return f"Ask your human to save a card for this agent at {setup_url}"
|
|
301
|
+
|
|
302
|
+
case _:
|
|
303
|
+
return f"Ask your human to fix {reason} at {setup_url}"
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def get_recipient(request: RequestFrame) -> str | None:
|
|
307
|
+
envelope = request.envelope
|
|
308
|
+
if request.kind != "send" or not isinstance(envelope, Routed):
|
|
309
|
+
return None
|
|
310
|
+
|
|
311
|
+
return envelope.to
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def construct_payment_error(failure: FailedFrame, to: str) -> PaymentRequiredError:
|
|
315
|
+
reason = cast(PaymentRequiredReason, failure.reason)
|
|
316
|
+
setup_url = failure.setup_url
|
|
317
|
+
if reason == "unclaimed":
|
|
318
|
+
return PaymentRequiredError(
|
|
319
|
+
reason, describe_unclaimed(to, setup_url), setup_url
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
setup = f". {describe_setup(reason, setup_url)}" if setup_url else ""
|
|
323
|
+
|
|
324
|
+
return PaymentRequiredError(
|
|
325
|
+
reason, f"{to} requires payment for this task ({reason}){setup}", setup_url
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def construct_failure_error(
|
|
330
|
+
failure: FailedFrame, request: RequestFrame
|
|
331
|
+
) -> AgentJamError:
|
|
332
|
+
to = get_recipient(request)
|
|
333
|
+
generic = AgentJamError(failure.message)
|
|
334
|
+
|
|
335
|
+
match failure.code:
|
|
336
|
+
case "agent_not_found":
|
|
337
|
+
return generic if to is None else AgentNotFoundError(to)
|
|
338
|
+
|
|
339
|
+
case "payment_required":
|
|
340
|
+
return generic if to is None else construct_payment_error(failure, to)
|
|
341
|
+
|
|
342
|
+
case "skill_required":
|
|
343
|
+
return generic if to is None else SkillRequiredError(to, failure.message)
|
|
344
|
+
|
|
345
|
+
case "invalid_input":
|
|
346
|
+
return generic if to is None else InvalidInputError(to, failure.message)
|
|
347
|
+
|
|
348
|
+
case "reassigned":
|
|
349
|
+
return ReassignedError(failure.message)
|
|
350
|
+
|
|
351
|
+
case "committed":
|
|
352
|
+
return TaskCommittedError(failure.message)
|
|
353
|
+
|
|
354
|
+
case "uncovered_cost":
|
|
355
|
+
if failure.required_cents is None or failure.reason is None:
|
|
356
|
+
return generic
|
|
357
|
+
|
|
358
|
+
code = cast(LimitCode, failure.reason)
|
|
359
|
+
|
|
360
|
+
return UncoveredCostError(failure.message, failure.required_cents, code)
|
|
361
|
+
|
|
362
|
+
case "invalid_frame" | "forbidden" | "conflict" | "internal":
|
|
363
|
+
return generic
|
|
364
|
+
|
|
365
|
+
case _:
|
|
366
|
+
return AgentJamError(f"The relay failed with {failure.code}")
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def parse_review(review: WireReview) -> Review:
|
|
370
|
+
return Review.model_validate(review.model_dump(by_alias=False))
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def parse_schedule(schedule: WireTriggerSchedule) -> TriggerSchedule:
|
|
374
|
+
fields = schedule.model_dump(by_alias=False, exclude={"schedule_id", "requester"})
|
|
375
|
+
|
|
376
|
+
return TriggerSchedule.model_validate(
|
|
377
|
+
{**fields, "id": schedule.schedule_id, "sender": schedule.requester}
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def parse_task(task: WireTaskSummary) -> TaskSummary:
|
|
382
|
+
fields = task.model_dump(by_alias=False, exclude={"task_id"})
|
|
383
|
+
|
|
384
|
+
return TaskSummary.model_validate({**fields, "id": task.task_id})
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def parse_past_task(task: WirePastTask) -> PastTask:
|
|
388
|
+
fields = task.model_dump(by_alias=False, exclude={"task_id"})
|
|
389
|
+
|
|
390
|
+
return PastTask.model_validate({**fields, "id": task.task_id})
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def construct_close_error(
|
|
394
|
+
code: int, name: str, reason: str = "", instance_id: str | None = None
|
|
395
|
+
) -> AgentJamError:
|
|
396
|
+
match code:
|
|
397
|
+
case CloseCode.NAME_TAKEN:
|
|
398
|
+
return construct_taken_error(name, reason, instance_id)
|
|
399
|
+
|
|
400
|
+
case CloseCode.SESSION_LOST:
|
|
401
|
+
return AgentJamError(
|
|
402
|
+
f'Another connection took over the session of "{name}"'
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
case CloseCode.POLICY_VIOLATION:
|
|
406
|
+
detail = f": {reason}" if reason else ""
|
|
407
|
+
|
|
408
|
+
return AgentJamError(
|
|
409
|
+
f'The relay closed the connection of "{name}" for breaking the protocol{detail}'
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
case CloseCode.AGENT_CHANGED:
|
|
413
|
+
return TransientError(
|
|
414
|
+
f'The relay asked "{name}" to reconnect after it changed'
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
case _:
|
|
418
|
+
return TransientError(f"The relay closed the connection with {code}")
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def construct_invalid_name(name: str) -> AgentJamError:
|
|
422
|
+
return AgentJamError(
|
|
423
|
+
f'"{name}" isn\'t a valid agent name. Use 1 to 64 letters, digits, hyphens or underscores, starting with a letter or digit'
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def construct_refusal_error(status: int, name: str, body: str) -> AgentJamError:
|
|
428
|
+
if status == 401:
|
|
429
|
+
return KeyRejectedError("The relay rejected the API key")
|
|
430
|
+
|
|
431
|
+
if status == 400:
|
|
432
|
+
return construct_invalid_name(name)
|
|
433
|
+
|
|
434
|
+
if status in (403, 404):
|
|
435
|
+
return AgentJamError(body or f'Your API key can\'t connect "{name}"')
|
|
436
|
+
|
|
437
|
+
message = f"The relay refused to connect with {status}"
|
|
438
|
+
|
|
439
|
+
return (
|
|
440
|
+
TransientError(message)
|
|
441
|
+
if status >= 500 or status == 429
|
|
442
|
+
else AgentJamError(message)
|
|
443
|
+
)
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import threading
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from pydantic import ValidationError
|
|
10
|
+
|
|
11
|
+
from agentjam._models import WireModel
|
|
12
|
+
|
|
13
|
+
Saved = dict[str, Any]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SavedGuest(WireModel):
|
|
17
|
+
"""A guest `create()` made, saved so `connect()` can connect it by name."""
|
|
18
|
+
|
|
19
|
+
key: str
|
|
20
|
+
claim_url: str
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# WARNING: a threading lock rather than an asyncio one, since relays on different event loops share the file.
|
|
24
|
+
lock = threading.Lock()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def get_store_path() -> Path:
|
|
28
|
+
config = os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config"
|
|
29
|
+
|
|
30
|
+
return Path(config) / "agentjam" / "guests.json"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def read_store(path: Path) -> Saved:
|
|
34
|
+
try:
|
|
35
|
+
saved = json.loads(path.read_text())
|
|
36
|
+
except (OSError, ValueError):
|
|
37
|
+
return {}
|
|
38
|
+
|
|
39
|
+
return saved if isinstance(saved, dict) else {}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def write_store(path: Path, saved: Saved) -> None:
|
|
43
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
44
|
+
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
45
|
+
|
|
46
|
+
with os.fdopen(descriptor, "w") as file:
|
|
47
|
+
file.write(json.dumps(saved, indent=2))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def get_guests(saved: Saved, api_url: str) -> Saved:
|
|
51
|
+
guests = saved.get(api_url)
|
|
52
|
+
|
|
53
|
+
return guests if isinstance(guests, dict) else {}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def update_store(change: Callable[[Saved], Saved | None]) -> None:
|
|
57
|
+
with lock:
|
|
58
|
+
path = get_store_path()
|
|
59
|
+
saved = change(read_store(path))
|
|
60
|
+
if saved is None:
|
|
61
|
+
return
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
write_store(path, saved)
|
|
65
|
+
except OSError:
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def read_guest(api_url: str, name: str) -> SavedGuest | None:
|
|
70
|
+
with lock:
|
|
71
|
+
guest = get_guests(read_store(get_store_path()), api_url).get(name)
|
|
72
|
+
|
|
73
|
+
try:
|
|
74
|
+
return SavedGuest.model_validate(guest)
|
|
75
|
+
except ValidationError:
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def store_guest(api_url: str, name: str, guest: SavedGuest) -> None:
|
|
80
|
+
update_store(
|
|
81
|
+
lambda saved: {
|
|
82
|
+
**saved,
|
|
83
|
+
api_url: {**get_guests(saved, api_url), name: guest.to_wire()},
|
|
84
|
+
}
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def remove_guest(api_url: str, name: str, key: str) -> None:
|
|
89
|
+
def change(saved: Saved) -> Saved | None:
|
|
90
|
+
guests = get_guests(saved, api_url)
|
|
91
|
+
guest = guests.get(name)
|
|
92
|
+
if not isinstance(guest, dict) or guest.get("key") != key:
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
others = {other: value for other, value in guests.items() if other != name}
|
|
96
|
+
|
|
97
|
+
return {**saved, api_url: others}
|
|
98
|
+
|
|
99
|
+
update_store(change)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
async def load_guest(api_url: str, name: str) -> SavedGuest | None:
|
|
103
|
+
"""Loads the guest saved under a name on a network, or None if there's none or the store can't be read."""
|
|
104
|
+
return await asyncio.to_thread(read_guest, api_url, name)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
async def save_guest(api_url: str, name: str, guest: SavedGuest) -> None:
|
|
108
|
+
"""Saves a guest under its name, ignoring a failed write since the guest still works for this run."""
|
|
109
|
+
await asyncio.to_thread(store_guest, api_url, name, guest)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
async def forget_guest(api_url: str, name: str, key: str) -> None:
|
|
113
|
+
"""Forgets the guest saved under a name, unless another run already replaced it with another key."""
|
|
114
|
+
await asyncio.to_thread(remove_guest, api_url, name, key)
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import httpx
|
|
2
|
+
|
|
3
|
+
from agentjam._errors import AgentExistsError, AgentJamError
|
|
4
|
+
from agentjam._models import WireModel
|
|
5
|
+
from agentjam._relay.frames import construct_invalid_name
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class GuestCredentials(WireModel):
|
|
9
|
+
name: str
|
|
10
|
+
key: str
|
|
11
|
+
claim_url: str
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def construct_taken_name_error(name: str) -> AgentExistsError:
|
|
15
|
+
return AgentExistsError(
|
|
16
|
+
f"The name \"{name}\" is taken. If that agent is yours, pass your account's api_key or set AGENTJAM_API_KEY. Otherwise, use a name that isn't taken for the guest"
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def construct_too_many_guests_error(retry_after: str | None) -> AgentJamError:
|
|
21
|
+
wait = f"in {retry_after} seconds" if retry_after else "later"
|
|
22
|
+
|
|
23
|
+
return AgentJamError(
|
|
24
|
+
f"Too many guests were created from this address. Try again {wait}, or reuse a guest's key through AGENTJAM_API_KEY"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def construct_refusal_error(response: httpx.Response, name: str) -> AgentJamError:
|
|
29
|
+
match response.status_code:
|
|
30
|
+
case 400:
|
|
31
|
+
return construct_invalid_name(name)
|
|
32
|
+
|
|
33
|
+
case 409:
|
|
34
|
+
return construct_taken_name_error(name)
|
|
35
|
+
|
|
36
|
+
case 429:
|
|
37
|
+
return construct_too_many_guests_error(response.headers.get("retry-after"))
|
|
38
|
+
|
|
39
|
+
case status:
|
|
40
|
+
return AgentJamError(f"Creating a guest failed with {status}")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def create_guest(api_url: str, name: str) -> GuestCredentials:
|
|
44
|
+
try:
|
|
45
|
+
async with httpx.AsyncClient() as client:
|
|
46
|
+
response = await client.post(
|
|
47
|
+
f"{api_url}/agents/guests", json={"name": name}
|
|
48
|
+
)
|
|
49
|
+
except httpx.TransportError:
|
|
50
|
+
raise AgentJamError(f"Could not reach the AgentJam API at {api_url}") from None
|
|
51
|
+
|
|
52
|
+
if not response.is_success:
|
|
53
|
+
raise construct_refusal_error(response, name)
|
|
54
|
+
|
|
55
|
+
return GuestCredentials.model_validate(response.json()["data"])
|