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/_slack.py ADDED
@@ -0,0 +1,468 @@
1
+ import hashlib
2
+ import hmac
3
+ import json
4
+ import math
5
+ import time
6
+ from collections.abc import Callable, Mapping
7
+ from dataclasses import replace
8
+ from typing import Any, Literal, TypeAlias, assert_never
9
+
10
+ import httpx
11
+
12
+ from agentjam._errors import AgentJamError
13
+ from agentjam._events import (
14
+ EventSource,
15
+ ReportedEvent,
16
+ RevokedAccount,
17
+ SourceDelivery,
18
+ SourceEvent,
19
+ SourceRequest,
20
+ SourceResponse,
21
+ read_source_request,
22
+ )
23
+ from agentjam._providers import (
24
+ AccountRevocation,
25
+ OAuthClient,
26
+ OAuthEndpoints,
27
+ ParsedTokens,
28
+ TokenError,
29
+ TokenResponse,
30
+ Tokens,
31
+ construct_standard_profile,
32
+ parse_standard_token,
33
+ )
34
+ from agentjam._types import (
35
+ Account,
36
+ JsonObject,
37
+ JsonSchema,
38
+ OnScheduleActive,
39
+ Trigger,
40
+ TriggerActivation,
41
+ TriggerContext,
42
+ TriggerEvent,
43
+ TriggerSchedule,
44
+ )
45
+
46
+ SlackEvent: TypeAlias = dict[str, Any]
47
+ """An event from Slack's Events API, such as a `message`, as the request's `event` field holds it."""
48
+
49
+ SlackEventMap: TypeAlias = Callable[[SlackEvent, str], list[str]]
50
+ """Assigns event keys to a Slack event type `slack_triggers` doesn't watch, given the id of the account that installed the app."""
51
+
52
+ SlackKind = Literal["message", "mention", "directMessage"]
53
+
54
+ SLACK_REVOKE = "https://slack.com/api/auth.revoke"
55
+
56
+ SLACK_ENDPOINTS = OAuthEndpoints(
57
+ authorize="https://slack.com/oauth/v2/authorize",
58
+ token="https://slack.com/api/oauth.v2.access",
59
+ revoke=SLACK_REVOKE,
60
+ )
61
+
62
+ SIGNATURE_MAX_AGE = 5 * 60
63
+
64
+ IGNORED_SUBTYPES = frozenset({"message_changed", "message_deleted"})
65
+
66
+
67
+ def read_object(value: object) -> dict[str, Any]:
68
+ return value if isinstance(value, dict) else {}
69
+
70
+
71
+ def read_text(body: Mapping[str, Any], key: str) -> str | None:
72
+ value = body.get(key)
73
+
74
+ return value if isinstance(value, str) else None
75
+
76
+
77
+ def split_scopes(scope: str | None) -> list[str]:
78
+ return [granted for granted in (scope or "").split(",") if granted]
79
+
80
+
81
+ def parse_slack_account(body: TokenResponse) -> Account | None:
82
+ team = read_object(body.get("team"))
83
+ enterprise = read_object(body.get("enterprise"))
84
+ enterprise_id = read_text(enterprise, "id")
85
+ id = read_text(team, "id")
86
+ if id is None or body.get("is_enterprise_install") is True:
87
+ id = enterprise_id
88
+
89
+ if id is None:
90
+ return None
91
+
92
+ name = read_text(team, "name")
93
+ bot_user_id = read_text(body, "bot_user_id")
94
+ app_id = read_text(body, "app_id")
95
+ details = {"botUserId": bot_user_id, "appId": app_id}
96
+
97
+ return Account(
98
+ id=id,
99
+ subject=read_text(read_object(body.get("authed_user")), "id"),
100
+ name=name if name is not None else read_text(enterprise, "name"),
101
+ details={field: value for field, value in details.items() if value is not None},
102
+ )
103
+
104
+
105
+ # WARNING: refreshing a user token answers with it at the top level, where a code exchange puts the bot token.
106
+ def parse_slack_tokens(
107
+ body: TokenResponse, previous: Mapping[str, Tokens] | None
108
+ ) -> ParsedTokens:
109
+ earlier = previous or {}
110
+ if body.get("token_type") == "user":
111
+ return ParsedTokens(
112
+ tokens={"user": parse_standard_token(body, earlier.get("user"))},
113
+ scopes={"user": split_scopes(read_text(body, "scope"))},
114
+ )
115
+
116
+ user = read_object(body.get("authed_user"))
117
+ tokens: dict[str, Tokens] = {}
118
+ scopes: dict[str, list[str]] = {}
119
+ if read_text(body, "access_token") is not None:
120
+ tokens["bot"] = parse_standard_token(body, earlier.get("bot"))
121
+ scopes["bot"] = split_scopes(read_text(body, "scope"))
122
+
123
+ if read_text(user, "access_token") is not None:
124
+ tokens["user"] = parse_standard_token(user, earlier.get("user"))
125
+ scopes["user"] = split_scopes(read_text(user, "scope"))
126
+
127
+ if not tokens:
128
+ raise AgentJamError("Slack's token response has no bot or user token")
129
+
130
+ return ParsedTokens(tokens=tokens, scopes=scopes, account=parse_slack_account(body))
131
+
132
+
133
+ def construct_slack_authorize_params(scopes: dict[str, list[str]]) -> dict[str, str]:
134
+ params = {"scope": ",".join(scopes.get("bot", []))}
135
+ if user := scopes.get("user"):
136
+ params["user_scope"] = ",".join(user)
137
+
138
+ return params
139
+
140
+
141
+ def read_slack_error(
142
+ response: httpx.Response, body: TokenResponse
143
+ ) -> TokenError | None:
144
+ if body.get("ok") is False:
145
+ return TokenError(code=str(body.get("error")))
146
+
147
+ return (
148
+ None
149
+ if response.is_success
150
+ else TokenError(code=f"status {response.status_code}")
151
+ )
152
+
153
+
154
+ async def revoke_slack_token(tokens: Tokens, _: OAuthClient) -> None:
155
+ async with httpx.AsyncClient() as client:
156
+ response = await client.post(
157
+ SLACK_REVOKE, headers={"authorization": f"Bearer {tokens.access_token}"}
158
+ )
159
+
160
+ body = read_object(response.json())
161
+ if body.get("ok") is not True:
162
+ error = read_text(body, "error")
163
+ reason = error if error is not None else f"status {response.status_code}"
164
+
165
+ raise AgentJamError(f"Slack refused to revoke the token: {reason}")
166
+
167
+
168
+ slack_profile = replace(
169
+ construct_standard_profile(SLACK_ENDPOINTS),
170
+ pkce=False,
171
+ default_token="bot",
172
+ shared_tokens=["bot"],
173
+ lost_grant_errors=["invalid_refresh_token", "token_revoked"],
174
+ construct_authorize_params=construct_slack_authorize_params,
175
+ parse_tokens=parse_slack_tokens,
176
+ read_error=read_slack_error,
177
+ revoke_tokens=revoke_slack_token,
178
+ )
179
+ """How to run Slack's OAuth v2 flow, which `oauth_connection(provider="slack")` uses.
180
+
181
+ It requests the `bot` token's scopes as `scope` and the `user` token's as `user_scope`, and reads the workspace as the
182
+ account, with the human who installed the app as its `subject`. Everyone who connects the same workspace shares the bot token.
183
+ """
184
+
185
+
186
+ def is_signed(secret: str, headers: httpx.Headers, body: str) -> bool:
187
+ timestamp = headers.get("x-slack-request-timestamp", "")
188
+ try:
189
+ age = abs(time.time() - float(timestamp))
190
+ except ValueError:
191
+ return False
192
+
193
+ if not math.isfinite(age) or age > SIGNATURE_MAX_AGE:
194
+ return False
195
+
196
+ digest = hmac.new(
197
+ secret.encode(), f"v0:{timestamp}:{body}".encode(), hashlib.sha256
198
+ ).hexdigest()
199
+ signature = headers.get("x-slack-signature", "")
200
+
201
+ return hmac.compare_digest(signature.encode(), f"v0={digest}".encode())
202
+
203
+
204
+ def construct_slack_key(account: str, kind: SlackKind, scope: str | None = None) -> str:
205
+ return (
206
+ f"slack:{account}:{kind}"
207
+ if scope is None
208
+ else f"slack:{account}:{kind}:{scope}"
209
+ )
210
+
211
+
212
+ def get_account(request: JsonObject) -> str | None:
213
+ authorizations = request.get("authorizations") or [{}]
214
+ is_enterprise = read_object(authorizations[0]).get("is_enterprise_install")
215
+
216
+ return read_text(request, "enterprise_id" if is_enterprise else "team_id")
217
+
218
+
219
+ def get_kind(event: SlackEvent) -> SlackKind | None:
220
+ match event.get("type"):
221
+ case "app_mention":
222
+ return "mention"
223
+
224
+ case "message":
225
+ return "directMessage" if event.get("channel_type") == "im" else "message"
226
+
227
+ case _:
228
+ return None
229
+
230
+
231
+ def is_own_message(request: JsonObject, event: SlackEvent) -> bool:
232
+ authorizations = [
233
+ read_object(granted) for granted in request.get("authorizations") or []
234
+ ]
235
+ is_own_bot = event.get("bot_id") is not None and event.get("app_id") == request.get(
236
+ "api_app_id"
237
+ )
238
+
239
+ return is_own_bot or any(
240
+ granted.get("is_bot") and granted.get("user_id") == event.get("user")
241
+ for granted in authorizations
242
+ )
243
+
244
+
245
+ def summarize_message(kind: SlackKind, event: SlackEvent) -> str:
246
+ user, channel = event.get("user"), event.get("channel")
247
+
248
+ match kind:
249
+ case "message":
250
+ return f"New Slack message from {user} in {channel}"
251
+
252
+ case "mention":
253
+ return f"{user} mentioned the app in {channel}"
254
+
255
+ case "directMessage":
256
+ return f"Direct message from {user}"
257
+
258
+ case _:
259
+ assert_never(kind)
260
+
261
+
262
+ def construct_message_data(event: SlackEvent, team: str | None) -> JsonObject:
263
+ fields = {
264
+ "channel": event.get("channel"),
265
+ "ts": event.get("ts"),
266
+ "thread_ts": event.get("thread_ts"),
267
+ "user": event.get("user"),
268
+ "text": event.get("text"),
269
+ "team": event.get("team", team),
270
+ }
271
+
272
+ return {field: value for field, value in fields.items() if value is not None}
273
+
274
+
275
+ def construct_message_keys(
276
+ account: str, kind: SlackKind, event: SlackEvent
277
+ ) -> list[str]:
278
+ if kind == "directMessage":
279
+ return [construct_slack_key(account, kind, event.get("user"))]
280
+
281
+ return [
282
+ construct_slack_key(account, kind, event.get("channel")),
283
+ construct_slack_key(account, kind),
284
+ ]
285
+
286
+
287
+ def read_revocations(account: str, event: SlackEvent) -> list[SourceEvent]:
288
+ tokens = read_object(event.get("tokens"))
289
+
290
+ def revoke(reason: str, subject: str | None = None) -> RevokedAccount:
291
+ revocation = AccountRevocation(id=account, subject=subject, reason=reason)
292
+
293
+ return RevokedAccount(provider="slack", revocation=revocation)
294
+
295
+ if event.get("type") == "app_uninstalled":
296
+ return [revoke("The workspace uninstalled the Slack app")]
297
+
298
+ if tokens.get("bot"):
299
+ return [revoke("Slack revoked the app's bot token")]
300
+
301
+ return [
302
+ revoke("The human revoked the Slack app's access", subject)
303
+ for subject in tokens.get("oauth") or []
304
+ ]
305
+
306
+
307
+ def read_events(request: JsonObject, map: SlackEventMap | None) -> list[SourceEvent]:
308
+ event = request.get("event")
309
+ id = read_text(request, "event_id")
310
+ account = get_account(request)
311
+ if not isinstance(event, dict) or id is None or account is None:
312
+ return []
313
+
314
+ if event.get("type") in ("app_uninstalled", "tokens_revoked"):
315
+ return read_revocations(account, event)
316
+
317
+ if (kind := get_kind(event)) is None:
318
+ event_keys = map(event, account) if map else []
319
+ read = TriggerEvent(
320
+ id=id, summary=f"Slack {event.get('type')} event", data=event
321
+ )
322
+ elif is_own_message(request, event) or event.get("subtype") in IGNORED_SUBTYPES:
323
+ return []
324
+ else:
325
+ event_keys = construct_message_keys(account, kind, event)
326
+ read = TriggerEvent(
327
+ id=id,
328
+ summary=summarize_message(kind, event),
329
+ data=construct_message_data(event, read_text(request, "team_id")),
330
+ )
331
+
332
+ return [ReportedEvent(event_keys=event_keys, event=read)] if event_keys else []
333
+
334
+
335
+ class SlackEvents:
336
+ """Reads Slack's Events API requests, verifying each one's signature."""
337
+
338
+ def __init__(self, signing_secret: str, map: SlackEventMap | None) -> None:
339
+ self._signing_secret = signing_secret
340
+ self._map = map
341
+
342
+ async def receive(self, request: SourceRequest | httpx.Request) -> SourceDelivery:
343
+ """Verifies a Slack request and reads the events it carries.
344
+
345
+ Args:
346
+ request: Slack's request.
347
+
348
+ Returns:
349
+ The answer to send Slack, and the events to dispatch or revoke.
350
+ """
351
+ received = await read_source_request(request)
352
+ if not is_signed(self._signing_secret, received.headers, received.body):
353
+ return SourceDelivery(
354
+ response=SourceResponse(status=401, body="Invalid Slack signature")
355
+ )
356
+
357
+ payload = json.loads(received.body)
358
+ if payload.get("type") == "url_verification":
359
+ return SourceDelivery(
360
+ response=SourceResponse(
361
+ status=200,
362
+ headers={"content-type": "text/plain"},
363
+ body=str(payload.get("challenge")),
364
+ )
365
+ )
366
+
367
+ is_callback = payload.get("type") == "event_callback"
368
+
369
+ return SourceDelivery(
370
+ response=SourceResponse(status=200),
371
+ events=read_events(payload, self._map) if is_callback else [],
372
+ )
373
+
374
+
375
+ def slack_events(
376
+ *, signing_secret: str, map: SlackEventMap | None = None
377
+ ) -> EventSource:
378
+ """Reads Slack's Events API requests, for `agent.receive_events()` at the app's Request URL.
379
+
380
+ It verifies each request's signature, answers Slack's URL check, and reads messages, mentions and direct messages
381
+ under the keys `slack_triggers` subscribe to, leaving out the app's own messages and edits or deletions.
382
+
383
+ Args:
384
+ signing_secret: The signing secret on the Slack app's Basic Information page.
385
+ map: Assigns event keys to other Slack event types, such as `reaction_added`. No keys drops the event.
386
+
387
+ Returns:
388
+ An event source for Slack's requests.
389
+ """
390
+ return SlackEvents(signing_secret, map)
391
+
392
+
393
+ CHANNEL_CONFIG: JsonSchema = {
394
+ "type": "object",
395
+ "properties": {
396
+ "channel": {
397
+ "type": "string",
398
+ "description": "The id of the channel to watch, such as C0123ABCD. Leave it out to watch every channel the app is in.",
399
+ },
400
+ },
401
+ }
402
+
403
+
404
+ async def read_slack_account(context: TriggerContext) -> Account:
405
+ connected = await context.account("slack")
406
+ if connected is None:
407
+ raise AgentJamError(
408
+ "The schedule has no Slack account connected, so it can't watch Slack"
409
+ )
410
+
411
+ return connected
412
+
413
+
414
+ def get_channel(schedule: TriggerSchedule) -> str | None:
415
+ channel = schedule.config.get("channel")
416
+
417
+ return channel if isinstance(channel, str) else None
418
+
419
+
420
+ def watch_channel(kind: Literal["message", "mention"]) -> OnScheduleActive:
421
+ async def activate(
422
+ schedule: TriggerSchedule, context: TriggerContext
423
+ ) -> TriggerActivation:
424
+ account = await read_slack_account(context)
425
+
426
+ return TriggerActivation(
427
+ event_keys=[construct_slack_key(account.id, kind, get_channel(schedule))]
428
+ )
429
+
430
+ return activate
431
+
432
+
433
+ async def watch_direct_messages(
434
+ _: TriggerSchedule, context: TriggerContext
435
+ ) -> TriggerActivation:
436
+ account = await read_slack_account(context)
437
+ if account.subject is None:
438
+ raise AgentJamError(
439
+ "The schedule's Slack account names no human, so it can't watch their direct messages"
440
+ )
441
+
442
+ return TriggerActivation(
443
+ event_keys=[construct_slack_key(account.id, "directMessage", account.subject)]
444
+ )
445
+
446
+
447
+ slack_triggers: Mapping[str, Trigger] = {
448
+ "message": Trigger(
449
+ description="A message is posted in a channel the app is in, or in one channel when `channel` is set",
450
+ config=CHANNEL_CONFIG,
451
+ on_schedule_active=watch_channel("message"),
452
+ ),
453
+ "mention": Trigger(
454
+ description="Someone mentions the app in a channel it's in, or in one channel when `channel` is set",
455
+ config=CHANNEL_CONFIG,
456
+ on_schedule_active=watch_channel("mention"),
457
+ ),
458
+ "directMessage": Trigger(
459
+ description="The human who connected Slack sends the app a direct message",
460
+ config={"type": "object", "properties": {}},
461
+ on_schedule_active=watch_direct_messages,
462
+ ),
463
+ }
464
+ """Triggers that run a schedule on the Slack events `slack_events()` reads, for a skill with a `slack` connection.
465
+
466
+ Every schedule watching an event gets its own run, with the message's `channel`, `ts`, `thread_ts`, `user`, `text`
467
+ and `team` as `task.event.data`.
468
+ """
agentjam/_stripe.py ADDED
@@ -0,0 +1,93 @@
1
+ import re
2
+
3
+ import httpx
4
+ from mpp.methods.stripe.client import CreateTokenFn, OnChallengeParameters
5
+
6
+ from agentjam._errors import AgentJamError, PaymentRequiredError
7
+
8
+ CreateToken = CreateTokenFn
9
+ """Creates a Stripe shared payment token for one task's payment, and returns its id."""
10
+
11
+ API_URL = "https://api.stripe.com/v1/"
12
+ PREVIEW_VERSION = "2026-07-29.preview"
13
+ SECRET_KEY = re.compile(r"[rs]k_(test|live)_\w+", re.ASCII)
14
+ UNAUTHORIZED = 401
15
+
16
+
17
+ def is_test_key(api_key: str) -> bool:
18
+ return api_key.startswith(("rk_test_", "sk_test_"))
19
+
20
+
21
+ def get_secret_key(api_key: str | None) -> str:
22
+ if not api_key:
23
+ raise AgentJamError(
24
+ "Your Stripe api_key is empty, which usually means its env var isn't set"
25
+ )
26
+
27
+ if not SECRET_KEY.fullmatch(api_key):
28
+ raise AgentJamError(
29
+ "Your Stripe api_key must be a secret or restricted key, starting with sk_ or rk_"
30
+ )
31
+
32
+ return api_key
33
+
34
+
35
+ def construct_refusal_error(status: int, message: str) -> AgentJamError:
36
+ if status == UNAUTHORIZED:
37
+ return AgentJamError(f"Stripe rejected your api_key: {message}")
38
+
39
+ return PaymentRequiredError(
40
+ "payment_failed", f"Stripe couldn't issue a payment token: {message}"
41
+ )
42
+
43
+
44
+ def compute_seller_fields(request: OnChallengeParameters) -> dict[str, str]:
45
+ profile = (
46
+ {"seller_details[network_business_profile]": request.network_id}
47
+ if request.network_id
48
+ else {}
49
+ )
50
+ metadata = request.metadata or {}
51
+
52
+ return {**profile, **{f"metadata[{key}]": value for key, value in metadata.items()}}
53
+
54
+
55
+ # WARNING: Stripe's test helper rejects seller details, so test tokens only carry their usage limits.
56
+ def get_endpoint(
57
+ api_key: str, request: OnChallengeParameters
58
+ ) -> tuple[str, dict[str, str]]:
59
+ if is_test_key(api_key):
60
+ return "test_helpers/shared_payment/granted_tokens", {}
61
+
62
+ return "shared_payment/issued_tokens", compute_seller_fields(request)
63
+
64
+
65
+ def issue_token(*, api_key: str | None, payment_method: str) -> CreateToken:
66
+ secret_key = get_secret_key(api_key)
67
+
68
+ async def create_token(request: OnChallengeParameters) -> str:
69
+ path, fields = get_endpoint(secret_key, request)
70
+
71
+ async with httpx.AsyncClient() as client:
72
+ response = await client.post(
73
+ f"{API_URL}{path}",
74
+ headers={
75
+ "authorization": f"Bearer {secret_key}",
76
+ "stripe-version": PREVIEW_VERSION,
77
+ },
78
+ data={
79
+ "payment_method": payment_method,
80
+ "usage_limits[currency]": request.currency,
81
+ "usage_limits[max_amount]": request.amount,
82
+ "usage_limits[expires_at]": str(request.expires_at),
83
+ **fields,
84
+ },
85
+ )
86
+
87
+ issued = response.json()
88
+ if error := issued.get("error"):
89
+ raise construct_refusal_error(response.status_code, error["message"])
90
+
91
+ return str(issued["id"])
92
+
93
+ return create_token
File without changes
@@ -0,0 +1,142 @@
1
+ import asyncio
2
+ from collections.abc import Awaitable, Callable
3
+ from dataclasses import dataclass
4
+
5
+ from agentjam._connections import ConnectionHolder
6
+ from agentjam._signals import Signal, guard
7
+
8
+ FIRST_ACCESS_CHECK = 5.0
9
+
10
+ MAX_ACCESS_CHECK = 60.0
11
+
12
+
13
+ @dataclass(frozen=True, kw_only=True)
14
+ class AccessOptions:
15
+ """What a task's `require_access()` asks the human for."""
16
+
17
+ reason: str
18
+ """What the human must do, shown to them beside the link, such as "Give the app access to acme/api"."""
19
+ verify: Callable[[], Awaitable[bool] | bool]
20
+ """Checks whether the task has the access it needs yet, such as by fetching the repository it lacked."""
21
+ url: str | None = None
22
+ """Where the human grants the access. Defaults to the connection's own page for it, or else a fresh consent link."""
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class AccessWait:
27
+ """A task waiting on access to `provider` through its holder's connection, which is its schedule's for a run."""
28
+
29
+ provider: str
30
+ holder: ConnectionHolder
31
+ proposal_id: str
32
+
33
+
34
+ def compute_next_check(delay: float) -> float:
35
+ return min(delay * 2, MAX_ACCESS_CHECK)
36
+
37
+
38
+ def compute_wait_key(provider: str, holder: ConnectionHolder) -> tuple[str, str, str]:
39
+ return provider, holder.requester, holder.id
40
+
41
+
42
+ class AccessWaiter:
43
+ """One task's wait on access, woken early once its holder's connection is ready, even between its checks."""
44
+
45
+ def __init__(self, proposal_id: str, close: Callable[[], None]) -> None:
46
+ self.proposal_id = proposal_id
47
+ self.close = close
48
+ self._woken = False
49
+ self._resume: Callable[[], None] | None = None
50
+
51
+ def wake(self) -> None:
52
+ if self._resume is None:
53
+ self._woken = True
54
+ else:
55
+ self._resume()
56
+
57
+ async def sleep(self, delay: float, signal: Signal) -> bool:
58
+ """Waits `delay` seconds, or less once `wake()` is called, returning whether a ready connection woke it.
59
+
60
+ It returns at once when `wake()` was called since the last wait, and raises the signal's reason once it aborts.
61
+ """
62
+ signal.raise_if_aborted()
63
+
64
+ if self._woken:
65
+ self._woken = False
66
+
67
+ return True
68
+
69
+ loop = asyncio.get_running_loop()
70
+ woken: asyncio.Future[bool] = loop.create_future()
71
+
72
+ def settle(value: bool) -> None:
73
+ if not woken.done():
74
+ woken.set_result(value)
75
+
76
+ timer = loop.call_later(delay, settle, False)
77
+ self._resume = lambda: settle(True)
78
+
79
+ try:
80
+ return await guard(woken, signal)
81
+ finally:
82
+ timer.cancel()
83
+ self._resume = None
84
+
85
+
86
+ class AccessWaits:
87
+ """Tracks the tasks waiting on access, so a provider's connection becoming ready or relinked reaches each of them."""
88
+
89
+ def __init__(self) -> None:
90
+ self._waiters: dict[tuple[str, str, str], dict[AccessWaiter, None]] = {}
91
+
92
+ async def poll(
93
+ self,
94
+ wait: AccessWait,
95
+ signal: Signal,
96
+ check: Callable[[bool], Awaitable[bool]],
97
+ ) -> None:
98
+ """Calls `check` after each wait, backing off from 5 seconds to a minute apart, until it returns True.
99
+
100
+ A ready connection ends a wait early, and `check` hears whether one woke it. Raises the signal's reason once it aborts.
101
+ """
102
+ waiter = self._open(wait)
103
+
104
+ try:
105
+ delay = FIRST_ACCESS_CHECK
106
+ while True:
107
+ if await check(await waiter.sleep(delay, signal)):
108
+ return
109
+
110
+ delay = compute_next_check(delay)
111
+ finally:
112
+ waiter.close()
113
+
114
+ def wake(self, provider: str, holder: ConnectionHolder) -> None:
115
+ for waiter in self._find_waiters(provider, holder):
116
+ waiter.wake()
117
+
118
+ def list_waiting(self, provider: str, holder: ConnectionHolder) -> list[str]:
119
+ """Lists the ids of the tasks waiting on access to `provider` through `holder`'s connection."""
120
+ ids = [waiter.proposal_id for waiter in self._find_waiters(provider, holder)]
121
+
122
+ return list(dict.fromkeys(ids))
123
+
124
+ def _open(self, wait: AccessWait) -> AccessWaiter:
125
+ key = compute_wait_key(wait.provider, wait.holder)
126
+ waiters = self._waiters.get(key, {})
127
+
128
+ def close() -> None:
129
+ waiters.pop(waiter, None)
130
+ if not waiters:
131
+ self._waiters.pop(key, None)
132
+
133
+ waiter = AccessWaiter(wait.proposal_id, close)
134
+ waiters[waiter] = None
135
+ self._waiters[key] = waiters
136
+
137
+ return waiter
138
+
139
+ def _find_waiters(
140
+ self, provider: str, holder: ConnectionHolder
141
+ ) -> list[AccessWaiter]:
142
+ return list(self._waiters.get(compute_wait_key(provider, holder), ()))