agentjam 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. agentjam/__init__.py +435 -0
  2. agentjam/_adapters/__init__.py +0 -0
  3. agentjam/_adapters/responses.py +73 -0
  4. agentjam/_adapters/shared.py +435 -0
  5. agentjam/_agent.py +1032 -0
  6. agentjam/_agent_access.py +360 -0
  7. agentjam/_agent_delegations.py +376 -0
  8. agentjam/_agent_executions.py +566 -0
  9. agentjam/_agent_judging.py +288 -0
  10. agentjam/_agent_options.py +122 -0
  11. agentjam/_agent_routing.py +214 -0
  12. agentjam/_agent_session.py +195 -0
  13. agentjam/_agent_support.py +415 -0
  14. agentjam/_artifacts.py +565 -0
  15. agentjam/_attachments.py +112 -0
  16. agentjam/_connections.py +1282 -0
  17. agentjam/_content.py +29 -0
  18. agentjam/_cron.py +302 -0
  19. agentjam/_errors.py +238 -0
  20. agentjam/_events.py +113 -0
  21. agentjam/_files.py +55 -0
  22. agentjam/_github.py +742 -0
  23. agentjam/_idempotency.py +68 -0
  24. agentjam/_inputs.py +79 -0
  25. agentjam/_models.py +21 -0
  26. agentjam/_polling.py +139 -0
  27. agentjam/_profile.py +244 -0
  28. agentjam/_protocol.py +480 -0
  29. agentjam/_providers.py +365 -0
  30. agentjam/_recaps.py +67 -0
  31. agentjam/_relay/__init__.py +0 -0
  32. agentjam/_relay/actions.py +234 -0
  33. agentjam/_relay/artifacts.py +96 -0
  34. agentjam/_relay/base.py +387 -0
  35. agentjam/_relay/commits.py +77 -0
  36. agentjam/_relay/copies.py +66 -0
  37. agentjam/_relay/credentials.py +127 -0
  38. agentjam/_relay/endpoints.py +39 -0
  39. agentjam/_relay/follow_ups.py +548 -0
  40. agentjam/_relay/frames.py +443 -0
  41. agentjam/_relay/guest_store.py +114 -0
  42. agentjam/_relay/guests.py +55 -0
  43. agentjam/_relay/inputs.py +119 -0
  44. agentjam/_relay/lineage.py +294 -0
  45. agentjam/_relay/memory.py +1045 -0
  46. agentjam/_relay/payments.py +204 -0
  47. agentjam/_relay/profiles.py +95 -0
  48. agentjam/_relay/remote.py +826 -0
  49. agentjam/_relay/resumptions.py +65 -0
  50. agentjam/_relay/revisions.py +43 -0
  51. agentjam/_relay/schedule_follow_ups.py +274 -0
  52. agentjam/_relay/schedules.py +547 -0
  53. agentjam/_relay/secrets.py +275 -0
  54. agentjam/_relay/sessions.py +640 -0
  55. agentjam/_relay/uploads.py +71 -0
  56. agentjam/_requests.py +178 -0
  57. agentjam/_screening.py +368 -0
  58. agentjam/_secrets.py +153 -0
  59. agentjam/_sentry.py +233 -0
  60. agentjam/_signals.py +98 -0
  61. agentjam/_slack.py +468 -0
  62. agentjam/_stripe.py +93 -0
  63. agentjam/_tasks/__init__.py +0 -0
  64. agentjam/_tasks/access.py +142 -0
  65. agentjam/_tasks/incoming.py +952 -0
  66. agentjam/_tasks/outgoing.py +472 -0
  67. agentjam/_tasks/scheduled.py +206 -0
  68. agentjam/_tasks/serial.py +40 -0
  69. agentjam/_tasks/triggers.py +258 -0
  70. agentjam/_tasks/watches.py +77 -0
  71. agentjam/_tools.py +1035 -0
  72. agentjam/_types.py +965 -0
  73. agentjam/_utils.py +75 -0
  74. agentjam/_verdicts.py +21 -0
  75. agentjam/_watermarks.py +59 -0
  76. agentjam/anthropic.py +442 -0
  77. agentjam/mpp.py +233 -0
  78. agentjam/openai.py +141 -0
  79. agentjam/openai_agents.py +253 -0
  80. agentjam/py.typed +0 -0
  81. agentjam/pydantic_ai.py +301 -0
  82. agentjam/skills.py +69 -0
  83. agentjam-0.1.0.dist-info/METADATA +210 -0
  84. agentjam-0.1.0.dist-info/RECORD +86 -0
  85. agentjam-0.1.0.dist-info/WHEEL +4 -0
  86. agentjam-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,204 @@
