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/_providers.py ADDED
@@ -0,0 +1,365 @@
1
+ import base64
2
+ import re
3
+ from collections.abc import Awaitable, Callable, Mapping
4
+ from dataclasses import dataclass, replace
5
+ from datetime import UTC, datetime, timedelta
6
+ from typing import Annotated, Any, TypeAlias
7
+ from urllib.parse import quote
8
+
9
+ import httpx
10
+ from pydantic import BeforeValidator, PlainSerializer
11
+
12
+ from agentjam._errors import AgentJamError
13
+ from agentjam._models import WireModel
14
+ from agentjam._types import Account
15
+
16
+
17
+ def parse_epoch_milliseconds(value: object) -> object:
18
+ if isinstance(value, int | float) and not isinstance(value, bool):
19
+ return datetime.fromtimestamp(value / 1000, UTC)
20
+
21
+ return value
22
+
23
+
24
+ def format_epoch_milliseconds(moment: datetime) -> int:
25
+ return round(moment.timestamp() * 1000)
26
+
27
+
28
+ EpochMilliseconds: TypeAlias = Annotated[
29
+ datetime,
30
+ BeforeValidator(parse_epoch_milliseconds),
31
+ PlainSerializer(format_epoch_milliseconds, return_type=int, when_used="json"),
32
+ ]
33
+ """A moment saved as milliseconds since the epoch, the shape every AgentJam SDK reads from a shared store."""
34
+
35
+ TokenResponse: TypeAlias = dict[str, Any]
36
+ """A token endpoint's JSON response, as the provider sent it."""
37
+
38
+ DEFAULT_TOKEN = "default"
39
+ """The name of the only token a standard provider issues."""
40
+
41
+
42
+ class OAuthEndpoints(WireModel):
43
+ """A provider's OAuth 2.0 endpoints, plus extra `params` for its authorization URL."""
44
+
45
+ authorize: str
46
+ """The URL where the human grants access."""
47
+ token: str
48
+ """The URL that exchanges codes and refresh tokens for access tokens."""
49
+ revoke: str | None = None
50
+ """The URL that revokes a token, if the provider has one."""
51
+ params: dict[str, str] | None = None
52
+ """Extra query parameters for the authorization URL."""
53
+
54
+
55
+ class Tokens(WireModel):
56
+ """An access token, with the refresh token that renews it if the provider issued one."""
57
+
58
+ access_token: str
59
+ refresh_token: str | None = None
60
+ expires_at: EpochMilliseconds | None = None
61
+ """When the access token expires."""
62
+
63
+
64
+ class OAuthClient(WireModel):
65
+ """The client credentials the provider issued to the executor."""
66
+
67
+ client_id: str
68
+ client_secret: str
69
+
70
+
71
+ class TokenError(WireModel):
72
+ """Why the provider refused a token request."""
73
+
74
+ code: str
75
+ """The provider's error code, such as `invalid_grant`."""
76
+ description: str | None = None
77
+ """The provider's explanation, if it sent one."""
78
+
79
+
80
+ class AccountRevocation(WireModel):
81
+ """An account that lost access with the provider, such as a Slack workspace that uninstalled the app."""
82
+
83
+ id: str
84
+ """The account's id with the provider."""
85
+ subject: str | None = None
86
+ """The person whose access ended, or None when it ended for everyone who connected the account."""
87
+ reason: str
88
+ """Why access ended, shown to the requesters whose tasks and schedules it ends."""
89
+
90
+
91
+ class ParsedTokens(WireModel):
92
+ """The tokens a token response issued."""
93
+
94
+ tokens: dict[str, Tokens]
95
+ """The tokens issued, keyed by name. A provider that issues one token names it `default`."""
96
+ scopes: dict[str, list[str]] | None = None
97
+ """The scopes granted to each token. A token left out is granted every scope requested for it."""
98
+ account: Account | None = None
99
+ """The account the tokens are for, if the response says."""
100
+
101
+
102
+ @dataclass(frozen=True, kw_only=True)
103
+ class OAuthProfile:
104
+ """How to run a provider's OAuth 2.0 flow, which `dataclasses.replace()` can adjust.
105
+
106
+ `oauth_connection()` knows Google's, GitHub's, GitHub Apps' and Slack's, and `construct_standard_profile()`
107
+ builds one for any provider that follows the standard.
108
+ """
109
+
110
+ endpoints: OAuthEndpoints
111
+ pkce: bool
112
+ """Whether authorizations send a PKCE challenge and code exchanges its verifier."""
113
+ default_token: str
114
+ """The token that list-form scopes are requested for, and that `token()` returns unless told another."""
115
+ shared_tokens: list[str]
116
+ """The tokens every human who connects the same account shares, revoked only once none of them uses it."""
117
+ implied_scopes: dict[str, list[str]]
118
+ """Invariant: maps a scope to every scope it implies, including the ones its implied scopes imply."""
119
+ lost_grant_errors: list[str]
120
+ """The token error codes that mean the human revoked access or the grant expired."""
121
+ construct_authorize_params: Callable[[dict[str, list[str]]], dict[str, str]]
122
+ """Returns the authorization URL's query parameters that request each token's scopes, plus any the provider needs."""
123
+ parse_tokens: Callable[[TokenResponse, Mapping[str, Tokens] | None], ParsedTokens]
124
+ """Reads the tokens out of a successful token response, keeping earlier values the response leaves out."""
125
+ read_error: Callable[[httpx.Response, TokenResponse], TokenError | None]
126
+ """Returns why the provider refused a token request, or None if it succeeded."""
127
+ revoke_tokens: Callable[[Tokens, OAuthClient], Awaitable[None]]
128
+ """Revokes one of a grant's tokens, raising if the provider refuses, or returns when the provider can't revoke."""
129
+ construct_access_url: Callable[[OAuthClient], str] | None = None
130
+ """Returns where a human who already connected changes what the executor reaches, for providers with such a page."""
131
+
132
+
133
+ async def post_form(
134
+ url: str, form: Mapping[str, str], headers: Mapping[str, str] | None = None
135
+ ) -> httpx.Response:
136
+ async with httpx.AsyncClient() as client:
137
+ return await client.post(
138
+ url,
139
+ data=dict(form),
140
+ headers={
141
+ "content-type": "application/x-www-form-urlencoded",
142
+ **(headers or {}),
143
+ },
144
+ )
145
+
146
+
147
+ def encode_component(text: str) -> str:
148
+ return quote(text, safe="!~*'()")
149
+
150
+
151
+ def read_string(body: TokenResponse, key: str) -> str | None:
152
+ value = body.get(key)
153
+
154
+ return value if isinstance(value, str) else None
155
+
156
+
157
+ def read_number(body: TokenResponse, key: str) -> float | None:
158
+ value = body.get(key)
159
+
160
+ return (
161
+ value
162
+ if isinstance(value, int | float) and not isinstance(value, bool)
163
+ else None
164
+ )
165
+
166
+
167
+ def parse_scopes(scope: str) -> list[str]:
168
+ return [granted for granted in re.split(r"[\s,]+", scope) if granted]
169
+
170
+
171
+ def parse_standard_token(body: TokenResponse, previous: Tokens | None = None) -> Tokens:
172
+ """Reads an access token, its refresh token and its expiry from a token response's standard fields.
173
+
174
+ Custom profiles reuse it for each token a response nests, such as Slack's user token.
175
+
176
+ Args:
177
+ body: The token response, or the object nested in it that holds one token.
178
+ previous: The token's earlier values, whose refresh token is kept when the response leaves it out.
179
+
180
+ Returns:
181
+ The token.
182
+
183
+ Raises:
184
+ AgentJamError: If the response has no access token.
185
+ """
186
+ access_token = read_string(body, "access_token")
187
+ if not access_token:
188
+ raise AgentJamError("The provider's token response has no access_token")
189
+
190
+ refresh_token = read_string(body, "refresh_token")
191
+ if refresh_token is None and previous is not None:
192
+ refresh_token = previous.refresh_token
193
+
194
+ expires_in = read_number(body, "expires_in")
195
+ expires_at = (
196
+ None
197
+ if expires_in is None
198
+ else datetime.now(UTC) + timedelta(seconds=expires_in)
199
+ )
200
+
201
+ return Tokens(
202
+ access_token=access_token, refresh_token=refresh_token, expires_at=expires_at
203
+ )
204
+
205
+
206
+ def parse_standard_tokens(
207
+ body: TokenResponse, previous: Mapping[str, Tokens] | None
208
+ ) -> ParsedTokens:
209
+ scope = read_string(body, "scope")
210
+
211
+ return ParsedTokens(
212
+ tokens={
213
+ DEFAULT_TOKEN: parse_standard_token(
214
+ body, previous.get(DEFAULT_TOKEN) if previous else None
215
+ )
216
+ },
217
+ scopes={DEFAULT_TOKEN: parse_scopes(scope)} if scope is not None else None,
218
+ )
219
+
220
+
221
+ # WARNING: some providers, such as GitHub, answer a refused token request with a successful status.
222
+ def read_standard_error(
223
+ response: httpx.Response, body: TokenResponse
224
+ ) -> TokenError | None:
225
+ code = read_string(body, "error")
226
+ if response.is_success and code is None:
227
+ return None
228
+
229
+ return TokenError(
230
+ code=code if code is not None else f"status {response.status_code}",
231
+ description=read_string(body, "error_description"),
232
+ )
233
+
234
+
235
+ def construct_standard_profile(endpoints: OAuthEndpoints) -> OAuthProfile:
236
+ """Builds the profile of a provider that follows the OAuth 2.0 standard, with PKCE, space-separated scopes and RFC 7009 revocation.
237
+
238
+ Adjust a hook with `dataclasses.replace()`, such as `replace(construct_standard_profile(endpoints), pkce=False)`.
239
+
240
+ Args:
241
+ endpoints: The provider's endpoints.
242
+
243
+ Returns:
244
+ The provider's profile.
245
+ """
246
+
247
+ def construct_authorize_params(scopes: dict[str, list[str]]) -> dict[str, str]:
248
+ return {
249
+ **(endpoints.params or {}),
250
+ "scope": " ".join(scopes.get(DEFAULT_TOKEN, [])),
251
+ }
252
+
253
+ async def revoke_tokens(tokens: Tokens, _: OAuthClient) -> None:
254
+ if endpoints.revoke is None:
255
+ return
256
+
257
+ response = await post_form(
258
+ endpoints.revoke, {"token": tokens.refresh_token or tokens.access_token}
259
+ )
260
+ if not response.is_success:
261
+ raise AgentJamError(
262
+ f"The provider refused to revoke the grant (status {response.status_code})"
263
+ )
264
+
265
+ return OAuthProfile(
266
+ endpoints=endpoints,
267
+ pkce=True,
268
+ default_token=DEFAULT_TOKEN,
269
+ shared_tokens=[],
270
+ implied_scopes={},
271
+ lost_grant_errors=["invalid_grant"],
272
+ construct_authorize_params=construct_authorize_params,
273
+ parse_tokens=parse_standard_tokens,
274
+ read_error=read_standard_error,
275
+ revoke_tokens=revoke_tokens,
276
+ )
277
+
278
+
279
+ async def revoke_github_grant(tokens: Tokens, client: OAuthClient) -> None:
280
+ credentials = base64.b64encode(
281
+ f"{client.client_id}:{client.client_secret}".encode()
282
+ ).decode()
283
+
284
+ async with httpx.AsyncClient() as http:
285
+ response = await http.request(
286
+ "DELETE",
287
+ f"https://api.github.com/applications/{encode_component(client.client_id)}/grant",
288
+ headers={
289
+ "authorization": f"Basic {credentials}",
290
+ "accept": "application/vnd.github+json",
291
+ "x-github-api-version": "2022-11-28",
292
+ },
293
+ json={"access_token": tokens.access_token},
294
+ )
295
+
296
+ if not response.is_success:
297
+ raise AgentJamError(
298
+ f"The provider refused to revoke the github grant (status {response.status_code})"
299
+ )
300
+
301
+
302
+ def construct_github_access_url(client: OAuthClient) -> str:
303
+ return f"https://github.com/settings/connections/applications/{encode_component(client.client_id)}"
304
+
305
+
306
+ google_profile = construct_standard_profile(
307
+ OAuthEndpoints(
308
+ authorize="https://accounts.google.com/o/oauth2/v2/auth",
309
+ token="https://oauth2.googleapis.com/token",
310
+ revoke="https://oauth2.googleapis.com/revoke",
311
+ params={
312
+ "access_type": "offline",
313
+ "prompt": "consent",
314
+ "include_granted_scopes": "true",
315
+ },
316
+ )
317
+ )
318
+
319
+ github_profile = replace(
320
+ construct_standard_profile(
321
+ OAuthEndpoints(
322
+ authorize="https://github.com/login/oauth/authorize",
323
+ token="https://github.com/login/oauth/access_token",
324
+ )
325
+ ),
326
+ implied_scopes={
327
+ "repo": [
328
+ "repo:status",
329
+ "repo_deployment",
330
+ "public_repo",
331
+ "repo:invite",
332
+ "security_events",
333
+ ],
334
+ "admin:repo_hook": ["write:repo_hook", "read:repo_hook"],
335
+ "write:repo_hook": ["read:repo_hook"],
336
+ "admin:org": ["write:org", "read:org"],
337
+ "write:org": ["read:org"],
338
+ "admin:public_key": ["write:public_key", "read:public_key"],
339
+ "write:public_key": ["read:public_key"],
340
+ "user": ["read:user", "user:email", "user:follow"],
341
+ "project": ["read:project"],
342
+ "write:packages": ["read:packages"],
343
+ "admin:gpg_key": ["write:gpg_key", "read:gpg_key"],
344
+ "write:gpg_key": ["read:gpg_key"],
345
+ },
346
+ lost_grant_errors=["invalid_grant", "bad_refresh_token"],
347
+ revoke_tokens=revoke_github_grant,
348
+ construct_access_url=construct_github_access_url,
349
+ )
350
+
351
+
352
+ def construct_github_app_profile(slug: str) -> OAuthProfile:
353
+ """Builds the profile of the GitHub App with `slug`, whose link opens its installation page to pick repositories and authorize in one visit."""
354
+ installation = f"https://github.com/apps/{encode_component(slug)}/installations/new"
355
+
356
+ return replace(
357
+ github_profile,
358
+ endpoints=github_profile.endpoints.model_copy(
359
+ update={"authorize": installation}
360
+ ),
361
+ # WARNING: GitHub's installation page drops PKCE challenges, so the code exchange can't send a verifier.
362
+ pkce=False,
363
+ implied_scopes={},
364
+ construct_access_url=lambda _: installation,
365
+ )
agentjam/_recaps.py ADDED
@@ -0,0 +1,67 @@
1
+ from datetime import datetime
2
+ from functools import partial
3
+
4
+ from agentjam._artifacts import download
5
+ from agentjam._errors import AgentJamError
6
+ from agentjam._files import File
7
+ from agentjam._protocol import AttachmentRef, RecappedArtifactRef, TaskRecapRef
8
+ from agentjam._types import RecappedArtifact, RecappedFile, RecappedText, TaskRecap
9
+
10
+
11
+ async def download_file(id: str, ref: AttachmentRef | RecappedArtifactRef) -> File:
12
+ subject = f"file {ref.name if ref.name is not None else id}"
13
+ if not ref.url:
14
+ raise AgentJamError(f"The relay kept no copy of {subject} to download")
15
+
16
+ data = await download(ref.url, "file", subject)
17
+
18
+ return File(data, ref.name if ref.name is not None else id, ref.mime_type or "")
19
+
20
+
21
+ def construct_file(id: str, ref: AttachmentRef | RecappedArtifactRef) -> RecappedFile:
22
+ return RecappedFile(
23
+ id=id,
24
+ name=ref.name if ref.name is not None else id,
25
+ mime_type=ref.mime_type,
26
+ size=ref.size,
27
+ key=ref.key if isinstance(ref, RecappedArtifactRef) else None,
28
+ download=partial(download_file, id, ref),
29
+ )
30
+
31
+
32
+ def recap_artifact(ref: RecappedArtifactRef) -> RecappedArtifact:
33
+ if ref.kind == "file":
34
+ return construct_file(ref.artifact_id, ref)
35
+
36
+ return RecappedText(
37
+ id=ref.artifact_id,
38
+ text=ref.text or "",
39
+ truncated=bool(ref.truncated),
40
+ name=ref.name,
41
+ mime_type=ref.mime_type,
42
+ key=ref.key,
43
+ )
44
+
45
+
46
+ def recap_from_wire(recap: TaskRecapRef) -> TaskRecap:
47
+ """Turns a relay's recap of a task into the one agents read, whose files download only once asked to."""
48
+ return TaskRecap(
49
+ id=recap.task_id,
50
+ requester=recap.requester,
51
+ text=recap.text,
52
+ skill=recap.skill,
53
+ input=recap.input,
54
+ attachments=[
55
+ construct_file(ref.attachment_id, ref) for ref in recap.attachments or []
56
+ ],
57
+ status=recap.status,
58
+ error=recap.error,
59
+ updates=recap.updates,
60
+ artifacts=[recap_artifact(ref) for ref in recap.artifacts],
61
+ history=recap.history,
62
+ follow_up=recap.follow_up,
63
+ created_at=datetime.fromisoformat(recap.created_at),
64
+ ended_at=datetime.fromisoformat(recap.ended_at)
65
+ if recap.ended_at is not None
66
+ else None,
67
+ )
File without changes
@@ -0,0 +1,234 @@
1
+ from dataclasses import dataclass, field, replace
2
+ from typing import Literal
3
+
4
+ from agentjam._errors import AgentJamError
5
+ from agentjam._protocol import (
6
+ AcceptEnvelope,
7
+ ConnectionReadyEnvelope,
8
+ ConnectionRequiredEnvelope,
9
+ ConnectionRevokedEnvelope,
10
+ ProposeEnvelope,
11
+ RecurEnvelope,
12
+ RequireEnvelope,
13
+ )
14
+ from agentjam._relay.sessions import request_key
15
+ from agentjam._types import ActionOrigin, ConnectionCard, ProposalAction
16
+
17
+
18
+ @dataclass(kw_only=True)
19
+ class TrackedAction:
20
+ """An action a proposal waits on, and whether the human took it."""
21
+
22
+ kind: Literal["oauth", "credential_form"]
23
+ provider: str
24
+ url: str
25
+ origin: ActionOrigin | None = None
26
+ reason: str | None = None
27
+ status: Literal["pending", "completed"] = "pending"
28
+
29
+ @property
30
+ def is_own(self) -> bool:
31
+ return self.origin is None
32
+
33
+
34
+ @dataclass
35
+ class ProposalRecord:
36
+ id: str
37
+ requester: str
38
+ executor: str
39
+ principal: str | None
40
+ declared: list[str]
41
+ schedule: bool
42
+ schedule_id: str | None = None
43
+ status: Literal["proposed", "requires_action", "accepted", "ended"] = "proposed"
44
+ actions: list[TrackedAction] = field(default_factory=list)
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class RequiredActions:
49
+ """The actions a proposal's executor required, and whether the proposal is still open."""
50
+
51
+ actions: list[TrackedAction]
52
+ open: bool
53
+
54
+
55
+ def track_action(action: ProposalAction) -> TrackedAction:
56
+ return TrackedAction(
57
+ kind=action.kind,
58
+ provider=action.provider,
59
+ url=action.url,
60
+ origin=action.origin,
61
+ reason=action.reason,
62
+ )
63
+
64
+
65
+ class ActionLedger:
66
+ """Tracks the actions each proposal routed through a `MemoryRelay` waits on, and which proposals use a grant."""
67
+
68
+ def __init__(self) -> None:
69
+ self._proposals: dict[str, ProposalRecord] = {}
70
+
71
+ def propose(
72
+ self, proposal: ProposeEnvelope, declared: list[ConnectionCard] | None
73
+ ) -> None:
74
+ key = request_key(proposal.sender, proposal.id)
75
+ if key in self._proposals:
76
+ return
77
+
78
+ self._proposals[key] = ProposalRecord(
79
+ id=proposal.id,
80
+ requester=proposal.sender,
81
+ executor=proposal.to,
82
+ principal=proposal.principal,
83
+ declared=[connection.provider for connection in declared or []],
84
+ schedule=proposal.cron is not None or proposal.trigger is not None,
85
+ )
86
+
87
+ def recur(self, recur: RecurEnvelope) -> None:
88
+ """Tracks a schedule's run as running, with the connections its schedule declares."""
89
+ schedule = self._proposals.get(request_key(recur.sender, recur.schedule_id))
90
+ key = request_key(recur.sender, recur.task_id)
91
+ if schedule is None or key in self._proposals:
92
+ return
93
+
94
+ self._proposals[key] = replace(
95
+ schedule,
96
+ id=recur.task_id,
97
+ schedule=False,
98
+ schedule_id=recur.schedule_id,
99
+ status="accepted",
100
+ actions=[],
101
+ )
102
+
103
+ def require(self, required: RequireEnvelope) -> None:
104
+ """Holds a proposal until its actions are taken, except a task whose actions are all copies, which starts right away."""
105
+ proposal = self._proposals.get(request_key(required.to, required.reply_to))
106
+ if proposal is None or proposal.status != "proposed":
107
+ return
108
+
109
+ actions = [track_action(action) for action in required.actions]
110
+ waits = proposal.schedule or any(action.is_own for action in actions)
111
+ proposal.status = "requires_action" if waits else "accepted"
112
+ proposal.actions = actions
113
+
114
+ def require_access(self, required: ConnectionRequiredEnvelope) -> None:
115
+ """Holds a task, run or waiting schedule until its human takes the action its executor requires.
116
+
117
+ The new action replaces that provider's own action.
118
+ """
119
+ proposal = self._proposals.get(request_key(required.to, required.proposal_id))
120
+ is_waiting = proposal is not None and proposal.status == "requires_action"
121
+ is_running = (
122
+ proposal is not None
123
+ and proposal.status == "accepted"
124
+ and not proposal.schedule
125
+ )
126
+
127
+ if proposal is None or not (is_waiting or is_running):
128
+ raise AgentJamError(
129
+ f"Proposal \"{required.proposal_id}\" isn't running or waiting on its human, so it can't require access"
130
+ )
131
+
132
+ if (
133
+ proposal.executor != required.sender
134
+ or required.provider not in proposal.declared
135
+ ):
136
+ raise AgentJamError(
137
+ f'{required.sender} doesn\'t run task "{required.proposal_id}" with a {required.provider} connection'
138
+ )
139
+
140
+ kept = [
141
+ action
142
+ for action in proposal.actions
143
+ if not action.is_own or action.provider != required.provider
144
+ ]
145
+
146
+ proposal.status = "requires_action"
147
+ proposal.actions = [
148
+ *kept,
149
+ TrackedAction(
150
+ kind="oauth",
151
+ provider=required.provider,
152
+ url=required.url,
153
+ reason=required.reason,
154
+ ),
155
+ ]
156
+
157
+ def accept(self, accept: AcceptEnvelope) -> None:
158
+ proposal = self._proposals.get(request_key(accept.to, accept.reply_to))
159
+ if proposal and proposal.status == "proposed":
160
+ proposal.status = "accepted"
161
+
162
+ def complete(self, ready: ConnectionReadyEnvelope) -> bool:
163
+ """Completes a proposal's action, the copy from the preparation `origin` when it's set.
164
+
165
+ Returns whether that accepted the proposal.
166
+ """
167
+ proposal = self._proposals.get(request_key(ready.to, ready.proposal_id))
168
+ if proposal is None or proposal.status != "requires_action":
169
+ return False
170
+
171
+ action = next(
172
+ (
173
+ candidate
174
+ for candidate in proposal.actions
175
+ if candidate.provider == ready.provider
176
+ and candidate.status == "pending"
177
+ and candidate.origin == ready.origin
178
+ ),
179
+ None,
180
+ )
181
+ if action is None:
182
+ return False
183
+
184
+ action.status = "completed"
185
+ if any(action.status == "pending" for action in proposal.actions):
186
+ return False
187
+
188
+ proposal.status = "accepted"
189
+
190
+ return True
191
+
192
+ def is_completed(self, requester: str, id: str, provider: str) -> bool:
193
+ """Whether the proposal's action for `provider` was completed."""
194
+ return any(
195
+ action.provider == provider and action.status == "completed"
196
+ for action in self.find_required(requester, id).actions
197
+ )
198
+
199
+ def find_required(self, requester: str, id: str) -> RequiredActions:
200
+ proposal = self._proposals.get(request_key(requester, id))
201
+ if proposal is None:
202
+ return RequiredActions([], open=False)
203
+
204
+ return RequiredActions(proposal.actions, open=proposal.status != "ended")
205
+
206
+ def end(self, requester: str, id: str) -> None:
207
+ """Ends a proposal that was rejected or canceled, or whose task finished."""
208
+ if proposal := self._proposals.get(request_key(requester, id)):
209
+ proposal.status = "ended"
210
+
211
+ def leave(self, name: str) -> None:
212
+ """Ends every proposal `name` takes part in."""
213
+ for proposal in self._proposals.values():
214
+ if name in (proposal.requester, proposal.executor):
215
+ proposal.status = "ended"
216
+
217
+ def using(self, revoked: ConnectionRevokedEnvelope) -> list[str]:
218
+ """Lists the proposals the requester delegated for `principal` that use their grant, so a revocation ends them."""
219
+ return [
220
+ proposal.id
221
+ for proposal in self._proposals.values()
222
+ if proposal.schedule_id is None
223
+ and proposal.executor == revoked.sender
224
+ and proposal.requester == revoked.to
225
+ and proposal.principal == revoked.principal
226
+ and proposal.status != "ended"
227
+ and revoked.provider in proposal.declared
228
+ and not any(
229
+ action.is_own
230
+ and action.provider == revoked.provider
231
+ and action.status == "pending"
232
+ for action in proposal.actions
233
+ )
234
+ ]