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,360 @@
1
+ import asyncio
2
+ from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence
3
+ from dataclasses import dataclass
4
+ from functools import partial
5
+ from typing import Any, Literal, assert_never
6
+
7
+ import httpx
8
+
9
+ from agentjam._connections import (
10
+ AccessLinkingSource,
11
+ AccountReadingSource,
12
+ AccountRevokingSource,
13
+ ConnectionDenied,
14
+ ConnectionEvent,
15
+ ConnectionGrant,
16
+ ConnectionHolder,
17
+ ConnectionReady,
18
+ ConnectionRequired,
19
+ ConnectionRevoked,
20
+ CredentialSource,
21
+ Readiness,
22
+ )
23
+ from agentjam._errors import AgentJamError
24
+ from agentjam._protocol import (
25
+ ConnectionReadyEnvelope,
26
+ ConnectionRequiredEnvelope,
27
+ ConnectionRevokedEnvelope,
28
+ RejectEnvelope,
29
+ )
30
+ from agentjam._providers import AccountRevocation
31
+ from agentjam._relay.base import CredentialChannel, Draft
32
+ from agentjam._secrets import (
33
+ SecretSource,
34
+ construct_secret_source,
35
+ is_secret_connection,
36
+ is_secret_source,
37
+ )
38
+ from agentjam._signals import Signal
39
+ from agentjam._tasks.access import AccessOptions, AccessWait, AccessWaits
40
+ from agentjam._tasks.incoming import ConnectionAccess
41
+ from agentjam._types import Account, ConnectionFetch, ProposalAction, SkillHandler
42
+ from agentjam._utils import create_id, resolve_value, spawn
43
+
44
+ AccessRequirer = Callable[[str, AccessOptions, Signal], Awaitable[None]]
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class AccessLink:
49
+ post: Callable[[Draft], Awaitable[None]]
50
+ channel: Callable[[str], CredentialChannel]
51
+ """Returns the relay connection's credential channel for the provider's secret connection."""
52
+ cancel: Callable[[ConnectionHolder, str], None]
53
+ """Cancels the running task the holder names, if there is one."""
54
+ on_error: Callable[[Exception], None]
55
+
56
+
57
+ def compute_action_kind(
58
+ source: CredentialSource,
59
+ ) -> Literal["oauth", "credential_form"]:
60
+ return "credential_form" if is_secret_source(source) else "oauth"
61
+
62
+
63
+ class AccessBroker:
64
+ """Reaches the accounts each skill's connections hold, and asks humans for the ones a task or schedule lacks."""
65
+
66
+ def __init__(
67
+ self, skills: Sequence[SkillHandler[Any, Any]], link: AccessLink
68
+ ) -> None:
69
+ self.readiness = Readiness()
70
+ self._waits = AccessWaits()
71
+ self._link = link
72
+ self._sources = {skill.name: self._construct_sources(skill) for skill in skills}
73
+ self._unwatch = [source.watch(self._hear) for source in self.list_sources()]
74
+
75
+ def list_sources(self) -> list[CredentialSource]:
76
+ unique = {
77
+ id(source): source
78
+ for sources in self._sources.values()
79
+ for source in sources.values()
80
+ }
81
+
82
+ return list(unique.values())
83
+
84
+ def list_skill_sources(self, skill: str | None) -> list[CredentialSource]:
85
+ return list(self._find_sources(skill).values())
86
+
87
+ def stop_watching(self) -> None:
88
+ for stop in self._unwatch:
89
+ stop()
90
+
91
+ async def list_actions(
92
+ self, skill: str | None, grant: ConnectionGrant
93
+ ) -> list[ProposalAction]:
94
+ """Lists the links where the grant's human connects the accounts the skill still lacks for it."""
95
+ sources = self.list_skill_sources(skill)
96
+ urls = await asyncio.gather(*(source.authorize(grant) for source in sources))
97
+
98
+ return [
99
+ ProposalAction(
100
+ kind=compute_action_kind(source), provider=source.provider, url=url
101
+ )
102
+ for source, url in zip(sources, urls, strict=True)
103
+ if url is not None
104
+ ]
105
+
106
+ def construct_access(
107
+ self, skill: str | None, holder: ConnectionHolder
108
+ ) -> ConnectionAccess:
109
+ """Builds how the holder's task or schedule reaches the accounts of the skill's connections."""
110
+
111
+ async def read_credentials(provider: str, name: str | None) -> str:
112
+ return await self._find_source(skill, provider).token(holder, name)
113
+
114
+ async def read_account(provider: str) -> Account | None:
115
+ source = self._find_source(skill, provider)
116
+ if not isinstance(source, AccountReadingSource):
117
+ return None
118
+
119
+ return await source.account(holder)
120
+
121
+ def construct_fetch(provider: str) -> ConnectionFetch:
122
+ source = self._find_secret_source(skill, provider)
123
+
124
+ async def fetch(
125
+ url: str,
126
+ *,
127
+ method: str = "GET",
128
+ headers: Mapping[str, str] | None = None,
129
+ content: bytes | str | None = None,
130
+ json: Any = None,
131
+ ) -> httpx.Response:
132
+ return await source.fetch(
133
+ holder,
134
+ url,
135
+ method=method,
136
+ headers=headers,
137
+ content=content,
138
+ json=json,
139
+ )
140
+
141
+ return fetch
142
+
143
+ async def read_config(provider: str) -> dict[str, str]:
144
+ return await self._find_secret_source(skill, provider).config(holder)
145
+
146
+ return ConnectionAccess(
147
+ credentials=read_credentials,
148
+ account=read_account,
149
+ connection_fetch=construct_fetch,
150
+ connection_config=read_config,
151
+ )
152
+
153
+ def construct_requirer(
154
+ self, skill: str | None, grant: ConnectionGrant, proposal_id: str
155
+ ) -> AccessRequirer:
156
+ """Builds how the running task `proposal_id` asks its human for access it lacks.
157
+
158
+ It requires the action, then re-runs `verify` with backoff, sooner once the connection is ready, and requires
159
+ it again if a ready connection still doesn't verify, since the relay already counted that action as taken.
160
+ """
161
+
162
+ async def require_access(
163
+ provider: str, options: AccessOptions, signal: Signal
164
+ ) -> None:
165
+ source = self._find_source(skill, provider)
166
+
167
+ async def require() -> None:
168
+ url = (
169
+ options.url
170
+ if options.url is not None
171
+ else await self._construct_access_url(source, grant)
172
+ )
173
+
174
+ await self._link.post(
175
+ ConnectionRequiredEnvelope(
176
+ id=create_id(),
177
+ to=grant.requester,
178
+ proposal_id=proposal_id,
179
+ provider=provider,
180
+ url=url,
181
+ reason=options.reason,
182
+ )
183
+ )
184
+
185
+ async def check(woken: bool) -> bool:
186
+ announced = woken and grant.id == proposal_id
187
+
188
+ if await resolve_value(options.verify()):
189
+ if not announced:
190
+ await self._post_ready(grant.requester, proposal_id, provider)
191
+
192
+ return True
193
+
194
+ if woken:
195
+ await require()
196
+
197
+ return False
198
+
199
+ await require()
200
+ await self._waits.poll(
201
+ AccessWait(provider, grant, proposal_id), signal, check
202
+ )
203
+
204
+ return require_access
205
+
206
+ async def announce(self, event: ConnectionEvent) -> None:
207
+ """Tells the requesters a connection event concerns about it."""
208
+ match event:
209
+ case ConnectionReady():
210
+ self.readiness.settle(event.provider, event.grant)
211
+ await self._post_ready(
212
+ event.grant.requester, event.grant.id, event.provider
213
+ )
214
+ self._waits.wake(event.provider, event.grant)
215
+
216
+ case ConnectionRequired():
217
+ waiting = self._waits.list_waiting(event.provider, event.grant)
218
+ await asyncio.gather(
219
+ *(
220
+ self._link.post(
221
+ ConnectionRequiredEnvelope(
222
+ id=create_id(),
223
+ to=event.grant.requester,
224
+ proposal_id=proposal_id,
225
+ provider=event.provider,
226
+ url=event.url,
227
+ reason=event.reason,
228
+ )
229
+ )
230
+ for proposal_id in waiting or [event.grant.id]
231
+ )
232
+ )
233
+
234
+ case ConnectionDenied():
235
+ await self._deny(event.grant, event.reason)
236
+
237
+ case ConnectionRevoked():
238
+ await asyncio.gather(
239
+ *(
240
+ self._link.post(
241
+ ConnectionRevokedEnvelope(
242
+ id=create_id(),
243
+ to=requester,
244
+ provider=event.provider,
245
+ principal=event.principal,
246
+ reason=event.reason,
247
+ )
248
+ )
249
+ for requester in event.requesters
250
+ )
251
+ )
252
+
253
+ case _:
254
+ assert_never(event)
255
+
256
+ async def revoke_account(
257
+ self, provider: str, revocation: AccountRevocation
258
+ ) -> None:
259
+ """Ends every grant of the account that `revocation` names, through each connection to `provider` that can."""
260
+ revocations = [
261
+ source.revoke_account(revocation)
262
+ for source in self.list_sources()
263
+ if source.provider == provider and isinstance(source, AccountRevokingSource)
264
+ ]
265
+ if not revocations:
266
+ raise AgentJamError(
267
+ f"{provider} revoked account {revocation.id}, but no {provider} connection can revoke accounts, so its grants stay until they fail"
268
+ )
269
+
270
+ await asyncio.gather(*revocations)
271
+
272
+ def release(
273
+ self, holder: ConnectionHolder, sources: Iterable[CredentialSource]
274
+ ) -> None:
275
+ """Stops the holder's ended task or schedule from using the accounts of `sources`."""
276
+ spawn(self._release_each(holder, list(sources)))
277
+
278
+ async def _release_each(
279
+ self, holder: ConnectionHolder, sources: list[CredentialSource]
280
+ ) -> None:
281
+ try:
282
+ await asyncio.gather(*(source.release(holder) for source in sources))
283
+ except Exception as error:
284
+ self._link.on_error(error)
285
+
286
+ async def _deny(self, holder: ConnectionHolder, reason: str) -> None:
287
+ self._link.cancel(holder, reason)
288
+ self.release(holder, self.list_sources())
289
+ await self._link.post(
290
+ RejectEnvelope(
291
+ id=create_id(), to=holder.requester, reply_to=holder.id, reason=reason
292
+ )
293
+ )
294
+
295
+ async def _post_ready(
296
+ self, requester: str, proposal_id: str, provider: str
297
+ ) -> None:
298
+ await self._link.post(
299
+ ConnectionReadyEnvelope(
300
+ id=create_id(), to=requester, proposal_id=proposal_id, provider=provider
301
+ )
302
+ )
303
+
304
+ def _hear(self, event: ConnectionEvent) -> None:
305
+ spawn(self._announce_or_report(event))
306
+
307
+ async def _announce_or_report(self, event: ConnectionEvent) -> None:
308
+ try:
309
+ await self.announce(event)
310
+ except Exception as error:
311
+ self._link.on_error(error)
312
+
313
+ def _construct_sources(
314
+ self, skill: SkillHandler[Any, Any]
315
+ ) -> dict[str, CredentialSource]:
316
+ sources: dict[str, CredentialSource] = {}
317
+ for connection in skill.connections or []:
318
+ if is_secret_connection(connection):
319
+ sources[connection.provider] = construct_secret_source(
320
+ connection, partial(self._link.channel, connection.provider)
321
+ )
322
+ elif isinstance(connection, CredentialSource):
323
+ sources[connection.provider] = connection
324
+ else:
325
+ raise AgentJamError(
326
+ f'The {connection.provider} connection of the "{skill.name}" skill must come from oauth_connection(), secret_connection() or another CredentialSource'
327
+ )
328
+
329
+ return sources
330
+
331
+ def _find_sources(self, skill: str | None) -> dict[str, CredentialSource]:
332
+ return {} if skill is None else self._sources.get(skill, {})
333
+
334
+ def _find_source(self, skill: str | None, provider: str) -> CredentialSource:
335
+ source = self._find_sources(skill).get(provider)
336
+ if source is None:
337
+ raise AgentJamError(
338
+ f'The "{skill}" skill declares no {provider} connection'
339
+ )
340
+
341
+ return source
342
+
343
+ def _find_secret_source(self, skill: str | None, provider: str) -> SecretSource:
344
+ source = self._find_source(skill, provider)
345
+ if not is_secret_source(source):
346
+ raise AgentJamError(
347
+ f'The {provider} connection of the "{skill}" skill isn\'t a secret connection, so get its token with credentials()'
348
+ )
349
+
350
+ return source
351
+
352
+ async def _construct_access_url(
353
+ self, source: CredentialSource, grant: ConnectionGrant
354
+ ) -> str:
355
+ if not isinstance(source, AccessLinkingSource):
356
+ raise AgentJamError(
357
+ f"The {source.provider} connection can't link to its access settings, so require_access() needs a url"
358
+ )
359
+
360
+ return await source.construct_access_url(grant)