1
+ from collections.abc import Awaitable, Callable
2
+ from dataclasses import dataclass
3
+ from typing import Any, Literal
4
+
5
+ import httpx
6
+
7
+ from agentjam._errors import AgentJamError, PaymentRequiredError
8
+ from agentjam._files import File
9
+ from agentjam._protocol import TaskRecapRef, TaskRef
10
+ from agentjam._relay.base import (
11
+ CredentialChannel,
12
+ Draft,
13
+ NetworkConnection,
14
+ TriggerListingConnection,
15
+ )
16
+ from agentjam._relay.endpoints import AGENT_NAME_HEADER, encode_component
17
+ from agentjam._relay.profiles import Account, parse_body
18
+ from agentjam._signals import Signal
19
+ from agentjam._types import (
20
+ AgentCard,
21
+ AgentQuery,
22
+ AutoReloadSettings,
23
+ CreditAccount,
24
+ Dispute,
25
+ HistoryPage,
26
+ HistoryQuery,
27
+ Review,
28
+ ReviewDraft,
29
+ ReviewPage,
30
+ ReviewQuery,
31
+ TaskPage,
32
+ TaskQuery,
33
+ TriggerSchedule,
34
+ )
35
+
36
+ Pay = Callable[[httpx.Request, int], Awaitable[httpx.Response]]
37
+ """Sends a request to the AgentJam API, paying its MPP challenge for `amount_cents`, and returns the read response."""
38
+
39
+
40
+ @dataclass(frozen=True, kw_only=True)
41
+ class Payments:
42
+ """Buys AgentJam credits over MPP. Create one with `stripe_payments()` or `mpp_payments()` from `agentjam.mpp`.
43
+
44
+ Each callable takes the request to send and the cents it may pay, and returns the read response.
45
+ """
46
+
47
+ buy: Pay
48
+ """Sends a purchase of `amount_cents` to the AgentJam API, paying only a challenge for exactly that."""
49
+ subscribe: Pay | None = None
50
+ """Sends an auto-reload of up to `amount_cents` a period, granting a recurring token for exactly that. Payments without a recurring token leave it out."""
51
+
52
+
53
+ @dataclass(frozen=True, kw_only=True)
54
+ class Purchase:
55
+ path: Literal["credits", "credits/auto-reload"]
56
+ body: dict[str, Any]
57
+ subject: str
58
+ """What's being paid for, as an error message names it."""
59
+ amount_cents: int
60
+ pay: Pay
61
+
62
+
63
+ def construct_purchase_error(
64
+ response: httpx.Response, purchase: Purchase
65
+ ) -> PaymentRequiredError:
66
+ body = parse_body(response)
67
+ detail = body.get("detail")
68
+ data: dict[str, Any] = body["data"] if isinstance(body.get("data"), dict) else {}
69
+ claim_url = data.get("claimUrl")
70
+ if data.get("reason") == "unclaimed" and isinstance(claim_url, str):
71
+ return PaymentRequiredError(
72
+ "unclaimed",
73
+ f"Guest agents can't buy credits or pay for tasks. Ask your human to claim this agent at {claim_url}, then try again",
74
+ claim_url,
75
+ )
76
+
77
+ message = data.get("message")
78
+ if response.status_code in (400, 403) and isinstance(message, str):
79
+ below_minimum = data.get("reason") == "below_card_minimum"
80
+
81
+ return PaymentRequiredError(
82
+ "below_card_minimum" if below_minimum else "payment_failed", message
83
+ )
84
+
85
+ suffix = f": {detail}" if isinstance(detail, str) else ""
86
+
87
+ return PaymentRequiredError(
88
+ "payment_failed",
89
+ f"Paying {purchase.subject} failed with {response.status_code}{suffix}",
90
+ )
91
+
92
+
93
+ class PaymentsConnection:
94
+ """Buys credits for the owner of the agent behind `connection`, paying over MPP."""
95
+
96
+ def __init__(
97
+ self, connection: NetworkConnection, *, account: Account, payments: Payments
98
+ ) -> None:
99
+ self._connection = connection
100
+ self._account = account
101
+ self._payments = payments
102
+
103
+ @property
104
+ def name(self) -> str:
105
+ return self._connection.name
106
+
107
+ @property
108
+ def card(self) -> AgentCard:
109
+ return self._connection.card
110
+
111
+ @property
112
+ def claim_url(self) -> str | None:
113
+ return self._connection.claim_url
114
+
115
+ @property
116
+ def payouts_url(self) -> str | None:
117
+ return self._connection.payouts_url
118
+
119
+ @property
120
+ def credentials(self) -> CredentialChannel | None:
121
+ return self._connection.credentials
122
+
123
+ async def send(self, envelope: Draft) -> None:
124
+ await self._connection.send(envelope)
125
+
126
+ async def top_up(self, amount_cents: int) -> CreditAccount:
127
+ return await self._purchase(
128
+ Purchase(
129
+ path="credits",
130
+ body={"amountCents": amount_cents},
131
+ subject=f"{amount_cents} cents of credits",
132
+ amount_cents=amount_cents,
133
+ pay=self._payments.buy,
134
+ )
135
+ )
136
+
137
+ async def set_auto_reload(self, settings: AutoReloadSettings) -> CreditAccount:
138
+ subscribe = self._payments.subscribe
139
+ if subscribe is None:
140
+ raise AgentJamError(
141
+ "Pass a recurring_token to your payments to set up auto-reload"
142
+ )
143
+
144
+ period = settings.period
145
+
146
+ return await self._purchase(
147
+ Purchase(
148
+ path="credits/auto-reload",
149
+ body=settings.to_wire(),
150
+ subject=f"auto-reload of up to {settings.limit_cents} cents every {period.count} {period.unit}",
151
+ amount_cents=settings.limit_cents,
152
+ pay=subscribe,
153
+ )
154
+ )
155
+
156
+ async def find(self, query: AgentQuery) -> list[AgentCard]:
157
+ return await self._connection.find(query)
158
+
159
+ async def rate(self, review: ReviewDraft) -> Review:
160
+ return await self._connection.rate(review)
161
+
162
+ async def dispute(self, task_id: str, reason: str) -> Dispute:
163
+ return await self._connection.dispute(task_id, reason)
164
+
165
+ async def reviews(self, name: str, query: ReviewQuery) -> ReviewPage:
166
+ return await self._connection.reviews(name, query)
167
+
168
+ async def triggers(self) -> list[TriggerSchedule]:
169
+ if not isinstance(self._connection, TriggerListingConnection):
170
+ return []
171
+
172
+ return await self._connection.triggers()
173
+
174
+ async def tasks(self, query: TaskQuery) -> TaskPage:
175
+ return await self._connection.tasks(query)
176
+
177
+ async def recall(self, task: TaskRef) -> TaskRecapRef:
178
+ return await self._connection.recall(task)
179
+
180
+ async def history(self, anchor: TaskRef, query: HistoryQuery) -> HistoryPage:
181
+ return await self._connection.history(anchor, query)
182
+
183
+ async def upload(self, file: File, signal: Signal | None = None) -> str:
184
+ return await self._connection.upload(file, signal)
185
+
186
+ async def close(self) -> None:
187
+ await self._connection.close()
188
+
189
+ async def _purchase(self, purchase: Purchase) -> CreditAccount:
190
+ request = httpx.Request(
191
+ "POST",
192
+ f"{self._account.api_url}/payments/{purchase.path}",
193
+ headers={
194
+ "authorization": f"Bearer {self._account.api_key}",
195
+ AGENT_NAME_HEADER: encode_component(self.name),
196
+ },
197
+ json=purchase.body,
198
+ )
199
+
200
+ response = await purchase.pay(request, purchase.amount_cents)
201
+ if not response.is_success:
202
+ raise construct_purchase_error(response, purchase)
203
+
204
+ return CreditAccount.model_validate(response.json()["data"])
@@ -0,0 +1,95 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any, Literal
3
+
4
+ import httpx
5
+
6
+ from agentjam._errors import AgentExistsError, AgentJamError
7
+ from agentjam._relay.endpoints import encode_component
8
+ from agentjam._relay.frames import KeyRejectedError
9
+ from agentjam._types import AgentCard, ProfileUpdate, StoredAgent
10
+
11
+
12
+ @dataclass(frozen=True, kw_only=True)
13
+ class Account:
14
+ """The account an API request acts for."""
15
+
16
+ api_url: str
17
+ api_key: str
18
+
19
+
20
+ class SavedAgent(AgentCard):
21
+ payouts_url: str | None = None
22
+
23
+
24
+ def parse_body(response: httpx.Response) -> dict[str, Any]:
25
+ """Parses a JSON object body, or returns an empty one for any other body."""
26
+ try:
27
+ body = response.json()
28
+ except ValueError:
29
+ return {}
30
+
31
+ return body if isinstance(body, dict) else {}
32
+
33
+
34
+ def get_message(response: httpx.Response) -> str:
35
+ data = parse_body(response).get("data")
36
+ message = data.get("message") if isinstance(data, dict) else None
37
+
38
+ return (
39
+ message
40
+ if isinstance(message, str)
41
+ else f"The AgentJam API answered with {response.status_code}"
42
+ )
43
+
44
+
45
+ def construct_refusal_error(response: httpx.Response) -> AgentJamError:
46
+ message = get_message(response)
47
+
48
+ if response.status_code == 401:
49
+ return KeyRejectedError(message)
50
+
51
+ if response.status_code == 409:
52
+ return AgentExistsError(message)
53
+
54
+ return AgentJamError(message)
55
+
56
+
57
+ async def write_agent(
58
+ account: Account, method: Literal["POST", "PATCH"], path: str, body: dict[str, Any]
59
+ ) -> StoredAgent:
60
+ try:
61
+ async with httpx.AsyncClient() as client:
62
+ response = await client.request(
63
+ method,
64
+ f"{account.api_url}{path}",
65
+ headers={"authorization": f"Bearer {account.api_key}"},
66
+ json=body,
67
+ )
68
+ except httpx.TransportError:
69
+ raise AgentJamError(
70
+ f"Could not reach the AgentJam API at {account.api_url}"
71
+ ) from None
72
+
73
+ if not response.is_success:
74
+ raise construct_refusal_error(response)
75
+
76
+ data = SavedAgent.model_validate(response.json()["data"])
77
+ card = AgentCard(name=data.name, description=data.description, skills=data.skills)
78
+
79
+ return StoredAgent(card=card, payouts_url=data.payouts_url)
80
+
81
+
82
+ async def create_agent(
83
+ account: Account, name: str, profile: ProfileUpdate
84
+ ) -> StoredAgent:
85
+ return await write_agent(
86
+ account, "POST", "/agents", {**profile.to_wire(), "name": name}
87
+ )
88
+
89
+
90
+ async def update_agent(
91
+ account: Account, name: str, profile: ProfileUpdate
92
+ ) -> StoredAgent:
93
+ path = f"/agents/{encode_component(name)}"
94
+
95
+ return await write_agent(account, "PATCH", path, profile.to_wire())