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,288 @@
1
+ import asyncio
2
+ from collections.abc import Sequence
3
+ from typing import TYPE_CHECKING, Any, Literal
4
+
5
+ from agentjam._agent_access import AccessBroker
6
+ from agentjam._agent_delegations import Delegations
7
+ from agentjam._agent_options import OnProposal
8
+ from agentjam._agent_support import (
9
+ Judgment,
10
+ Preparation,
11
+ VerdictEnvelope,
12
+ assert_accepted,
13
+ is_schedule,
14
+ list_actions,
15
+ resolve_principal,
16
+ to_proposal,
17
+ warn_revoking,
18
+ )
19
+ from agentjam._attachments import receive_attachments
20
+ from agentjam._connections import ConnectionGrant
21
+ from agentjam._errors import describe_error
22
+ from agentjam._inputs import ParsedValue, ValueProblem, parse_value
23
+ from agentjam._protocol import (
24
+ AcceptEnvelope,
25
+ ErrorEnvelope,
26
+ ParentRef,
27
+ ProposeEnvelope,
28
+ RejectEnvelope,
29
+ Reply,
30
+ RequireEnvelope,
31
+ )
32
+ from agentjam._requests import Requester
33
+ from agentjam._screening import ProposalScreen, screen_proposal
34
+ from agentjam._tasks.incoming import ParsedInput
35
+ from agentjam._tasks.outgoing import OutgoingTask
36
+ from agentjam._types import (
37
+ ActionOrigin,
38
+ Attachment,
39
+ Delegate,
40
+ DelegatePicker,
41
+ JsonObject,
42
+ Proposal,
43
+ SkillHandler,
44
+ Verdict,
45
+ )
46
+ from agentjam._utils import create_id, resolve_value
47
+ from agentjam._verdicts import accept
48
+
49
+ if TYPE_CHECKING:
50
+ from agentjam._agent import Agent
51
+
52
+
53
+ class ProposalJudge:
54
+ """Decides on the proposals an agent receives, asking the agents its skills delegate to for what they need first."""
55
+
56
+ def __init__(
57
+ self,
58
+ agent: "Agent",
59
+ skills: Sequence[SkillHandler[Any, Any]],
60
+ *,
61
+ on_proposal: OnProposal | None,
62
+ screen: ProposalScreen | None,
63
+ access: AccessBroker,
64
+ delegations: Delegations,
65
+ requests: Requester,
66
+ ) -> None:
67
+ self._agent = agent
68
+ self._inputs = {
69
+ skill.name: skill.input for skill in skills if skill.input is not None
70
+ }
71
+ self._delegates: dict[str, list[Delegate] | DelegatePicker] = {
72
+ skill.name: skill.delegates
73
+ for skill in skills
74
+ if skill.delegates is not None
75
+ }
76
+ self._on_proposal = on_proposal
77
+ self._screen = screen
78
+ self._access = access
79
+ self._delegations = delegations
80
+ self._requests = requests
81
+
82
+ def list_delegates(self, skill: str | None) -> list[Delegate]:
83
+ """Lists the agents and skills a skill hands work off to, leaving out ones a function picks per proposal."""
84
+ delegates = None if skill is None else self._delegates.get(skill)
85
+
86
+ return delegates if isinstance(delegates, list) else []
87
+
88
+ def parse_input(
89
+ self, skill: str | None, input: JsonObject | None
90
+ ) -> ParsedValue | ValueProblem | None:
91
+ """Parses a task's input with its skill's input schema, if this process handles the skill and it has one."""
92
+ schema = None if skill is None else self._inputs.get(skill)
93
+ if skill is None or schema is None:
94
+ return None
95
+
96
+ return parse_value(skill, "input", schema, input)
97
+
98
+ async def judge(self, proposal: ProposeEnvelope) -> Judgment:
99
+ """Decides how to answer a proposal, answering with an error envelope once deciding fails."""
100
+ try:
101
+ parsed = (
102
+ None
103
+ if proposal.prepare
104
+ else self.parse_input(proposal.skill, proposal.input)
105
+ )
106
+
107
+ if isinstance(parsed, ValueProblem):
108
+ return Judgment(
109
+ RejectEnvelope(
110
+ id=create_id(),
111
+ to=proposal.sender,
112
+ reply_to=proposal.id,
113
+ reason=parsed.problem,
114
+ )
115
+ )
116
+
117
+ attachments = await receive_attachments(proposal.attachments)
118
+ verdict, preparations = await self._construct_verdict(proposal, attachments)
119
+
120
+ return Judgment(
121
+ verdict,
122
+ attachments,
123
+ None if parsed is None else ParsedInput(parsed.value),
124
+ preparations,
125
+ )
126
+ except Exception as error:
127
+ return Judgment(
128
+ ErrorEnvelope(
129
+ id=create_id(),
130
+ to=proposal.sender,
131
+ reply_to=proposal.id,
132
+ error=describe_error(error),
133
+ )
134
+ )
135
+
136
+ async def prepare_each(
137
+ self, delegates: Sequence[Delegate], parent: ParentRef
138
+ ) -> list[Preparation]:
139
+ """Sends each delegate a preparation under `parent`, reporting the ones that can't prepare to `on_error`."""
140
+ prepared = await asyncio.gather(
141
+ *(self._prepare_or_report(delegate, parent) for delegate in delegates)
142
+ )
143
+
144
+ return [preparation for preparation in prepared if preparation is not None]
145
+
146
+ async def _construct_verdict(
147
+ self, proposal: ProposeEnvelope, attachments: list[Attachment]
148
+ ) -> tuple[VerdictEnvelope, list[OutgoingTask]]:
149
+ incoming = to_proposal(proposal, attachments)
150
+ verdict = accept() if proposal.prepare else await self._decide(incoming)
151
+
152
+ if not verdict.accepted:
153
+ reason = (
154
+ verdict.reason
155
+ if verdict.reason is not None
156
+ else f"{self._agent.name} declined the task"
157
+ )
158
+
159
+ rejection = RejectEnvelope(
160
+ id=create_id(), to=proposal.sender, reply_to=proposal.id, reason=reason
161
+ )
162
+
163
+ return rejection, []
164
+
165
+ if proposal.prepare:
166
+ warn_revoking(
167
+ self._agent.name,
168
+ proposal,
169
+ self._access.list_skill_sources(proposal.skill),
170
+ )
171
+
172
+ # WARNING: a relay that stamps no principal leaves each requester with its own grants.
173
+ grant = ConnectionGrant(
174
+ requester=proposal.sender,
175
+ id=proposal.id,
176
+ principal=resolve_principal(proposal.principal, proposal.sender),
177
+ )
178
+
179
+ own, prepared = await asyncio.gather(
180
+ self._access.list_actions(proposal.skill, grant),
181
+ self._prepare_delegates(proposal, incoming),
182
+ )
183
+
184
+ copies = [action for preparation in prepared for action in preparation.actions]
185
+ actions = [*own, *copies]
186
+ preparations = [preparation.task for preparation in prepared]
187
+ if actions:
188
+ requirement = RequireEnvelope(
189
+ id=create_id(),
190
+ to=proposal.sender,
191
+ reply_to=proposal.id,
192
+ actions=actions,
193
+ )
194
+
195
+ return requirement, preparations
196
+
197
+ acceptance = AcceptEnvelope(
198
+ id=create_id(), to=proposal.sender, reply_to=proposal.id
199
+ )
200
+
201
+ return acceptance, preparations
202
+
203
+ async def _prepare_delegates(
204
+ self, proposal: ProposeEnvelope, incoming: Proposal
205
+ ) -> list[Preparation]:
206
+ """Asks each agent the proposal's skill delegates to for the actions it needs ahead of the proposal's work."""
207
+ delegates = await self._pick_delegates(proposal, incoming)
208
+ kind: Literal["task", "schedule"] = (
209
+ "schedule" if is_schedule(proposal) else "task"
210
+ )
211
+
212
+ return await self.prepare_each(
213
+ delegates, ParentRef(kind=kind, requester=proposal.sender, id=proposal.id)
214
+ )
215
+
216
+ async def _pick_delegates(
217
+ self, proposal: ProposeEnvelope, incoming: Proposal
218
+ ) -> list[Delegate]:
219
+ """Lists the delegates of the proposal's skill, leaving out picked ones while another agent only prepares it."""
220
+ delegates = (
221
+ None if proposal.skill is None else self._delegates.get(proposal.skill)
222
+ )
223
+
224
+ then = proposal.then
225
+ follow_up = [] if then is None else [Delegate(agent=then.to, skill=then.skill)]
226
+
227
+ if not callable(delegates):
228
+ return [*(delegates or []), *follow_up]
229
+
230
+ if proposal.prepare:
231
+ return []
232
+
233
+ return [*await resolve_value(delegates(incoming, self._agent)), *follow_up]
234
+
235
+ async def _prepare_or_report(
236
+ self, delegate: Delegate, parent: ParentRef
237
+ ) -> Preparation | None:
238
+ try:
239
+ return await self._prepare(delegate, parent)
240
+ except Exception as error:
241
+ self._agent.report_error(error)
242
+
243
+ return None
244
+
245
+ async def _prepare(self, delegate: Delegate, parent: ParentRef) -> Preparation:
246
+ id = create_id()
247
+ origin = ActionOrigin(
248
+ requester=self._agent.name, task_id=id, executor=delegate.agent
249
+ )
250
+ draft = ProposeEnvelope(
251
+ id=id,
252
+ to=delegate.agent,
253
+ text=f'Connect the accounts the "{delegate.skill}" skill needs ahead of the work on {parent.id}',
254
+ skill=delegate.skill,
255
+ prepare=True,
256
+ parent=parent,
257
+ )
258
+
259
+ def adopt(reply: Reply) -> Preparation:
260
+ verdict = assert_accepted(delegate.agent, reply)
261
+ actions = [
262
+ action
263
+ if action.origin
264
+ else action.model_copy(update={"origin": origin})
265
+ for action in list_actions(verdict)
266
+ ]
267
+
268
+ task = self._delegations.track_accepted(verdict, parent)
269
+
270
+ return Preparation(task, actions)
271
+
272
+ return await self._requests.request(draft, adopt)
273
+
274
+ async def _decide(self, proposal: Proposal) -> Verdict:
275
+ verdict = (
276
+ await resolve_value(self._on_proposal(proposal, self._agent))
277
+ if self._on_proposal is not None
278
+ else self._agent.check_proposal(proposal)
279
+ )
280
+
281
+ if (
282
+ not verdict.accepted
283
+ or self._screen is None
284
+ or proposal.sender == self._agent.name
285
+ ):
286
+ return verdict
287
+
288
+ return await screen_proposal(proposal, self._agent, self._screen)
@@ -0,0 +1,122 @@
1
+ from collections.abc import Awaitable, Callable, Sequence
2
+ from dataclasses import dataclass, field
3
+ from typing import TYPE_CHECKING, Any, TypeAlias
4
+
5
+ from typing_extensions import TypedDict
6
+
7
+ from agentjam._attachments import AttachmentSource
8
+ from agentjam._relay.payments import Payments
9
+ from agentjam._screening import ProposalScreen
10
+ from agentjam._tasks.incoming import IncomingTask, TaskOutput
11
+ from agentjam._tasks.outgoing import OutgoingTask
12
+ from agentjam._tools import ToolName
13
+ from agentjam._types import (
14
+ ActionRequest,
15
+ IncomingMessage,
16
+ Proposal,
17
+ SkillHandler,
18
+ TaskOutcome,
19
+ Verdict,
20
+ )
21
+
22
+ if TYPE_CHECKING:
23
+ from agentjam._agent import Agent
24
+
25
+
26
+ @dataclass(frozen=True, kw_only=True)
27
+ class AttachedReply:
28
+ """A reply to a message along with files, which only a message about a task can carry."""
29
+
30
+ text: str
31
+ attachments: Sequence[AttachmentSource] = field(default_factory=list)
32
+
33
+
34
+ ReplyOutput: TypeAlias = str | AttachedReply
35
+ """What `on_message` replies with: its text, or its text along with files."""
36
+
37
+ OnMessage: TypeAlias = Callable[
38
+ [IncomingMessage, "Agent"], Awaitable[ReplyOutput] | ReplyOutput
39
+ ]
40
+
41
+ OnProposal: TypeAlias = Callable[[Proposal, "Agent"], Awaitable[Verdict] | Verdict]
42
+
43
+ OnTask: TypeAlias = Callable[
44
+ [IncomingTask, "Agent"], Awaitable[TaskOutput] | TaskOutput
45
+ ]
46
+
47
+ OnError: TypeAlias = Callable[[Exception], Awaitable[None] | None]
48
+
49
+ OnRun: TypeAlias = Callable[[OutgoingTask, "Agent"], Awaitable[None] | None]
50
+
51
+ OnActionRequired: TypeAlias = Callable[[ActionRequest, "Agent"], Awaitable[None] | None]
52
+
53
+ OnWatchResolved: TypeAlias = Callable[
54
+ [list[TaskOutcome], "Agent"], Awaitable[None] | None
55
+ ]
56
+
57
+
58
+ @dataclass(frozen=True, kw_only=True)
59
+ class ForwardSettings:
60
+ """What an agent passes up from the tasks it delegates while working on a task to that task."""
61
+
62
+ updates: bool = True
63
+ """Re-sends each of their updates as an update of the task, prefixed with the agent that sent it."""
64
+ questions: bool = True
65
+ """Asks the task's requester each question they send, and answers with its reply, ahead of `on_message`."""
66
+ files: bool = True
67
+ """Offers the `forward_artifact` tool, which delivers one of their artifacts as a result of the task."""
68
+
69
+
70
+ class HandlerOptions(TypedDict, total=False):
71
+ """The options adapters fill in, which `AdapterHandlers` and `ConnectOptions` share."""
72
+
73
+ on_message: OnMessage | None
74
+ """Handles a message from another agent. Returns the reply, which goes back to the sender along with any files when the message is about a task."""
75
+ on_proposal: OnProposal | None
76
+ """Handles a task or schedule proposed to this agent. Returns whether to accept it, and by default accepts proposals for the agent's stored skills."""
77
+ on_task: OnTask | None
78
+ """Handles an accepted task. Returns the final task output, which is delivered to the task's proposer."""
79
+ tool_names: Sequence[str]
80
+ """Your agent's own tool names, which `connect()` checks don't clash with the network tools."""
81
+ screen: ProposalScreen | None
82
+ """Screens each proposal `on_proposal` or the default checks accept with a model, before accepting it.
83
+
84
+ Leave it out to accept without one, and turn it on with an adapter's `screen` option or a `judge` calling any model.
85
+ """
86
+
87
+
88
+ class AdapterHandlers(HandlerOptions, total=False, closed=True):
89
+ """What adapters plug into `connect()`.
90
+
91
+ It's closed, so type checkers let it spread into `ConnectOptions` alongside your other options.
92
+ """
93
+
94
+
95
+ class ConnectOptions(HandlerOptions, total=False):
96
+ """How a connected agent handles what happens to it and runs, besides its name and network. Every option is optional."""
97
+
98
+ on_error: OnError | None
99
+ """Handles an error that can't be reported back to another agent, such as a lost connection. Defaults to logging it."""
100
+ on_run: OnRun | None
101
+ """Handles a run of one of this agent's schedules that no `Schedule` in this process follows, such as after a restart. Defaults to logging the run's outcome."""
102
+ on_follow_up: OnRun | None
103
+ """Handles a follow-up the relay proposed after a run of one of this agent's schedules that no `Schedule` in this process follows. Defaults to logging its outcome."""
104
+ on_action_required: OnActionRequired | None
105
+ """Handles a delegated task or schedule that waits for your human to act, such as connecting an account at a link. Defaults to logging a warning."""
106
+ on_watch_resolved: OnWatchResolved | None
107
+ """Handles the outcomes of tasks proposed with `watch`: one task's once it ends, or a whole group's once its last task ends."""
108
+ skills: Sequence[SkillHandler[Any, Any]]
109
+ """The stored skills this process runs triggers and connections for.
110
+
111
+ Each must exist on the relay, along with the triggers and connections it handles. Stored skills left out still take tasks.
112
+ """
113
+ payments: Payments | None
114
+ """Buys AgentJam credits over MPP through `top_up()` and `set_auto_reload()`. Ignored when `network` is set."""
115
+ network_tools: bool | Sequence[ToolName]
116
+ """Gives adapters network tools to merge into your agent's own: all of them, none, or the ones named. Defaults to True."""
117
+ timeout: float
118
+ """How many seconds to wait for a response to `send()`, `propose()` or `schedule()`, except for questions to a running task's requester, which wait until the task ends. Defaults to 30."""
119
+ instance_id: str | None
120
+ """Names this process among the agent's sessions, so a second process with the same instance waits for the first to end instead of running alongside it."""
121
+ forward: ForwardSettings
122
+ """What passes up from the tasks this agent delegates while working on a task to that task. Every kind defaults to True."""
@@ -0,0 +1,214 @@
1
+ import asyncio
2
+ import contextlib
3
+ from collections.abc import Awaitable, Callable
4
+ from typing import assert_never
5
+
6
+ from agentjam._agent_access import AccessBroker
7
+ from agentjam._agent_delegations import Delegations
8
+ from agentjam._agent_executions import Executions
9
+ from agentjam._agent_options import ForwardSettings
10
+ from agentjam._agent_support import construct_trigger_schedule
11
+ from agentjam._connections import ConnectionGrant, ConnectionHolder, ConnectionReady
12
+ from agentjam._errors import AgentNotFoundError, ReassignedError, TriggerFailedError
13
+ from agentjam._protocol import (
14
+ AcceptEnvelope,
15
+ ActionsEnvelope,
16
+ ArtifactEnvelope,
17
+ BudgetEnvelope,
18
+ CancelEnvelope,
19
+ CollectDraft,
20
+ CommitEnvelope,
21
+ CompleteEnvelope,
22
+ ConnectionReadyEnvelope,
23
+ ConnectionRequiredEnvelope,
24
+ ConnectionRevokedEnvelope,
25
+ ConnectionStoredEnvelope,
26
+ DeliveredEnvelope,
27
+ DisconnectEnvelope,
28
+ ErrorEnvelope,
29
+ FailEnvelope,
30
+ FollowUpEnvelope,
31
+ MessageEnvelope,
32
+ ProposeEnvelope,
33
+ RecurEnvelope,
34
+ RejectEnvelope,
35
+ ReplyEnvelope,
36
+ RequireEnvelope,
37
+ ScheduleEndEnvelope,
38
+ ScheduleHandoverEnvelope,
39
+ ScheduleStartEnvelope,
40
+ TaskEnvelope,
41
+ TriggerFailedEnvelope,
42
+ TriggerStoppedDraft,
43
+ UpdateEnvelope,
44
+ )
45
+ from agentjam._relay.base import Draft
46
+ from agentjam._requests import Requester
47
+ from agentjam._tasks.triggers import TriggerRunner
48
+ from agentjam._utils import create_id
49
+
50
+
51
+ class EnvelopeRouter:
52
+ """Hands each envelope the relay delivers to the part of the agent it concerns."""
53
+
54
+ def __init__(
55
+ self,
56
+ name: str,
57
+ *,
58
+ post: Callable[[Draft], Awaitable[None]],
59
+ requests: Requester,
60
+ delegations: Delegations,
61
+ executions: Executions,
62
+ triggers: TriggerRunner,
63
+ access: AccessBroker,
64
+ forward: ForwardSettings,
65
+ on_error: Callable[[Exception], None],
66
+ ) -> None:
67
+ self._name = name
68
+ self._post = post
69
+ self._requests = requests
70
+ self._delegations = delegations
71
+ self._executions = executions
72
+ self._triggers = triggers
73
+ self._access = access
74
+ self._forward = forward
75
+ self._on_error = on_error
76
+
77
+ async def route(self, envelope: DeliveredEnvelope) -> None:
78
+ match envelope:
79
+ case MessageEnvelope():
80
+ await self._executions.reply(envelope)
81
+
82
+ case ReplyEnvelope():
83
+ self._requests.settle(envelope)
84
+
85
+ case ErrorEnvelope() | RejectEnvelope():
86
+ if not self._requests.settle(envelope):
87
+ self._delegations.refuse(envelope)
88
+
89
+ case AcceptEnvelope() | RequireEnvelope():
90
+ if not self._requests.settle(envelope):
91
+ await self._delegations.restart(envelope)
92
+
93
+ case ProposeEnvelope() if envelope.resumed:
94
+ await self._executions.resume(envelope)
95
+
96
+ case ProposeEnvelope():
97
+ with contextlib.suppress(ReassignedError):
98
+ await self._executions.consider(envelope)
99
+
100
+ case (
101
+ UpdateEnvelope()
102
+ | ArtifactEnvelope()
103
+ | CommitEnvelope()
104
+ | CompleteEnvelope()
105
+ | FailEnvelope()
106
+ ):
107
+ await self._progress(envelope)
108
+
109
+ case CancelEnvelope():
110
+ task = self._executions.find(envelope.sender, envelope.task_id)
111
+ if task is not None:
112
+ task.cancel(envelope.reason, envelope.code)
113
+
114
+ case BudgetEnvelope():
115
+ task = self._executions.find(envelope.sender, envelope.task_id)
116
+ if task is not None:
117
+ task.set_held_cents(envelope.held_cents)
118
+
119
+ case ActionsEnvelope():
120
+ self._delegations.inherit(envelope)
121
+
122
+ case DisconnectEnvelope():
123
+ self._abandon(envelope.sender, envelope.abandoned)
124
+
125
+ case ScheduleEndEnvelope():
126
+ await self._close_schedule(envelope)
127
+
128
+ case ScheduleStartEnvelope():
129
+ self._triggers.activate(construct_trigger_schedule(envelope))
130
+
131
+ case ScheduleHandoverEnvelope():
132
+ await self._triggers.stop(
133
+ envelope.sender, envelope.schedule_id, "handover"
134
+ )
135
+
136
+ case TriggerFailedEnvelope():
137
+ self._on_error(
138
+ TriggerFailedError(
139
+ envelope.sender,
140
+ envelope.schedule_id,
141
+ envelope.event_id,
142
+ envelope.error,
143
+ )
144
+ )
145
+
146
+ case RecurEnvelope() if envelope.sender != self._name:
147
+ await self._executions.perform(envelope)
148
+
149
+ case RecurEnvelope():
150
+ self._delegations.notice(envelope.to, envelope)
151
+
152
+ case FollowUpEnvelope():
153
+ self._delegations.follow_up(envelope)
154
+
155
+ case ConnectionReadyEnvelope():
156
+ self._delegations.complete(envelope)
157
+
158
+ case ConnectionRequiredEnvelope():
159
+ self._delegations.require_access(envelope)
160
+
161
+ case ConnectionStoredEnvelope():
162
+ grant = ConnectionGrant(
163
+ requester=envelope.sender,
164
+ id=envelope.proposal_id,
165
+ principal=envelope.principal,
166
+ )
167
+
168
+ await self._access.announce(
169
+ ConnectionReady(provider=envelope.provider, grant=grant)
170
+ )
171
+
172
+ case ConnectionRevokedEnvelope():
173
+ pass
174
+
175
+ case _:
176
+ assert_never(envelope)
177
+
178
+ async def _progress(self, envelope: TaskEnvelope) -> None:
179
+ task = await self._delegations.progress(envelope)
180
+ if not isinstance(envelope, UpdateEnvelope) or not self._forward.updates:
181
+ return
182
+
183
+ if (above := self._executions.find_above(task)) is not None:
184
+ await above.update(f"{envelope.sender}: {envelope.text}")
185
+
186
+ def _abandon(self, peer: str, abandoned: list[str] | None) -> None:
187
+ ids = None if abandoned is None else set(abandoned)
188
+ self._requests.fail_to(peer, AgentNotFoundError(peer), ids)
189
+ self._delegations.abandon(peer, ids)
190
+ self._executions.abandon(peer, ids)
191
+
192
+ async def _close_schedule(self, envelope: ScheduleEndEnvelope) -> None:
193
+ self._delegations.close_schedule(envelope)
194
+ collect = CollectDraft(
195
+ id=create_id(), to=envelope.sender, schedule_id=envelope.schedule_id
196
+ )
197
+
198
+ await asyncio.gather(
199
+ self._stop_schedule(envelope.sender, envelope.schedule_id),
200
+ self._post(collect),
201
+ )
202
+
203
+ async def _stop_schedule(self, requester: str, schedule_id: str) -> None:
204
+ """Stops the ended schedule's trigger, telling the relay so its connections close, then releases them."""
205
+ try:
206
+ if await self._triggers.stop(requester, schedule_id, "ended"):
207
+ await self._post(
208
+ TriggerStoppedDraft(
209
+ id=create_id(), to=requester, schedule_id=schedule_id
210
+ )
211
+ )
212
+ finally:
213
+ holder = ConnectionHolder(requester=requester, id=schedule_id)
214
+ self._access.release(holder, self._access.list_sources())