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,1282 @@
1
+ import asyncio
2
+ import base64
3
+ import hashlib
4
+ import json
5
+ import secrets
6
+ from collections import Counter
7
+ from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Sequence
8
+ from contextlib import AbstractAsyncContextManager, asynccontextmanager
9
+ from dataclasses import dataclass
10
+ from datetime import UTC, datetime, timedelta
11
+ from functools import reduce
12
+ from typing import Literal, Protocol, TypeAlias, runtime_checkable
13
+ from weakref import WeakKeyDictionary
14
+
15
+ import httpx
16
+ from pydantic import Field
17
+
18
+ from agentjam._errors import AgentJamError, ConnectionRevokedError
19
+ from agentjam._models import WireModel
20
+ from agentjam._providers import (
21
+ DEFAULT_TOKEN,
22
+ AccountRevocation,
23
+ EpochMilliseconds,
24
+ OAuthClient,
25
+ OAuthEndpoints,
26
+ OAuthProfile,
27
+ ParsedTokens,
28
+ TokenError,
29
+ TokenResponse,
30
+ Tokens,
31
+ construct_github_app_profile,
32
+ construct_standard_profile,
33
+ github_profile,
34
+ google_profile,
35
+ post_form,
36
+ )
37
+ from agentjam._signals import Signal, guard
38
+ from agentjam._slack import slack_profile
39
+ from agentjam._types import Account, ConnectionScopes, SkillConnection
40
+ from agentjam._utils import encode_json, resolve_value
41
+
42
+ Scopes: TypeAlias = dict[str, list[str]]
43
+
44
+ BUILT_IN_PROFILES: dict[str, OAuthProfile] = {
45
+ "google": google_profile,
46
+ "github": github_profile,
47
+ "slack": slack_profile,
48
+ }
49
+
50
+ GITHUB_APP = "github-app"
51
+
52
+ EXPIRY_SKEW = timedelta(seconds=60)
53
+
54
+ AUTHORIZATION_TTL = timedelta(hours=1)
55
+
56
+ LOST_GRANT = "The human revoked access, or the grant expired"
57
+
58
+
59
+ class ConnectionStore(Protocol):
60
+ """Where an OAuth connection keeps its tokens and pending authorizations as strings, such as a database table.
61
+
62
+ Its methods may be sync or async.
63
+ """
64
+
65
+ def get(self, key: str) -> Awaitable[str | None] | str | None:
66
+ """Reads the value saved under `key`.
67
+
68
+ Args:
69
+ key: The value's key.
70
+
71
+ Returns:
72
+ The value, or None if there is none.
73
+ """
74
+ ...
75
+
76
+ def set(self, key: str, value: str) -> Awaitable[object] | object:
77
+ """Saves `value` under `key`, replacing any earlier value.
78
+
79
+ Args:
80
+ key: The value's key.
81
+ value: The value to save.
82
+ """
83
+ ...
84
+
85
+ def delete(self, key: str) -> Awaitable[object] | object:
86
+ """Removes the value saved under `key`, if there is one.
87
+
88
+ Args:
89
+ key: The value's key.
90
+ """
91
+ ...
92
+
93
+
94
+ class MemoryConnectionStore:
95
+ """A `ConnectionStore` in this process's memory, for tests. Its tokens are lost when the process exits."""
96
+
97
+ def __init__(self) -> None:
98
+ self._values: dict[str, str] = {}
99
+
100
+ def get(self, key: str) -> str | None:
101
+ """Reads the value saved under `key`.
102
+
103
+ Args:
104
+ key: The value's key.
105
+
106
+ Returns:
107
+ The value, or None if there is none.
108
+ """
109
+ return self._values.get(key)
110
+
111
+ def set(self, key: str, value: str) -> None:
112
+ """Saves `value` under `key`, replacing any earlier value.
113
+
114
+ Args:
115
+ key: The value's key.
116
+ value: The value to save.
117
+ """
118
+ self._values[key] = value
119
+
120
+ def delete(self, key: str) -> None:
121
+ """Removes the value saved under `key`, if there is one.
122
+
123
+ Args:
124
+ key: The value's key.
125
+ """
126
+ self._values.pop(key, None)
127
+
128
+ def keys(self) -> list[str]:
129
+ """Lists the keys of every saved value.
130
+
131
+
132
+ Returns:
133
+ The keys, in the order they were first saved.
134
+ """
135
+ return list(self._values)
136
+
137
+
138
+ class ConnectionHolder(WireModel):
139
+ """The task or schedule `id` that `requester` proposed."""
140
+
141
+ requester: str
142
+ """The agent that proposed the task or schedule."""
143
+ id: str
144
+ """The id of the task or schedule."""
145
+
146
+
147
+ class ConnectionGrant(ConnectionHolder):
148
+ """A task or schedule that uses the account of `principal`, the human whose request started its chain."""
149
+
150
+ principal: str
151
+ """The human's email, or `guest:<agent>` for an unclaimed guest."""
152
+
153
+
154
+ @dataclass(frozen=True, kw_only=True)
155
+ class ConnectionReady:
156
+ """An account with `provider` that became connected for the proposal `grant`."""
157
+
158
+ provider: str
159
+ grant: ConnectionGrant
160
+ type: Literal["ready"] = "ready"
161
+
162
+
163
+ @dataclass(frozen=True, kw_only=True)
164
+ class ConnectionRequired:
165
+ """A consent that granted fewer scopes than the proposal needs, which the human retries at the new link `url`."""
166
+
167
+ provider: str
168
+ grant: ConnectionGrant
169
+ url: str
170
+ reason: str
171
+ """What the human must do at `url`."""
172
+ type: Literal["required"] = "required"
173
+
174
+
175
+ @dataclass(frozen=True, kw_only=True)
176
+ class ConnectionDenied:
177
+ """An authorization the human denied for the proposal `grant`."""
178
+
179
+ provider: str
180
+ grant: ConnectionGrant
181
+ reason: str
182
+ type: Literal["denied"] = "denied"
183
+
184
+
185
+ @dataclass(frozen=True, kw_only=True)
186
+ class ConnectionRevoked:
187
+ """A human's account with `provider` that stopped being connected."""
188
+
189
+ provider: str
190
+ principal: str
191
+ requesters: list[str]
192
+ """The agents whose tasks and schedules used the account."""
193
+ reason: str
194
+ type: Literal["revoked"] = "revoked"
195
+
196
+
197
+ ConnectionEvent: TypeAlias = (
198
+ ConnectionReady | ConnectionRequired | ConnectionDenied | ConnectionRevoked
199
+ )
200
+ """A proposal whose account became connected or was denied, or a human's account that stopped being connected."""
201
+
202
+ ConnectionListener: TypeAlias = Callable[[ConnectionEvent], None]
203
+
204
+
205
+ @runtime_checkable
206
+ class CredentialSource(Protocol):
207
+ """Gives an executor access to a human's account with `provider`, through one grant per human that all their tasks share.
208
+
209
+ `oauth_connection()` builds one, and a credential vault can implement it instead, subclassing `SkillConnection` so
210
+ skills can list it. Its optional capabilities are `AccountReadingSource`, `AccountRevokingSource` and `AccessLinkingSource`.
211
+ """
212
+
213
+ provider: str
214
+ scopes: ConnectionScopes
215
+
216
+ @property
217
+ def revoke_on_end(self) -> bool:
218
+ """Whether the source revokes a grant once no task or schedule uses it."""
219
+ ...
220
+
221
+ async def authorize(self, grant: ConnectionGrant) -> str | None:
222
+ """Returns where the principal connects their account for `grant`.
223
+
224
+ Args:
225
+ grant: The task or schedule that needs the account.
226
+
227
+ Returns:
228
+ The URL to connect at, or None when their grant already covers it.
229
+ """
230
+ ...
231
+
232
+ async def token(self, holder: ConnectionHolder, name: str | None = None) -> str:
233
+ """Returns a current access token for `holder`.
234
+
235
+ Args:
236
+ holder: The task or schedule using the account.
237
+ name: The token's name, for providers that issue several.
238
+
239
+ Returns:
240
+ The access token.
241
+
242
+ Raises:
243
+ ConnectionRevokedError: Once access is lost.
244
+ """
245
+ ...
246
+
247
+ async def release(self, holder: ConnectionHolder) -> None:
248
+ """Stops `holder` from using the principal's account once its task or schedule ended.
249
+
250
+ Args:
251
+ holder: The task or schedule that ended.
252
+ """
253
+ ...
254
+
255
+ def watch(self, listener: ConnectionListener) -> Callable[[], None]:
256
+ """Calls `listener` on every connection event.
257
+
258
+ Args:
259
+ listener: Called with each event.
260
+
261
+ Returns:
262
+ A function that stops calling `listener`.
263
+ """
264
+ ...
265
+
266
+
267
+ @runtime_checkable
268
+ class AccountReadingSource(Protocol):
269
+ """A credential source that knows which account each holder uses."""
270
+
271
+ async def account(self, holder: ConnectionHolder) -> Account | None:
272
+ """Returns the account `holder` uses.
273
+
274
+ Args:
275
+ holder: The task or schedule using the account.
276
+
277
+ Returns:
278
+ The account, if the source knows it.
279
+
280
+ Raises:
281
+ ConnectionRevokedError: Once access is lost.
282
+ """
283
+ ...
284
+
285
+
286
+ @runtime_checkable
287
+ class AccountRevokingSource(Protocol):
288
+ """A credential source that can end every grant of an account the provider already revoked."""
289
+
290
+ async def revoke_account(self, revocation: AccountRevocation) -> None:
291
+ """Ends every grant of the account that `revocation` names, without calling the provider.
292
+
293
+ Args:
294
+ revocation: The account, and why its access ended.
295
+ """
296
+ ...
297
+
298
+
299
+ @runtime_checkable
300
+ class AccessLinkingSource(Protocol):
301
+ """A credential source that links to where a human changes what their account lets a task reach."""
302
+
303
+ async def construct_access_url(self, grant: ConnectionGrant) -> str:
304
+ """Returns where the principal changes what their account lets `grant` reach, such as which repositories.
305
+
306
+ Args:
307
+ grant: The running task that lacks access.
308
+
309
+ Returns:
310
+ The URL.
311
+ """
312
+ ...
313
+
314
+
315
+ class WaitingHolder(ConnectionHolder):
316
+ scopes: Scopes
317
+
318
+
319
+ # Invariant: `holders` are the principal's tasks and schedules that use these tokens, each saved under its holder key
320
+ # too, and the principal is listed under the account key of `account` while it's set.
321
+ class SavedGrant(WireModel):
322
+ tokens: dict[str, Tokens]
323
+ scopes: Scopes
324
+ account: Account | None = None
325
+ holders: list[ConnectionHolder]
326
+
327
+
328
+ class PendingAuthorization(WireModel):
329
+ principal: str
330
+ verifier: str | None = None
331
+ scopes: Scopes
332
+ expires_at: EpochMilliseconds
333
+
334
+
335
+ # Invariant: a principal has at most one current link per provider, whose `holders` wait on it, and whose scopes cover each one's.
336
+ class PendingLink(WireModel):
337
+ state: str
338
+ url: str
339
+ scopes: Scopes
340
+ expires_at: EpochMilliseconds
341
+ holders: list[WaitingHolder] = Field(default_factory=list)
342
+
343
+
344
+ @dataclass(frozen=True, kw_only=True)
345
+ class Relink:
346
+ url: str
347
+ holders: list[WaitingHolder]
348
+
349
+
350
+ @dataclass(frozen=True, kw_only=True)
351
+ class Settlement:
352
+ ready: list[WaitingHolder]
353
+ relink: Relink | None
354
+
355
+
356
+ class KeyedLocks:
357
+ """Runs work for one key at a time, so read-modify-writes of a store don't interleave."""
358
+
359
+ def __init__(self) -> None:
360
+ self._locks: dict[str, asyncio.Lock] = {}
361
+ self._users: Counter[str] = Counter()
362
+
363
+ @asynccontextmanager
364
+ async def hold(self, key: str) -> AsyncIterator[None]:
365
+ lock = self._locks.setdefault(key, asyncio.Lock())
366
+ self._users[key] += 1
367
+
368
+ try:
369
+ async with lock:
370
+ yield
371
+ finally:
372
+ self._users[key] -= 1
373
+ if self._users[key] == 0:
374
+ del self._users[key]
375
+ del self._locks[key]
376
+
377
+
378
+ store_locks: WeakKeyDictionary[ConnectionStore, KeyedLocks] = WeakKeyDictionary()
379
+
380
+
381
+ def construct_scope_record(
382
+ scopes: ConnectionScopes, token: str = DEFAULT_TOKEN
383
+ ) -> Scopes:
384
+ if isinstance(scopes, list):
385
+ return {token: list(scopes)}
386
+
387
+ return {name: list(granted) for name, granted in scopes.items()}
388
+
389
+
390
+ def resolve_github_app_profile(
391
+ scopes: ConnectionScopes, app_slug: str | None
392
+ ) -> OAuthProfile:
393
+ if not app_slug:
394
+ raise AgentJamError(
395
+ f'oauth_connection() needs an app_slug for the "{GITHUB_APP}" provider'
396
+ )
397
+
398
+ if any(construct_scope_record(scopes).values()):
399
+ raise AgentJamError(
400
+ f'A GitHub App grants access through its permissions, so the "{GITHUB_APP}" provider takes no scopes'
401
+ )
402
+
403
+ return construct_github_app_profile(app_slug)
404
+
405
+
406
+ def resolve_profile(
407
+ provider: str,
408
+ scopes: ConnectionScopes,
409
+ endpoints: OAuthEndpoints | None,
410
+ profile: OAuthProfile | None,
411
+ app_slug: str | None,
412
+ ) -> OAuthProfile:
413
+ if profile is not None and endpoints is not None:
414
+ raise AgentJamError("oauth_connection() takes a profile or endpoints, not both")
415
+
416
+ is_custom = profile is not None or endpoints is not None
417
+ if app_slug is not None and (provider != GITHUB_APP or is_custom):
418
+ raise AgentJamError(
419
+ f'oauth_connection() only takes an app_slug for the built-in "{GITHUB_APP}" provider'
420
+ )
421
+
422
+ if profile is not None:
423
+ return profile
424
+
425
+ if endpoints is not None:
426
+ return construct_standard_profile(endpoints)
427
+
428
+ if provider == GITHUB_APP:
429
+ return resolve_github_app_profile(scopes, app_slug)
430
+
431
+ if (known := BUILT_IN_PROFILES.get(provider)) is None:
432
+ raise AgentJamError(
433
+ f'oauth_connection() has no profile for "{provider}", so pass its endpoints or a profile'
434
+ )
435
+
436
+ return known
437
+
438
+
439
+ def construct_state_key(state: str) -> str:
440
+ return f"state:{state}"
441
+
442
+
443
+ def construct_grant_key(provider: str, principal: str) -> str:
444
+ return f"grant:{encode_json([provider, principal])}"
445
+
446
+
447
+ def construct_pending_key(provider: str, principal: str) -> str:
448
+ return f"pending:{encode_json([provider, principal])}"
449
+
450
+
451
+ def construct_holder_key(provider: str, holder: ConnectionHolder) -> str:
452
+ return f"holder:{encode_json([provider, holder.requester, holder.id])}"
453
+
454
+
455
+ def construct_account_key(provider: str, id: str) -> str:
456
+ return f"account:{encode_json([provider, id])}"
457
+
458
+
459
+ def is_same_holder(first: ConnectionHolder, second: ConnectionHolder) -> bool:
460
+ return first.requester == second.requester and first.id == second.id
461
+
462
+
463
+ def add_waiting(
464
+ holders: list[WaitingHolder], waiting: WaitingHolder
465
+ ) -> list[WaitingHolder]:
466
+ return [*(held for held in holders if not is_same_holder(held, waiting)), waiting]
467
+
468
+
469
+ def add_holder(
470
+ holders: list[ConnectionHolder], holder: ConnectionHolder
471
+ ) -> list[ConnectionHolder]:
472
+ if any(is_same_holder(held, holder) for held in holders):
473
+ return holders
474
+
475
+ return [*holders, ConnectionHolder(requester=holder.requester, id=holder.id)]
476
+
477
+
478
+ def construct_grant(holder: ConnectionHolder, principal: str) -> ConnectionGrant:
479
+ return ConnectionGrant(
480
+ requester=holder.requester, id=holder.id, principal=principal
481
+ )
482
+
483
+
484
+ def list_requesters(holders: Iterable[ConnectionHolder]) -> list[str]:
485
+ return list(dict.fromkeys(holder.requester for holder in holders))
486
+
487
+
488
+ def compute_challenge(verifier: str) -> str:
489
+ digest = hashlib.sha256(verifier.encode()).digest()
490
+
491
+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
492
+
493
+
494
+ def union(first: Iterable[str], second: Iterable[str]) -> list[str]:
495
+ return list(dict.fromkeys([*first, *second]))
496
+
497
+
498
+ def union_scopes(first: Scopes, second: Scopes) -> Scopes:
499
+ return {
500
+ token: union(first.get(token, []), second.get(token, []))
501
+ for token in union(first, second)
502
+ }
503
+
504
+
505
+ def get_account_id(account: Account | None) -> str | None:
506
+ return account.id if account is not None else None
507
+
508
+
509
+ def merge_grant(
510
+ saved: SavedGrant | None, parsed: ParsedTokens, granted: Scopes
511
+ ) -> SavedGrant:
512
+ """Adds newly issued tokens to `saved`, keeping its other tokens unless the new ones are for another account."""
513
+ kept = (
514
+ saved
515
+ if saved is not None
516
+ and get_account_id(saved.account) == get_account_id(parsed.account)
517
+ else None
518
+ )
519
+
520
+ return SavedGrant(
521
+ tokens={**(kept.tokens if kept else {}), **parsed.tokens},
522
+ scopes={**(kept.scopes if kept else {}), **granted},
523
+ account=parsed.account,
524
+ holders=saved.holders if saved is not None else [],
525
+ )
526
+
527
+
528
+ def compute_granted_scopes(parsed: ParsedTokens, requested: Scopes) -> Scopes:
529
+ reported = parsed.scopes or {}
530
+
531
+ return {
532
+ name: reported[name] if name in reported else requested.get(name, [])
533
+ for name in parsed.tokens
534
+ }
535
+
536
+
537
+ def compute_now() -> datetime:
538
+ return datetime.now(UTC)
539
+
540
+
541
+ def is_fresh(tokens: Tokens) -> bool:
542
+ return tokens.expires_at is None or tokens.expires_at - EXPIRY_SKEW > compute_now()
543
+
544
+
545
+ def construct_refusal(error: TokenError) -> AgentJamError:
546
+ reason = error.description if error.description is not None else error.code
547
+
548
+ return AgentJamError(f"The provider refused the token request: {reason}")
549
+
550
+
551
+ class OAuthConnection(SkillConnection):
552
+ """An OAuth 2.0 connection that an executor runs itself, keeping tokens in its own store. Build one with `oauth_connection()`."""
553
+
554
+ def __init__(
555
+ self,
556
+ *,
557
+ provider: str,
558
+ scopes: Scopes,
559
+ profile: OAuthProfile,
560
+ client: OAuthClient,
561
+ redirect_uri: str,
562
+ store: ConnectionStore,
563
+ access_url: str | None,
564
+ revoke_on_end: bool,
565
+ ) -> None:
566
+ super().__init__(provider=provider, scopes=scopes)
567
+ self.revoke_on_end = revoke_on_end
568
+ """Whether a grant is revoked with the provider once no task or schedule uses it."""
569
+ self._requested = scopes
570
+ self._profile = profile
571
+ self._client = client
572
+ self._redirect_uri = redirect_uri
573
+ self._store = store
574
+ self._access_url = access_url
575
+ self._locks = store_locks.setdefault(store, KeyedLocks())
576
+ self._listeners: dict[ConnectionListener, None] = {}
577
+
578
+ async def authorize(self, grant: ConnectionGrant) -> str | None:
579
+ """Returns where the principal connects their account for `grant`, sharing one link among those waiting on them.
580
+
581
+ Args:
582
+ grant: The task or schedule that needs the account.
583
+
584
+ Returns:
585
+ The URL to connect at, or None when their grant already covers the scopes.
586
+ """
587
+ async with self._lock_grant(grant.principal):
588
+ saved = await self._read(grant.principal)
589
+ if saved is not None and self._covers(saved.scopes, self._requested):
590
+ await self._hold(grant.principal, [grant], saved)
591
+
592
+ return None
593
+
594
+ return await self._wait_on_link(grant, saved)
595
+
596
+ async def construct_access_url(self, grant: ConnectionGrant) -> str:
597
+ """Returns where the principal changes what their account lets `grant` reach.
598
+
599
+ It's the connection's `access_url`, else the provider's own page for it, else a fresh consent link.
600
+
601
+ Args:
602
+ grant: The running task that lacks access.
603
+
604
+ Returns:
605
+ The URL.
606
+ """
607
+ if self._access_url is not None:
608
+ return self._access_url
609
+
610
+ if self._profile.construct_access_url is not None:
611
+ return self._profile.construct_access_url(self._client)
612
+
613
+ async with self._lock_grant(grant.principal):
614
+ return await self._wait_on_link(grant, await self._read(grant.principal))
615
+
616
+ async def callback(self, url: str | httpx.URL) -> ConnectionGrant:
617
+ """Finishes an authorization when the provider redirects the human back to `redirect_uri`.
618
+
619
+ Args:
620
+ url: The callback request's URL, absolute or relative to `redirect_uri`.
621
+
622
+ Returns:
623
+ The grant that became connected.
624
+
625
+ Raises:
626
+ AgentJamError: If the human denied access or some of the scopes, the authorization expired, or the provider refuses the code.
627
+ """
628
+ query = httpx.URL(self._redirect_uri).join(url).params
629
+ state = query.get("state", "")
630
+ pending = await self._consume(state)
631
+
632
+ if (denial := query.get("error")) is not None:
633
+ raise await self._deny_waiting(
634
+ pending.principal, f"The human denied access ({denial})"
635
+ )
636
+
637
+ if (code := query.get("code")) is None:
638
+ raise AgentJamError("The OAuth callback has no code")
639
+
640
+ return await self._exchange(state, pending, code)
641
+
642
+ async def token(self, holder: ConnectionHolder, name: str | None = None) -> str:
643
+ """Returns a current access token for `holder`, refreshing it once for concurrent callers when it expires.
644
+
645
+ Args:
646
+ holder: The task or schedule using the account.
647
+ name: The token's name. Defaults to the profile's default token.
648
+
649
+ Returns:
650
+ The access token.
651
+
652
+ Raises:
653
+ ConnectionRevokedError: Once access is lost.
654
+ AgentJamError: If the grant has no such token, or the provider refuses a refresh.
655
+ """
656
+ wanted = name if name is not None else self._profile.default_token
657
+ principal = await self._find_principal(holder)
658
+ saved = self._get_token(await self._find_holding(principal, holder), wanted)
659
+ if is_fresh(saved):
660
+ return saved.access_token
661
+
662
+ async with self._lock_grant(principal):
663
+ current = await self._find_holding(principal, holder)
664
+ tokens = self._get_token(current, wanted)
665
+ if is_fresh(tokens):
666
+ return tokens.access_token
667
+
668
+ return await self._refresh(principal, current, wanted)
669
+
670
+ async def account(self, holder: ConnectionHolder) -> Account | None:
671
+ """Returns the account `holder` uses.
672
+
673
+ Args:
674
+ holder: The task or schedule using the account.
675
+
676
+ Returns:
677
+ The account, if the provider's token response named it.
678
+
679
+ Raises:
680
+ ConnectionRevokedError: Once access is lost.
681
+ """
682
+ principal = await self._find_principal(holder)
683
+
684
+ return (await self._find_holding(principal, holder)).account
685
+
686
+ async def release(self, holder: ConnectionHolder) -> None:
687
+ """Stops `holder` from using the principal's account, revoking the grant once nothing uses it with `revoke_on_end`.
688
+
689
+ Args:
690
+ holder: The task or schedule that ended.
691
+ """
692
+ principal = await self._get(construct_holder_key(self.provider, holder))
693
+ if principal is None:
694
+ return
695
+
696
+ async with self._lock_grant(principal):
697
+ await self._delete(construct_holder_key(self.provider, holder))
698
+ saved = await self._read(principal)
699
+ if saved is None:
700
+ return
701
+
702
+ holders = [
703
+ held for held in saved.holders if not is_same_holder(held, holder)
704
+ ]
705
+ if holders or not self.revoke_on_end:
706
+ await self._save(
707
+ principal, saved.model_copy(update={"holders": holders})
708
+ )
709
+
710
+ return
711
+
712
+ await self._delete(construct_grant_key(self.provider, principal))
713
+ shared = await self._leave_account(principal, saved.account)
714
+ await self._revoke_tokens(saved.tokens, keep_shared=shared)
715
+
716
+ async def revoke(self, principal: str) -> None:
717
+ """Revokes a human's grant with the provider and forgets its tokens, which ends every task and schedule that uses it.
718
+
719
+ Args:
720
+ principal: The human whose account to disconnect.
721
+
722
+ Raises:
723
+ AgentJamError: If the provider refuses the revocation.
724
+ """
725
+ async with self._lock_grant(principal):
726
+ saved = await self._read(principal)
727
+ if saved is not None:
728
+ await self._revoke_grant(principal, saved)
729
+
730
+ await self._lose(principal, saved, "The executor removed the connection")
731
+
732
+ async def revoke_account(self, revocation: AccountRevocation) -> None:
733
+ """Ends every grant of the account that `revocation` names, or of its `subject`, without calling the provider.
734
+
735
+ Args:
736
+ revocation: The account, and why its access ended.
737
+ """
738
+ for principal in await self._read_members(revocation.id):
739
+ async with self._lock_grant(principal):
740
+ saved = await self._read(principal)
741
+ account = saved.account if saved is not None else None
742
+ if account is None or account.id != revocation.id:
743
+ continue
744
+
745
+ if (
746
+ revocation.subject is not None
747
+ and account.subject != revocation.subject
748
+ ):
749
+ continue
750
+
751
+ await self._lose(principal, saved, revocation.reason)
752
+
753
+ def watch(self, listener: ConnectionListener) -> Callable[[], None]:
754
+ """Calls `listener` on every connection event.
755
+
756
+ Args:
757
+ listener: Called with each event.
758
+
759
+ Returns:
760
+ A function that stops calling `listener`.
761
+ """
762
+ self._listeners[listener] = None
763
+
764
+ def stop() -> None:
765
+ self._listeners.pop(listener, None)
766
+
767
+ return stop
768
+
769
+ def _lock_grant(self, principal: str) -> AbstractAsyncContextManager[None]:
770
+ return self._locks.hold(construct_grant_key(self.provider, principal))
771
+
772
+ async def _get(self, key: str) -> str | None:
773
+ return await resolve_value(self._store.get(key))
774
+
775
+ async def _set(self, key: str, value: str) -> None:
776
+ await resolve_value(self._store.set(key, value))
777
+
778
+ async def _delete(self, key: str) -> None:
779
+ await resolve_value(self._store.delete(key))
780
+
781
+ async def _read(self, principal: str) -> SavedGrant | None:
782
+ saved = await self._get(construct_grant_key(self.provider, principal))
783
+
784
+ return SavedGrant.model_validate_json(saved) if saved is not None else None
785
+
786
+ async def _save(self, principal: str, grant: SavedGrant) -> None:
787
+ await self._set(
788
+ construct_grant_key(self.provider, principal),
789
+ grant.model_dump_json(exclude_none=True),
790
+ )
791
+
792
+ async def _read_members(self, id: str) -> list[str]:
793
+ saved = await self._get(construct_account_key(self.provider, id))
794
+
795
+ return (
796
+ [str(member) for member in json.loads(saved)] if saved is not None else []
797
+ )
798
+
799
+ async def _update_members(
800
+ self, id: str, update: Callable[[list[str]], list[str]]
801
+ ) -> list[str]:
802
+ key = construct_account_key(self.provider, id)
803
+
804
+ async with self._locks.hold(key):
805
+ members = update(await self._read_members(id))
806
+ if members:
807
+ await self._set(key, encode_json(members))
808
+ else:
809
+ await self._delete(key)
810
+
811
+ return members
812
+
813
+ async def _join_account(self, principal: str, account: Account | None) -> None:
814
+ if account is not None:
815
+ await self._update_members(
816
+ account.id, lambda members: union(members, [principal])
817
+ )
818
+
819
+ async def _leave_account(self, principal: str, account: Account | None) -> bool:
820
+ """Removes `principal` from the members of `account`, and returns whether another member still shares its tokens."""
821
+ if account is None:
822
+ return False
823
+
824
+ remaining = await self._update_members(
825
+ account.id,
826
+ lambda members: [member for member in members if member != principal],
827
+ )
828
+
829
+ return len(remaining) > 0
830
+
831
+ async def _hold(
832
+ self, principal: str, holders: Sequence[ConnectionHolder], saved: SavedGrant
833
+ ) -> None:
834
+ await asyncio.gather(
835
+ *(
836
+ self._set(construct_holder_key(self.provider, holder), principal)
837
+ for holder in holders
838
+ )
839
+ )
840
+ held = reduce(add_holder, holders, saved.holders)
841
+ await self._save(principal, saved.model_copy(update={"holders": held}))
842
+
843
+ async def _read_link(self, principal: str) -> PendingLink | None:
844
+ saved = await self._get(construct_pending_key(self.provider, principal))
845
+ current = PendingLink.model_validate_json(saved) if saved is not None else None
846
+
847
+ return (
848
+ current
849
+ if current is not None and current.expires_at > compute_now()
850
+ else None
851
+ )
852
+
853
+ async def _save_link(self, principal: str, current: PendingLink) -> None:
854
+ key = construct_pending_key(self.provider, principal)
855
+ if current.holders:
856
+ await self._set(key, current.model_dump_json(exclude_none=True))
857
+ else:
858
+ await self._delete(key)
859
+
860
+ async def _lose(
861
+ self, principal: str, saved: SavedGrant | None, reason: str
862
+ ) -> ConnectionRevokedError:
863
+ holders = saved.holders if saved is not None else []
864
+ await asyncio.gather(
865
+ *(
866
+ self._delete(construct_holder_key(self.provider, holder))
867
+ for holder in holders
868
+ )
869
+ )
870
+ await self._delete(construct_grant_key(self.provider, principal))
871
+ await self._leave_account(
872
+ principal, saved.account if saved is not None else None
873
+ )
874
+
875
+ self._emit(
876
+ ConnectionRevoked(
877
+ provider=self.provider,
878
+ principal=principal,
879
+ requesters=list_requesters(holders),
880
+ reason=reason,
881
+ )
882
+ )
883
+
884
+ return ConnectionRevokedError(self.provider, reason)
885
+
886
+ def _emit(self, event: ConnectionEvent) -> None:
887
+ for listener in list(self._listeners):
888
+ listener(event)
889
+
890
+ def _deny(
891
+ self, holders: Iterable[ConnectionHolder], principal: str, reason: str
892
+ ) -> None:
893
+ for holder in holders:
894
+ grant = construct_grant(holder, principal)
895
+ self._emit(
896
+ ConnectionDenied(provider=self.provider, grant=grant, reason=reason)
897
+ )
898
+
899
+ def _require_consent(
900
+ self, holders: Iterable[ConnectionHolder], principal: str, url: str
901
+ ) -> None:
902
+ for holder in holders:
903
+ self._emit(
904
+ ConnectionRequired(
905
+ provider=self.provider,
906
+ grant=construct_grant(holder, principal),
907
+ url=url,
908
+ reason="Grant every permission the link asks for",
909
+ )
910
+ )
911
+
912
+ def _covers_token(self, granted: list[str], wanted: list[str]) -> bool:
913
+ held = {
914
+ implied
915
+ for scope in granted
916
+ for implied in (scope, *self._profile.implied_scopes.get(scope, []))
917
+ }
918
+
919
+ return all(scope in held for scope in wanted)
920
+
921
+ def _covers(self, granted: Scopes, wanted: Scopes) -> bool:
922
+ return all(
923
+ self._covers_token(granted.get(token, []), needed)
924
+ for token, needed in wanted.items()
925
+ )
926
+
927
+ async def _request_tokens(
928
+ self, form: dict[str, str]
929
+ ) -> tuple[TokenResponse, TokenError | None]:
930
+ response = await post_form(
931
+ self._profile.endpoints.token,
932
+ {
933
+ "client_id": self._client.client_id,
934
+ "client_secret": self._client.client_secret,
935
+ **form,
936
+ },
937
+ {"accept": "application/json"},
938
+ )
939
+ body: TokenResponse = response.json()
940
+
941
+ return body, self._profile.read_error(response, body)
942
+
943
+ async def _revoke_tokens(
944
+ self, tokens: dict[str, Tokens], *, keep_shared: bool
945
+ ) -> None:
946
+ for name, issued in tokens.items():
947
+ if not keep_shared or name not in self._profile.shared_tokens:
948
+ await self._profile.revoke_tokens(issued, self._client)
949
+
950
+ async def _revoke_grant(self, principal: str, saved: SavedGrant) -> None:
951
+ shared = await self._leave_account(principal, saved.account)
952
+
953
+ try:
954
+ await self._revoke_tokens(saved.tokens, keep_shared=shared)
955
+ except BaseException:
956
+ await self._join_account(principal, saved.account)
957
+ raise
958
+
959
+ def _get_token(self, saved: SavedGrant, name: str) -> Tokens:
960
+ if (issued := saved.tokens.get(name)) is None:
961
+ raise AgentJamError(
962
+ f'The {self.provider} grant has no token named "{name}"'
963
+ )
964
+
965
+ return issued
966
+
967
+ async def _refresh(self, principal: str, saved: SavedGrant, name: str) -> str:
968
+ refresh_token = self._get_token(saved, name).refresh_token
969
+ if not refresh_token:
970
+ raise await self._lose(
971
+ principal,
972
+ saved,
973
+ "The access token expired, and the provider issued no refresh token",
974
+ )
975
+
976
+ body, error = await self._request_tokens(
977
+ {"grant_type": "refresh_token", "refresh_token": refresh_token}
978
+ )
979
+ if error is not None and error.code in self._profile.lost_grant_errors:
980
+ raise await self._lose(principal, saved, LOST_GRANT)
981
+
982
+ if error is not None:
983
+ raise construct_refusal(error)
984
+
985
+ refreshed = self._profile.parse_tokens(body, saved.tokens).tokens
986
+ if (issued := refreshed.get(name)) is None:
987
+ raise AgentJamError(
988
+ f'The provider\'s refresh response has no token named "{name}"'
989
+ )
990
+
991
+ tokens = {**saved.tokens, **refreshed}
992
+ await self._save(principal, saved.model_copy(update={"tokens": tokens}))
993
+
994
+ return issued.access_token
995
+
996
+ async def _find_principal(self, holder: ConnectionHolder) -> str:
997
+ principal = await self._get(construct_holder_key(self.provider, holder))
998
+ if principal is None:
999
+ raise ConnectionRevokedError(
1000
+ self.provider, "The account isn't connected for this task"
1001
+ )
1002
+
1003
+ return principal
1004
+
1005
+ async def _find_holding(
1006
+ self, principal: str, holder: ConnectionHolder
1007
+ ) -> SavedGrant:
1008
+ saved = await self._read(principal)
1009
+ if saved is None or not any(
1010
+ is_same_holder(held, holder) for held in saved.holders
1011
+ ):
1012
+ raise ConnectionRevokedError(
1013
+ self.provider, "The account isn't connected for this task"
1014
+ )
1015
+
1016
+ return saved
1017
+
1018
+ async def _settle_link(
1019
+ self, state: str, principal: str, granted: Scopes, body: TokenResponse
1020
+ ) -> Settlement:
1021
+ """Holds the waiting holders `granted` covers, moving the rest onto a new link for the same scopes when `state` was their current one."""
1022
+ async with self._lock_grant(principal):
1023
+ current = await self._read_link(principal)
1024
+ waiting = current.holders if current is not None else []
1025
+ ready = [
1026
+ holder for holder in waiting if self._covers(granted, holder.scopes)
1027
+ ]
1028
+ unready = [holder for holder in waiting if holder not in ready]
1029
+ relinked = (
1030
+ await self._link(principal, current.scopes)
1031
+ if current is not None and current.state == state and unready
1032
+ else None
1033
+ )
1034
+
1035
+ if current is not None:
1036
+ kept = relinked or current
1037
+ await self._save_link(
1038
+ principal, kept.model_copy(update={"holders": unready})
1039
+ )
1040
+
1041
+ saved = await self._read(principal)
1042
+ if ready:
1043
+ parsed = self._profile.parse_tokens(
1044
+ body, saved.tokens if saved else None
1045
+ )
1046
+ merged = merge_grant(saved, parsed, granted)
1047
+ earlier = saved.account if saved is not None else None
1048
+ if get_account_id(earlier) != get_account_id(merged.account):
1049
+ await self._leave_account(principal, earlier)
1050
+
1051
+ await self._join_account(principal, merged.account)
1052
+ await self._hold(principal, ready, merged)
1053
+ elif saved is None:
1054
+ # WARNING: revoking a Google or GitHub token revokes the whole grant, so a partial consent keeps the earlier tokens.
1055
+ parsed = self._profile.parse_tokens(body, None)
1056
+ shared = await self._leave_account(principal, parsed.account)
1057
+ await self._revoke_tokens(parsed.tokens, keep_shared=shared)
1058
+
1059
+ relink = Relink(url=relinked.url, holders=unready) if relinked else None
1060
+
1061
+ return Settlement(ready=ready, relink=relink)
1062
+
1063
+ async def _exchange(
1064
+ self, state: str, pending: PendingAuthorization, code: str
1065
+ ) -> ConnectionGrant:
1066
+ form = {
1067
+ "grant_type": "authorization_code",
1068
+ "code": code,
1069
+ "redirect_uri": self._redirect_uri,
1070
+ }
1071
+ if pending.verifier is not None:
1072
+ form["code_verifier"] = pending.verifier
1073
+
1074
+ body, error = await self._request_tokens(form)
1075
+ if error is not None:
1076
+ raise construct_refusal(error)
1077
+
1078
+ granted = compute_granted_scopes(
1079
+ self._profile.parse_tokens(body, None), pending.scopes
1080
+ )
1081
+ settled = await self._settle_link(state, pending.principal, granted, body)
1082
+
1083
+ if settled.relink is not None:
1084
+ self._require_consent(
1085
+ settled.relink.holders, pending.principal, settled.relink.url
1086
+ )
1087
+
1088
+ for holder in settled.ready:
1089
+ grant = construct_grant(holder, pending.principal)
1090
+ self._emit(ConnectionReady(provider=self.provider, grant=grant))
1091
+
1092
+ if settled.ready:
1093
+ return construct_grant(settled.ready[0], pending.principal)
1094
+
1095
+ raise AgentJamError(
1096
+ "The human didn't grant every scope, so they must consent again at a new link"
1097
+ if settled.relink is not None
1098
+ else "No task waits on this authorization any more"
1099
+ )
1100
+
1101
+ async def _deny_waiting(self, principal: str, reason: str) -> AgentJamError:
1102
+ async with self._lock_grant(principal):
1103
+ current = await self._read_link(principal)
1104
+ await self._delete(construct_pending_key(self.provider, principal))
1105
+
1106
+ self._deny(current.holders if current is not None else [], principal, reason)
1107
+
1108
+ return AgentJamError(reason)
1109
+
1110
+ async def _consume(self, state: str) -> PendingAuthorization:
1111
+ saved = await self._get(construct_state_key(state))
1112
+ if saved is None:
1113
+ raise AgentJamError("The OAuth callback answers no pending authorization")
1114
+
1115
+ await self._delete(construct_state_key(state))
1116
+ pending = PendingAuthorization.model_validate_json(saved)
1117
+ if pending.expires_at <= compute_now():
1118
+ raise AgentJamError(
1119
+ "The authorization expired, so the human must start over from a new link"
1120
+ )
1121
+
1122
+ return pending
1123
+
1124
+ async def _link(self, principal: str, wanted: Scopes) -> PendingLink:
1125
+ state = secrets.token_urlsafe(16)
1126
+ verifier = secrets.token_urlsafe(32) if self._profile.pkce else None
1127
+ expires_at = compute_now() + AUTHORIZATION_TTL
1128
+ pending = PendingAuthorization(
1129
+ principal=principal, verifier=verifier, scopes=wanted, expires_at=expires_at
1130
+ )
1131
+ await self._set(
1132
+ construct_state_key(state), pending.model_dump_json(exclude_none=True)
1133
+ )
1134
+
1135
+ params = {
1136
+ **self._profile.construct_authorize_params(wanted),
1137
+ "response_type": "code",
1138
+ "client_id": self._client.client_id,
1139
+ "redirect_uri": self._redirect_uri,
1140
+ "state": state,
1141
+ }
1142
+ if verifier is not None:
1143
+ params |= {
1144
+ "code_challenge": compute_challenge(verifier),
1145
+ "code_challenge_method": "S256",
1146
+ }
1147
+
1148
+ url = httpx.URL(self._profile.endpoints.authorize).copy_merge_params(params)
1149
+
1150
+ return PendingLink(
1151
+ state=state, url=str(url), scopes=wanted, expires_at=expires_at
1152
+ )
1153
+
1154
+ async def _wait_on_link(
1155
+ self, grant: ConnectionGrant, saved: SavedGrant | None
1156
+ ) -> str:
1157
+ """Puts the grant's holder on the principal's current link while it covers the scopes, else on a newly minted one."""
1158
+ current = await self._read_link(grant.principal)
1159
+ waiting = WaitingHolder(
1160
+ requester=grant.requester, id=grant.id, scopes=self._requested
1161
+ )
1162
+ holders = add_waiting(current.holders if current is not None else [], waiting)
1163
+
1164
+ if current is not None and self._covers(current.scopes, self._requested):
1165
+ await self._save_link(
1166
+ grant.principal, current.model_copy(update={"holders": holders})
1167
+ )
1168
+
1169
+ return current.url
1170
+
1171
+ wanted = [
1172
+ saved.scopes if saved is not None else {},
1173
+ current.scopes if current is not None else {},
1174
+ self._requested,
1175
+ ]
1176
+ minted = await self._link(grant.principal, reduce(union_scopes, wanted))
1177
+ await self._save_link(
1178
+ grant.principal, minted.model_copy(update={"holders": holders})
1179
+ )
1180
+
1181
+ return minted.url
1182
+
1183
+
1184
+ def oauth_connection(
1185
+ *,
1186
+ provider: str,
1187
+ scopes: ConnectionScopes,
1188
+ client_id: str,
1189
+ client_secret: str,
1190
+ redirect_uri: str,
1191
+ store: ConnectionStore,
1192
+ endpoints: OAuthEndpoints | None = None,
1193
+ profile: OAuthProfile | None = None,
1194
+ app_slug: str | None = None,
1195
+ access_url: str | None = None,
1196
+ revoke_on_end: bool = False,
1197
+ ) -> OAuthConnection:
1198
+ """Connects a skill to a human's account with an OAuth 2.0 provider, which defaults to a built-in profile for `google`, `github`, `github-app` or `slack`.
1199
+
1200
+ Each human connects once, and their later tasks and schedules reuse the grant while it covers their scopes,
1201
+ whichever agent requested them. Those waiting on the human at the same time share one link, which connects them all.
1202
+
1203
+ Args:
1204
+ provider: 1 to 64 lowercase letters, digits, hyphens or underscores.
1205
+ scopes: The OAuth scopes the skill asks the human to grant, as a list or lists keyed by token name.
1206
+ client_id: The OAuth client id the provider issued to the executor.
1207
+ client_secret: The OAuth client secret the provider issued to the executor.
1208
+ redirect_uri: The executor's callback URL registered with the provider, which passes each request to `callback()`.
1209
+ store: Where the connection keeps its tokens and pending authorizations.
1210
+ endpoints: The provider's endpoints, which treat it as a standard OAuth 2.0 provider instead of a built-in one.
1211
+ profile: How to run the provider's flow, for providers that depart from the standard.
1212
+ app_slug: The GitHub App's slug, as its public page URL shows it, which the `github-app` provider needs.
1213
+ access_url: Where a connected human changes what the executor reaches. Defaults to the provider's own page, else a fresh consent link.
1214
+ revoke_on_end: Whether to revoke access with the provider once no task or schedule uses a grant.
1215
+
1216
+ Returns:
1217
+ A connection to list in a skill's `connections`.
1218
+
1219
+ Raises:
1220
+ AgentJamError: If both `profile` and `endpoints` are passed, neither is for an unknown provider, or a `github-app` connection has scopes or no `app_slug`.
1221
+ """
1222
+ resolved = resolve_profile(provider, scopes, endpoints, profile, app_slug)
1223
+
1224
+ return OAuthConnection(
1225
+ provider=provider,
1226
+ scopes=construct_scope_record(scopes, resolved.default_token),
1227
+ profile=resolved,
1228
+ client=OAuthClient(client_id=client_id, client_secret=client_secret),
1229
+ redirect_uri=redirect_uri,
1230
+ store=store,
1231
+ access_url=access_url,
1232
+ revoke_on_end=revoke_on_end,
1233
+ )
1234
+
1235
+
1236
+ def construct_readiness_key(holder: ConnectionHolder) -> str:
1237
+ return encode_json([holder.requester, holder.id])
1238
+
1239
+
1240
+ @dataclass(kw_only=True)
1241
+ class Expectation:
1242
+ providers: set[str]
1243
+ outcome: asyncio.Future[None]
1244
+
1245
+
1246
+ class Readiness:
1247
+ """Holds back one-off tasks until the requester's human connected every account their skill still needs."""
1248
+
1249
+ def __init__(self) -> None:
1250
+ self._awaited: dict[str, Expectation] = {}
1251
+
1252
+ def expect(self, holder: ConnectionHolder, providers: Sequence[str]) -> None:
1253
+ if not providers:
1254
+ return
1255
+
1256
+ self._awaited[construct_readiness_key(holder)] = Expectation(
1257
+ providers=set(providers),
1258
+ outcome=asyncio.get_running_loop().create_future(),
1259
+ )
1260
+
1261
+ def settle(self, provider: str, holder: ConnectionHolder) -> None:
1262
+ entry = self._awaited.get(construct_readiness_key(holder))
1263
+ if entry is None or provider not in entry.providers:
1264
+ return
1265
+
1266
+ entry.providers.discard(provider)
1267
+ if not entry.providers and not entry.outcome.done():
1268
+ entry.outcome.set_result(None)
1269
+
1270
+ async def wait(self, holder: ConnectionHolder, signal: Signal) -> None:
1271
+ """Returns once `holder` is ready, and raises the signal's reason if it aborted first."""
1272
+ key = construct_readiness_key(holder)
1273
+ if (entry := self._awaited.get(key)) is None:
1274
+ return
1275
+
1276
+ try:
1277
+ await guard(entry.outcome, signal)
1278
+ finally:
1279
+ self._awaited.pop(key, None)
1280
+
1281
+ def forget(self, holder: ConnectionHolder) -> None:
1282
+ self._awaited.pop(construct_readiness_key(holder), None)