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.
- agentjam/__init__.py +435 -0
- agentjam/_adapters/__init__.py +0 -0
- agentjam/_adapters/responses.py +73 -0
- agentjam/_adapters/shared.py +435 -0
- agentjam/_agent.py +1032 -0
- agentjam/_agent_access.py +360 -0
- agentjam/_agent_delegations.py +376 -0
- agentjam/_agent_executions.py +566 -0
- agentjam/_agent_judging.py +288 -0
- agentjam/_agent_options.py +122 -0
- agentjam/_agent_routing.py +214 -0
- agentjam/_agent_session.py +195 -0
- agentjam/_agent_support.py +415 -0
- agentjam/_artifacts.py +565 -0
- agentjam/_attachments.py +112 -0
- agentjam/_connections.py +1282 -0
- agentjam/_content.py +29 -0
- agentjam/_cron.py +302 -0
- agentjam/_errors.py +238 -0
- agentjam/_events.py +113 -0
- agentjam/_files.py +55 -0
- agentjam/_github.py +742 -0
- agentjam/_idempotency.py +68 -0
- agentjam/_inputs.py +79 -0
- agentjam/_models.py +21 -0
- agentjam/_polling.py +139 -0
- agentjam/_profile.py +244 -0
- agentjam/_protocol.py +480 -0
- agentjam/_providers.py +365 -0
- agentjam/_recaps.py +67 -0
- agentjam/_relay/__init__.py +0 -0
- agentjam/_relay/actions.py +234 -0
- agentjam/_relay/artifacts.py +96 -0
- agentjam/_relay/base.py +387 -0
- agentjam/_relay/commits.py +77 -0
- agentjam/_relay/copies.py +66 -0
- agentjam/_relay/credentials.py +127 -0
- agentjam/_relay/endpoints.py +39 -0
- agentjam/_relay/follow_ups.py +548 -0
- agentjam/_relay/frames.py +443 -0
- agentjam/_relay/guest_store.py +114 -0
- agentjam/_relay/guests.py +55 -0
- agentjam/_relay/inputs.py +119 -0
- agentjam/_relay/lineage.py +294 -0
- agentjam/_relay/memory.py +1045 -0
- agentjam/_relay/payments.py +204 -0
- agentjam/_relay/profiles.py +95 -0
- agentjam/_relay/remote.py +826 -0
- agentjam/_relay/resumptions.py +65 -0
- agentjam/_relay/revisions.py +43 -0
- agentjam/_relay/schedule_follow_ups.py +274 -0
- agentjam/_relay/schedules.py +547 -0
- agentjam/_relay/secrets.py +275 -0
- agentjam/_relay/sessions.py +640 -0
- agentjam/_relay/uploads.py +71 -0
- agentjam/_requests.py +178 -0
- agentjam/_screening.py +368 -0
- agentjam/_secrets.py +153 -0
- agentjam/_sentry.py +233 -0
- agentjam/_signals.py +98 -0
- agentjam/_slack.py +468 -0
- agentjam/_stripe.py +93 -0
- agentjam/_tasks/__init__.py +0 -0
- agentjam/_tasks/access.py +142 -0
- agentjam/_tasks/incoming.py +952 -0
- agentjam/_tasks/outgoing.py +472 -0
- agentjam/_tasks/scheduled.py +206 -0
- agentjam/_tasks/serial.py +40 -0
- agentjam/_tasks/triggers.py +258 -0
- agentjam/_tasks/watches.py +77 -0
- agentjam/_tools.py +1035 -0
- agentjam/_types.py +965 -0
- agentjam/_utils.py +75 -0
- agentjam/_verdicts.py +21 -0
- agentjam/_watermarks.py +59 -0
- agentjam/anthropic.py +442 -0
- agentjam/mpp.py +233 -0
- agentjam/openai.py +141 -0
- agentjam/openai_agents.py +253 -0
- agentjam/py.typed +0 -0
- agentjam/pydantic_ai.py +301 -0
- agentjam/skills.py +69 -0
- agentjam-0.1.0.dist-info/METADATA +210 -0
- agentjam-0.1.0.dist-info/RECORD +86 -0
- agentjam-0.1.0.dist-info/WHEEL +4 -0
- agentjam-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1045 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import base64
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any, assert_never
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from agentjam._errors import (
|
|
10
|
+
AgentExistsError,
|
|
11
|
+
AgentJamError,
|
|
12
|
+
AgentNotFoundError,
|
|
13
|
+
InvalidInputError,
|
|
14
|
+
describe_error,
|
|
15
|
+
)
|
|
16
|
+
from agentjam._files import File
|
|
17
|
+
from agentjam._protocol import (
|
|
18
|
+
AcceptEnvelope,
|
|
19
|
+
ActionsEnvelope,
|
|
20
|
+
ArtifactEnvelope,
|
|
21
|
+
AttachmentRef,
|
|
22
|
+
BudgetEnvelope,
|
|
23
|
+
CancelEnvelope,
|
|
24
|
+
CollectDraft,
|
|
25
|
+
CommitEnvelope,
|
|
26
|
+
CompleteEnvelope,
|
|
27
|
+
ConnectionReadyEnvelope,
|
|
28
|
+
ConnectionRequiredEnvelope,
|
|
29
|
+
ConnectionRevokedEnvelope,
|
|
30
|
+
ConnectionStoredEnvelope,
|
|
31
|
+
CostDraft,
|
|
32
|
+
DelegatedTask,
|
|
33
|
+
DeliveredEnvelope,
|
|
34
|
+
DisconnectEnvelope,
|
|
35
|
+
DispatchDraft,
|
|
36
|
+
DrainDraft,
|
|
37
|
+
ErrorEnvelope,
|
|
38
|
+
FailEnvelope,
|
|
39
|
+
FollowUpEnvelope,
|
|
40
|
+
MessageEnvelope,
|
|
41
|
+
ParentRef,
|
|
42
|
+
ProposeEnvelope,
|
|
43
|
+
ReattachDraft,
|
|
44
|
+
RecurEnvelope,
|
|
45
|
+
RejectEnvelope,
|
|
46
|
+
ReplyEnvelope,
|
|
47
|
+
RequireEnvelope,
|
|
48
|
+
ScheduleEndEnvelope,
|
|
49
|
+
ScheduleHandoverEnvelope,
|
|
50
|
+
ScheduleStartEnvelope,
|
|
51
|
+
TaskEndCode,
|
|
52
|
+
TaskRecapRef,
|
|
53
|
+
TaskRef,
|
|
54
|
+
TriggerFailedEnvelope,
|
|
55
|
+
TriggerFireDraft,
|
|
56
|
+
TriggerStoppedDraft,
|
|
57
|
+
TriggerSubscribeDraft,
|
|
58
|
+
UpdateEnvelope,
|
|
59
|
+
parse_envelope,
|
|
60
|
+
)
|
|
61
|
+
from agentjam._relay.actions import ActionLedger
|
|
62
|
+
from agentjam._relay.artifacts import ArtifactLedger, FinishedArtifact
|
|
63
|
+
from agentjam._relay.base import (
|
|
64
|
+
Draft,
|
|
65
|
+
Receiver,
|
|
66
|
+
SecretGrant,
|
|
67
|
+
SessionEvents,
|
|
68
|
+
SessionOptions,
|
|
69
|
+
)
|
|
70
|
+
from agentjam._relay.commits import CommitLedger
|
|
71
|
+
from agentjam._relay.copies import CopyLedger
|
|
72
|
+
from agentjam._relay.follow_ups import FollowUpLedger
|
|
73
|
+
from agentjam._relay.inputs import input_problem, output_problem
|
|
74
|
+
from agentjam._relay.lineage import LineageLedger
|
|
75
|
+
from agentjam._relay.resumptions import ResumptionLedger
|
|
76
|
+
from agentjam._relay.revisions import RevisionLedger
|
|
77
|
+
from agentjam._relay.schedule_follow_ups import (
|
|
78
|
+
FOLLOW_UP_SUFFIX,
|
|
79
|
+
FollowedRun,
|
|
80
|
+
FollowUpJudge,
|
|
81
|
+
construct_check,
|
|
82
|
+
construct_notice,
|
|
83
|
+
find_target_skill,
|
|
84
|
+
follow_up_problem,
|
|
85
|
+
is_matching,
|
|
86
|
+
refuse_judgment,
|
|
87
|
+
)
|
|
88
|
+
from agentjam._relay.schedules import ClosedSchedule, ScheduleBook
|
|
89
|
+
from agentjam._relay.secrets import SecretLedger, SecretStub
|
|
90
|
+
from agentjam._relay.sessions import (
|
|
91
|
+
Member,
|
|
92
|
+
SessionBook,
|
|
93
|
+
WorkKey,
|
|
94
|
+
conversation_key,
|
|
95
|
+
request_key,
|
|
96
|
+
)
|
|
97
|
+
from agentjam._relay.uploads import DEFAULT_MIME_TYPE
|
|
98
|
+
from agentjam._signals import Signal
|
|
99
|
+
from agentjam._types import (
|
|
100
|
+
ActionOrigin,
|
|
101
|
+
AgentCard,
|
|
102
|
+
AgentQuery,
|
|
103
|
+
HistoryPage,
|
|
104
|
+
HistoryQuery,
|
|
105
|
+
JsonObject,
|
|
106
|
+
Message,
|
|
107
|
+
ProfileUpdate,
|
|
108
|
+
SkillCard,
|
|
109
|
+
StoredAgent,
|
|
110
|
+
)
|
|
111
|
+
from agentjam._utils import create_id, logger, resolve_value, spawn
|
|
112
|
+
|
|
113
|
+
CONNECTION_REVOKED = "The executor lost access to an account the task connects to"
|
|
114
|
+
|
|
115
|
+
PARENT_ENDED = "The task it was part of ended"
|
|
116
|
+
|
|
117
|
+
DEFAULT_HOLD = 10 * 60.0
|
|
118
|
+
|
|
119
|
+
STOP_GRACE = 60.0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass(frozen=True)
|
|
123
|
+
class StoppingSchedule:
|
|
124
|
+
executor: str
|
|
125
|
+
timer: asyncio.TimerHandle
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass(frozen=True)
|
|
129
|
+
class FollowedCompletion:
|
|
130
|
+
run: FollowedRun
|
|
131
|
+
artifacts: list[FinishedArtifact]
|
|
132
|
+
output: JsonObject | None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def copy_card(card: AgentCard) -> AgentCard:
|
|
136
|
+
return card.model_copy(deep=True)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def is_matching_card(card: AgentCard, query: AgentQuery) -> bool:
|
|
140
|
+
words = [card.name, card.description]
|
|
141
|
+
for skill in card.skills:
|
|
142
|
+
words += [skill.name, skill.description]
|
|
143
|
+
|
|
144
|
+
text = " ".join(words).lower()
|
|
145
|
+
is_skilled = not query.skill or any(
|
|
146
|
+
skill.name == query.skill for skill in card.skills
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
return is_skilled and (not query.query or query.query.lower() in text)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def construct_missing(name: str) -> AgentJamError:
|
|
153
|
+
return AgentJamError(f'No agent named "{name}" exists. Create it with create()')
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
async def hand_envelope(recipient: Member, envelope: DeliveredEnvelope) -> None:
|
|
157
|
+
try:
|
|
158
|
+
await recipient.receive(envelope)
|
|
159
|
+
except Exception:
|
|
160
|
+
logger.exception(
|
|
161
|
+
'"%s" failed to handle a %s envelope', recipient.name, envelope.type
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class MemoryRelay:
|
|
166
|
+
"""An in-process relay for tests and local setups whose agents all trust each other.
|
|
167
|
+
|
|
168
|
+
Envelopes are delivered asynchronously and round-tripped through JSON while their recipient is connected, and
|
|
169
|
+
nothing is kept for an agent that isn't. An agent may connect many sessions, and each piece of work stays with
|
|
170
|
+
the session it went to, so a task whose requester's session left keeps running unheard. A task of a resumable
|
|
171
|
+
skill moves to another session of its executor once its own leaves, or waits `hold` seconds for the next one to
|
|
172
|
+
connect. A draining session gets no new work while a sibling can take it.
|
|
173
|
+
|
|
174
|
+
Every task runs for free, schedules end once either agent has no session left, there are no reviews or task
|
|
175
|
+
lists, and every agent is public. Uploads stay in memory and reach their recipients as data URLs, and secret
|
|
176
|
+
connections reach the stubs in `secrets`. A schedule's follow-up `condition` is answered by `judge_follow_up`,
|
|
177
|
+
which fails every check by default.
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
def __init__(
|
|
181
|
+
self,
|
|
182
|
+
*,
|
|
183
|
+
judge_follow_up: FollowUpJudge | None = None,
|
|
184
|
+
hold: float = DEFAULT_HOLD,
|
|
185
|
+
secrets: Mapping[str, SecretStub] | None = None,
|
|
186
|
+
) -> None:
|
|
187
|
+
"""Creates an empty relay.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
judge_follow_up: Answers whether a completed run meets its schedule's follow-up `condition`, in place of
|
|
191
|
+
the AgentJam network's model. By default every condition fails to check, so its follow-up is
|
|
192
|
+
reported as a `FollowUpFailedError`.
|
|
193
|
+
hold: How long a resumable task whose executor's last session left waits for its next one, in seconds.
|
|
194
|
+
secrets: Stand-ins for the credentials of secret connections, by provider, which tasks reach through
|
|
195
|
+
`connection_fetch()`.
|
|
196
|
+
"""
|
|
197
|
+
self._judge_follow_up = (
|
|
198
|
+
refuse_judgment if judge_follow_up is None else judge_follow_up
|
|
199
|
+
)
|
|
200
|
+
self._hold = hold
|
|
201
|
+
self._secrets = SecretLedger({} if secrets is None else secrets)
|
|
202
|
+
self._profiles: dict[str, AgentCard] = {}
|
|
203
|
+
self._sessions = SessionBook()
|
|
204
|
+
self._conversations: dict[str, list[Message]] = {}
|
|
205
|
+
self._unanswered: dict[str, Message] = {}
|
|
206
|
+
self._actions = ActionLedger()
|
|
207
|
+
self._copies = CopyLedger()
|
|
208
|
+
self._commits = CommitLedger()
|
|
209
|
+
self._revisions = RevisionLedger()
|
|
210
|
+
self._lineage = LineageLedger()
|
|
211
|
+
self._follow_ups = FollowUpLedger()
|
|
212
|
+
self._resumptions = ResumptionLedger()
|
|
213
|
+
self._uploads: dict[str, AttachmentRef] = {}
|
|
214
|
+
self._artifacts = ArtifactLedger()
|
|
215
|
+
self._book = ScheduleBook(self._deliver_scheduled, self._close_schedule)
|
|
216
|
+
self._holds: dict[str, asyncio.TimerHandle] = {}
|
|
217
|
+
self._stopping: dict[str, StoppingSchedule] = {}
|
|
218
|
+
|
|
219
|
+
def enter_credential(self, url: str) -> None:
|
|
220
|
+
"""Acts as the requester's human entering a credential in the form at a `credential_form` action's link.
|
|
221
|
+
|
|
222
|
+
This tells the executor it's stored, so the task or schedule waiting on it starts.
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
url: The link of the action.
|
|
226
|
+
Raises:
|
|
227
|
+
AgentJamError: If no form is open at `url`.
|
|
228
|
+
"""
|
|
229
|
+
stored = self._secrets.enter(url)
|
|
230
|
+
self._deliver_to(stored, stored.to)
|
|
231
|
+
|
|
232
|
+
async def create(self, name: str, profile: ProfileUpdate) -> StoredAgent:
|
|
233
|
+
"""Stores a new agent, filling in the fields `profile` leaves out with an empty profile.
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
name: The agent's name.
|
|
237
|
+
profile: The agent's profile.
|
|
238
|
+
Returns:
|
|
239
|
+
The stored agent.
|
|
240
|
+
Raises:
|
|
241
|
+
AgentExistsError: If an agent with that name already exists.
|
|
242
|
+
"""
|
|
243
|
+
if name in self._profiles:
|
|
244
|
+
raise AgentExistsError(f'An agent named "{name}" already exists')
|
|
245
|
+
|
|
246
|
+
card = AgentCard(
|
|
247
|
+
name=name,
|
|
248
|
+
description="" if profile.description is None else profile.description,
|
|
249
|
+
skills=[] if profile.skills is None else profile.skills,
|
|
250
|
+
)
|
|
251
|
+
self._profiles[name] = copy_card(card)
|
|
252
|
+
|
|
253
|
+
return StoredAgent(card=copy_card(card))
|
|
254
|
+
|
|
255
|
+
async def update(self, name: str, profile: ProfileUpdate) -> StoredAgent:
|
|
256
|
+
"""Changes only the fields of the agent's stored profile that `profile` sets.
|
|
257
|
+
|
|
258
|
+
Args:
|
|
259
|
+
name: The agent's name.
|
|
260
|
+
profile: The fields to change.
|
|
261
|
+
Returns:
|
|
262
|
+
The stored agent.
|
|
263
|
+
Raises:
|
|
264
|
+
AgentJamError: If no agent with that name exists.
|
|
265
|
+
"""
|
|
266
|
+
card = self._get_profile(name)
|
|
267
|
+
updated = AgentCard(
|
|
268
|
+
name=name,
|
|
269
|
+
description=card.description
|
|
270
|
+
if profile.description is None
|
|
271
|
+
else profile.description,
|
|
272
|
+
skills=card.skills if profile.skills is None else profile.skills,
|
|
273
|
+
)
|
|
274
|
+
self._profiles[name] = copy_card(updated)
|
|
275
|
+
|
|
276
|
+
return StoredAgent(card=copy_card(updated))
|
|
277
|
+
|
|
278
|
+
async def connect(
|
|
279
|
+
self,
|
|
280
|
+
name: str,
|
|
281
|
+
receive: Receiver,
|
|
282
|
+
events: SessionEvents | None = None,
|
|
283
|
+
options: SessionOptions | None = None,
|
|
284
|
+
) -> "MemoryConnection":
|
|
285
|
+
"""Connects an agent the relay stores and starts delivering its envelopes to `receive`.
|
|
286
|
+
|
|
287
|
+
Args:
|
|
288
|
+
name: The agent's name.
|
|
289
|
+
receive: Handles each delivered envelope.
|
|
290
|
+
events: Ignored, since a `MemoryRelay` never loses a session.
|
|
291
|
+
options: Names the instance the session runs as.
|
|
292
|
+
Returns:
|
|
293
|
+
The live connection.
|
|
294
|
+
Raises:
|
|
295
|
+
AgentJamError: If no agent with that name exists, or another connection holds the instance.
|
|
296
|
+
"""
|
|
297
|
+
if name not in self._profiles:
|
|
298
|
+
raise construct_missing(name)
|
|
299
|
+
|
|
300
|
+
member = Member(name, None if options is None else options.instance_id, receive)
|
|
301
|
+
for task in self._sessions.join(member):
|
|
302
|
+
self._redeliver(task)
|
|
303
|
+
|
|
304
|
+
return MemoryConnection(self, member)
|
|
305
|
+
|
|
306
|
+
def _assert_open(self, member: Member) -> None:
|
|
307
|
+
if not self._sessions.is_live(member):
|
|
308
|
+
raise AgentJamError(f'The connection for "{member.name}" is closed')
|
|
309
|
+
|
|
310
|
+
def _send(self, member: Member, envelope: Draft) -> None:
|
|
311
|
+
self._assert_open(member)
|
|
312
|
+
stamped = envelope.model_copy(update={"sender": member.name})
|
|
313
|
+
self._route(self._link_uploads(stamped), member)
|
|
314
|
+
|
|
315
|
+
def _close(self, member: Member) -> None:
|
|
316
|
+
if self._sessions.is_live(member):
|
|
317
|
+
self._leave(member)
|
|
318
|
+
|
|
319
|
+
def _store_upload(self, agent: str, file: File) -> str:
|
|
320
|
+
upload_id = create_id()
|
|
321
|
+
mime_type = file.mime_type or DEFAULT_MIME_TYPE
|
|
322
|
+
encoded = base64.b64encode(file.data).decode()
|
|
323
|
+
self._uploads[request_key(agent, upload_id)] = AttachmentRef(
|
|
324
|
+
attachment_id=upload_id,
|
|
325
|
+
name=file.name,
|
|
326
|
+
mime_type=mime_type,
|
|
327
|
+
size=file.size,
|
|
328
|
+
url=f"data:{mime_type};base64,{encoded}",
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
return upload_id
|
|
332
|
+
|
|
333
|
+
def _link_uploads(self, envelope: Draft) -> Draft:
|
|
334
|
+
"""Links the uploads a proposal, message or reply attaches or a file artifact names, each as a data URL."""
|
|
335
|
+
match envelope:
|
|
336
|
+
case ArtifactEnvelope(upload_id=str(upload_id)) if upload_id:
|
|
337
|
+
upload = self._find_upload(envelope.sender, upload_id)
|
|
338
|
+
|
|
339
|
+
return envelope.model_copy(update={"url": upload.url})
|
|
340
|
+
|
|
341
|
+
case ProposeEnvelope() | MessageEnvelope() | ReplyEnvelope() if (
|
|
342
|
+
envelope.attachments is not None
|
|
343
|
+
):
|
|
344
|
+
attachments = [
|
|
345
|
+
self._find_upload(envelope.sender, attachment.attachment_id)
|
|
346
|
+
for attachment in envelope.attachments
|
|
347
|
+
]
|
|
348
|
+
|
|
349
|
+
return envelope.model_copy(update={"attachments": attachments})
|
|
350
|
+
|
|
351
|
+
case _:
|
|
352
|
+
return envelope
|
|
353
|
+
|
|
354
|
+
def _find_upload(self, agent: str, upload_id: str) -> AttachmentRef:
|
|
355
|
+
upload = self._uploads.get(request_key(agent, upload_id))
|
|
356
|
+
if upload is None:
|
|
357
|
+
raise AgentJamError(f"No upload {upload_id} by {agent}")
|
|
358
|
+
|
|
359
|
+
return upload
|
|
360
|
+
|
|
361
|
+
def _get_profile(self, name: str) -> AgentCard:
|
|
362
|
+
card = self._profiles.get(name)
|
|
363
|
+
if card is None:
|
|
364
|
+
raise construct_missing(name)
|
|
365
|
+
|
|
366
|
+
return card
|
|
367
|
+
|
|
368
|
+
def _find_cards(self, query: AgentQuery) -> list[AgentCard]:
|
|
369
|
+
cards = (self._get_profile(name) for name in self._sessions.list_names())
|
|
370
|
+
|
|
371
|
+
return [copy_card(card) for card in cards if is_matching_card(card, query)]
|
|
372
|
+
|
|
373
|
+
def _leave(self, member: Member) -> None:
|
|
374
|
+
departure = self._sessions.leave(
|
|
375
|
+
member, lambda work: self._is_resumable(work.requester, work.id)
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
self._hand_over(departure.runs, departure.watches)
|
|
379
|
+
for task in departure.resumed:
|
|
380
|
+
self._redeliver(task)
|
|
381
|
+
|
|
382
|
+
for task in departure.held:
|
|
383
|
+
self._hold_task(task)
|
|
384
|
+
|
|
385
|
+
if not self._sessions.is_connected(member.name):
|
|
386
|
+
self._book.leave(member.name)
|
|
387
|
+
self._actions.leave(member.name)
|
|
388
|
+
|
|
389
|
+
for peer, abandoned in departure.abandoned.items():
|
|
390
|
+
notice = DisconnectEnvelope(
|
|
391
|
+
id=create_id(), sender=member.name, to=peer.name, abandoned=abandoned
|
|
392
|
+
)
|
|
393
|
+
self._deliver(notice, peer)
|
|
394
|
+
|
|
395
|
+
def _hand_over(self, runs: list[WorkKey], watches: list[WorkKey]) -> None:
|
|
396
|
+
for run in runs:
|
|
397
|
+
self._book.rerun(run.requester, run.id)
|
|
398
|
+
|
|
399
|
+
for watch in watches:
|
|
400
|
+
self._book.rewatch(watch.requester, watch.id)
|
|
401
|
+
|
|
402
|
+
def _is_resumable(self, requester: str, id: str) -> bool:
|
|
403
|
+
committed = self._commits.is_committed_irreversibly(requester, id)
|
|
404
|
+
|
|
405
|
+
return self._resumptions.is_resumable(requester, id) and not committed
|
|
406
|
+
|
|
407
|
+
def _redeliver(self, task: WorkKey) -> None:
|
|
408
|
+
"""Redelivers a task to the session of its executor that took it over, along with the open tasks it delegated."""
|
|
409
|
+
heir = self._sessions.get_executor(task)
|
|
410
|
+
if heir is None:
|
|
411
|
+
return
|
|
412
|
+
|
|
413
|
+
self._clear_hold(task)
|
|
414
|
+
children = self._lineage.list_children(task.requester, task.id)
|
|
415
|
+
delegated = [
|
|
416
|
+
DelegatedTask(to=child.executor, id=child.task_id) for child in children
|
|
417
|
+
]
|
|
418
|
+
proposal = self._resumptions.resume(task.requester, task.id, delegated)
|
|
419
|
+
if proposal is None:
|
|
420
|
+
return
|
|
421
|
+
|
|
422
|
+
for child in children:
|
|
423
|
+
self._sessions.rebind_requester(
|
|
424
|
+
WorkKey(child.requester, child.task_id), heir
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
self._deliver(proposal, heir)
|
|
428
|
+
|
|
429
|
+
def _hold_task(self, task: WorkKey) -> None:
|
|
430
|
+
loop = asyncio.get_running_loop()
|
|
431
|
+
timer = loop.call_later(self._hold, self._abandon_held, task)
|
|
432
|
+
self._holds[request_key(task.requester, task.id)] = timer
|
|
433
|
+
|
|
434
|
+
def _clear_hold(self, task: WorkKey) -> None:
|
|
435
|
+
if timer := self._holds.pop(request_key(task.requester, task.id), None):
|
|
436
|
+
timer.cancel()
|
|
437
|
+
|
|
438
|
+
def _close_schedule(self, schedule: ClosedSchedule) -> None:
|
|
439
|
+
"""Ends an ended schedule's grants, once its watcher's stop finishes or runs out of time when a session watched it."""
|
|
440
|
+
if not schedule.watched:
|
|
441
|
+
self._secrets.end(schedule.requester, schedule.id)
|
|
442
|
+
return
|
|
443
|
+
|
|
444
|
+
loop = asyncio.get_running_loop()
|
|
445
|
+
timer = loop.call_later(
|
|
446
|
+
STOP_GRACE, self._finish_stop, schedule.requester, schedule.id
|
|
447
|
+
)
|
|
448
|
+
self._stopping[request_key(schedule.requester, schedule.id)] = StoppingSchedule(
|
|
449
|
+
schedule.executor, timer
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
def _finish_stop(self, requester: str, id: str) -> None:
|
|
453
|
+
if stopping := self._stopping.pop(request_key(requester, id), None):
|
|
454
|
+
stopping.timer.cancel()
|
|
455
|
+
|
|
456
|
+
self._secrets.end(requester, id)
|
|
457
|
+
|
|
458
|
+
def _abandon_held(self, task: WorkKey) -> None:
|
|
459
|
+
"""Ends a task no session of its executor adopted in time, telling its requester's session if it's still live."""
|
|
460
|
+
executor = self._sessions.get_executor(task)
|
|
461
|
+
session = self._sessions.release_held(task)
|
|
462
|
+
if executor is None or session is None:
|
|
463
|
+
return
|
|
464
|
+
|
|
465
|
+
self._clear_hold(task)
|
|
466
|
+
self._end_work(task.requester, task.id)
|
|
467
|
+
if not self._sessions.is_live(session):
|
|
468
|
+
return
|
|
469
|
+
|
|
470
|
+
notice = DisconnectEnvelope(
|
|
471
|
+
id=create_id(), sender=executor.name, to=task.requester, abandoned=[task.id]
|
|
472
|
+
)
|
|
473
|
+
self._deliver(notice, session)
|
|
474
|
+
|
|
475
|
+
def _route(self, envelope: Draft, sender: Member) -> None:
|
|
476
|
+
match envelope:
|
|
477
|
+
case CollectDraft() | ReattachDraft() | CostDraft():
|
|
478
|
+
return
|
|
479
|
+
|
|
480
|
+
case DrainDraft():
|
|
481
|
+
self._drain(sender)
|
|
482
|
+
|
|
483
|
+
case TriggerStoppedDraft():
|
|
484
|
+
stopping = self._stopping.get(
|
|
485
|
+
request_key(envelope.to, envelope.schedule_id)
|
|
486
|
+
)
|
|
487
|
+
if stopping is not None and stopping.executor == envelope.sender:
|
|
488
|
+
self._finish_stop(envelope.to, envelope.schedule_id)
|
|
489
|
+
|
|
490
|
+
case TriggerFireDraft():
|
|
491
|
+
self._book.trigger(envelope)
|
|
492
|
+
|
|
493
|
+
case TriggerSubscribeDraft():
|
|
494
|
+
self._book.subscribe(envelope)
|
|
495
|
+
|
|
496
|
+
case DispatchDraft():
|
|
497
|
+
self._book.dispatch(envelope)
|
|
498
|
+
|
|
499
|
+
case _:
|
|
500
|
+
self._route_peer(envelope, sender)
|
|
501
|
+
|
|
502
|
+
def _drain(self, member: Member) -> None:
|
|
503
|
+
watches = self._sessions.drain(member)
|
|
504
|
+
for watch in watches:
|
|
505
|
+
handover = ScheduleHandoverEnvelope(
|
|
506
|
+
id=create_id(),
|
|
507
|
+
sender=watch.requester,
|
|
508
|
+
to=member.name,
|
|
509
|
+
schedule_id=watch.id,
|
|
510
|
+
)
|
|
511
|
+
self._deliver(handover, member)
|
|
512
|
+
|
|
513
|
+
self._hand_over([], watches)
|
|
514
|
+
|
|
515
|
+
def _cancel_held(self, cancel: CancelEnvelope) -> bool:
|
|
516
|
+
task = WorkKey(cancel.sender, cancel.task_id)
|
|
517
|
+
if self._sessions.release_held(task) is None:
|
|
518
|
+
return False
|
|
519
|
+
|
|
520
|
+
self._clear_hold(task)
|
|
521
|
+
self._end_work(task.requester, task.id)
|
|
522
|
+
|
|
523
|
+
return True
|
|
524
|
+
|
|
525
|
+
def _route_peer(self, envelope: DeliveredEnvelope, sender: Member) -> None:
|
|
526
|
+
if isinstance(envelope, CancelEnvelope) and self._cancel_held(envelope):
|
|
527
|
+
return
|
|
528
|
+
|
|
529
|
+
recipient = self._sessions.find_recipient(envelope, envelope.to, sender)
|
|
530
|
+
if recipient is None:
|
|
531
|
+
raise AgentNotFoundError(envelope.to)
|
|
532
|
+
|
|
533
|
+
ready = envelope if isinstance(envelope, ConnectionReadyEnvelope) else None
|
|
534
|
+
is_accepted = ready is not None and self._actions.complete(ready)
|
|
535
|
+
|
|
536
|
+
if isinstance(envelope, MessageEnvelope):
|
|
537
|
+
self._deliver_message(envelope, recipient, sender)
|
|
538
|
+
return
|
|
539
|
+
|
|
540
|
+
if isinstance(envelope, ReplyEnvelope):
|
|
541
|
+
self._record(envelope)
|
|
542
|
+
|
|
543
|
+
if isinstance(envelope, ErrorEnvelope):
|
|
544
|
+
self._unanswered.pop(request_key(envelope.to, envelope.reply_to), None)
|
|
545
|
+
|
|
546
|
+
routed = (
|
|
547
|
+
self._stamp_proposal(envelope)
|
|
548
|
+
if isinstance(envelope, ProposeEnvelope)
|
|
549
|
+
else envelope
|
|
550
|
+
)
|
|
551
|
+
followed = self._find_followed(routed)
|
|
552
|
+
self._schedule(routed)
|
|
553
|
+
self._follow_ups.observe(routed)
|
|
554
|
+
self._sessions.track(routed, recipient, sender)
|
|
555
|
+
self._deliver(self._revisions.revise(routed), recipient)
|
|
556
|
+
if isinstance(
|
|
557
|
+
routed, AcceptEnvelope | RequireEnvelope | RejectEnvelope | ErrorEnvelope
|
|
558
|
+
):
|
|
559
|
+
self._respond(routed)
|
|
560
|
+
|
|
561
|
+
if isinstance(routed, ConnectionReadyEnvelope):
|
|
562
|
+
self._mirror_actions(routed.to, routed.proposal_id)
|
|
563
|
+
if is_accepted:
|
|
564
|
+
self._start(routed)
|
|
565
|
+
|
|
566
|
+
self._forward_ready(routed)
|
|
567
|
+
|
|
568
|
+
if isinstance(routed, ConnectionRevokedEnvelope):
|
|
569
|
+
self._revoke(routed)
|
|
570
|
+
|
|
571
|
+
if followed is not None:
|
|
572
|
+
spawn(self._follow_up_run(followed))
|
|
573
|
+
|
|
574
|
+
def _stamp_proposal(self, proposal: ProposeEnvelope) -> ProposeEnvelope:
|
|
575
|
+
"""Stamps a proposal with its principal, and the recap of the task it follows up on."""
|
|
576
|
+
stamped = proposal.model_copy(
|
|
577
|
+
update={"principal": self._lineage.propose(proposal)}
|
|
578
|
+
)
|
|
579
|
+
|
|
580
|
+
return self._follow_ups.follow(stamped, self._find_skill(stamped))
|
|
581
|
+
|
|
582
|
+
def _find_followed(self, envelope: DeliveredEnvelope) -> FollowedCompletion | None:
|
|
583
|
+
"""Finds the run a completion ends when its schedule follows runs up, with what the run finished."""
|
|
584
|
+
if not isinstance(envelope, CompleteEnvelope):
|
|
585
|
+
return None
|
|
586
|
+
|
|
587
|
+
run = self._book.find_followed(envelope)
|
|
588
|
+
if run is None:
|
|
589
|
+
return None
|
|
590
|
+
|
|
591
|
+
artifacts = self._artifacts.list_finished(envelope.to, envelope.task_id)
|
|
592
|
+
|
|
593
|
+
return FollowedCompletion(run, artifacts, envelope.output)
|
|
594
|
+
|
|
595
|
+
async def _follow_up_run(self, followed: FollowedCompletion) -> None:
|
|
596
|
+
"""Proposes a completed run's follow-up once its schedule's `when` holds, or tells the requester why it couldn't."""
|
|
597
|
+
run = followed.run
|
|
598
|
+
try:
|
|
599
|
+
when = run.then.when
|
|
600
|
+
if when.condition is None:
|
|
601
|
+
is_met = is_matching(followed.output, when.match)
|
|
602
|
+
else:
|
|
603
|
+
check = construct_check(
|
|
604
|
+
run, when.condition, followed.artifacts, followed.output
|
|
605
|
+
)
|
|
606
|
+
is_met = await resolve_value(self._judge_follow_up(check))
|
|
607
|
+
|
|
608
|
+
if is_met:
|
|
609
|
+
self._propose_follow_up(run, followed.artifacts)
|
|
610
|
+
except Exception as error:
|
|
611
|
+
self._deliver_to(
|
|
612
|
+
construct_notice(run, error=describe_error(error)), run.requester
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
def _propose_follow_up(
|
|
616
|
+
self, run: FollowedRun, artifacts: list[FinishedArtifact]
|
|
617
|
+
) -> None:
|
|
618
|
+
"""Proposes a run's follow-up from the schedule's requester, as a child of the run with its artifacts attached.
|
|
619
|
+
|
|
620
|
+
The requester hears of it before the follow-up's agent, as the AgentJam relay does.
|
|
621
|
+
"""
|
|
622
|
+
then = run.then
|
|
623
|
+
if not self._book.is_live(run.requester, run.schedule_id):
|
|
624
|
+
raise AgentJamError(
|
|
625
|
+
f'Schedule "{run.schedule_id}" ended before its run\'s follow-up'
|
|
626
|
+
)
|
|
627
|
+
|
|
628
|
+
skill = find_target_skill(then, self._profiles.get(then.to))
|
|
629
|
+
if problem := input_problem(then.input, skill):
|
|
630
|
+
raise InvalidInputError(then.to, problem)
|
|
631
|
+
|
|
632
|
+
draft = ProposeEnvelope(
|
|
633
|
+
id=f"{run.run_id}{FOLLOW_UP_SUFFIX}",
|
|
634
|
+
sender=run.requester,
|
|
635
|
+
to=then.to,
|
|
636
|
+
text=run.text if then.text is None else then.text,
|
|
637
|
+
skill=then.skill,
|
|
638
|
+
input=then.input,
|
|
639
|
+
parent=ParentRef(kind="task", requester=run.requester, id=run.run_id),
|
|
640
|
+
attachments=[artifact.attachment for artifact in artifacts] or None,
|
|
641
|
+
)
|
|
642
|
+
recipient = self._sessions.find_recipient(draft, then.to)
|
|
643
|
+
if recipient is None:
|
|
644
|
+
raise AgentNotFoundError(then.to)
|
|
645
|
+
|
|
646
|
+
principal = self._lineage.follow_up(draft, run.schedule_id)
|
|
647
|
+
proposal = draft.model_copy(update={"principal": principal})
|
|
648
|
+
notice = construct_notice(run, task_id=proposal.id)
|
|
649
|
+
sender = self._sessions.find_recipient(notice, run.requester)
|
|
650
|
+
self._actions.propose(proposal, skill.connections)
|
|
651
|
+
self._secrets.propose(proposal, skill.connections)
|
|
652
|
+
self._commits.propose(proposal, skill)
|
|
653
|
+
self._resumptions.propose(proposal, skill)
|
|
654
|
+
if sender is not None:
|
|
655
|
+
self._sessions.track(proposal, recipient, sender)
|
|
656
|
+
self._deliver(notice, sender)
|
|
657
|
+
|
|
658
|
+
self._deliver(proposal, recipient)
|
|
659
|
+
|
|
660
|
+
def _forward_ready(self, ready: ConnectionReadyEnvelope) -> None:
|
|
661
|
+
"""Completes a schedule's copy of an action a preparation below it just completed, telling its requester.
|
|
662
|
+
|
|
663
|
+
The schedule starts if that was its last action.
|
|
664
|
+
"""
|
|
665
|
+
schedule = self._lineage.find_prepared(ready.to, ready.proposal_id)
|
|
666
|
+
is_completed = self._actions.is_completed(
|
|
667
|
+
ready.to, ready.proposal_id, ready.provider
|
|
668
|
+
)
|
|
669
|
+
if schedule is None or not is_completed:
|
|
670
|
+
return
|
|
671
|
+
|
|
672
|
+
copy = ConnectionReadyEnvelope(
|
|
673
|
+
id=create_id(),
|
|
674
|
+
sender=schedule.executor,
|
|
675
|
+
to=schedule.requester,
|
|
676
|
+
proposal_id=schedule.task_id,
|
|
677
|
+
provider=ready.provider,
|
|
678
|
+
origin=ActionOrigin(
|
|
679
|
+
requester=ready.to, task_id=ready.proposal_id, executor=ready.sender
|
|
680
|
+
),
|
|
681
|
+
)
|
|
682
|
+
|
|
683
|
+
is_accepted = self._actions.complete(copy)
|
|
684
|
+
self._deliver_to(copy, copy.to)
|
|
685
|
+
if is_accepted:
|
|
686
|
+
self._start(copy)
|
|
687
|
+
|
|
688
|
+
def _find_skill(self, proposal: ProposeEnvelope) -> SkillCard | None:
|
|
689
|
+
card = self._profiles.get(proposal.to)
|
|
690
|
+
skills = [] if card is None else card.skills
|
|
691
|
+
|
|
692
|
+
return next((skill for skill in skills if skill.name == proposal.skill), None)
|
|
693
|
+
|
|
694
|
+
def _propose(self, proposal: ProposeEnvelope) -> None:
|
|
695
|
+
skill = self._find_skill(proposal)
|
|
696
|
+
if proposal.prepare and skill is None:
|
|
697
|
+
raise AgentJamError("A preparation names one of its executor's skills")
|
|
698
|
+
|
|
699
|
+
if proposal.cron is not None or proposal.trigger is not None:
|
|
700
|
+
self._admit_follow_up(proposal, skill)
|
|
701
|
+
|
|
702
|
+
problem = None if proposal.prepare else input_problem(proposal.input, skill)
|
|
703
|
+
if problem:
|
|
704
|
+
raise InvalidInputError(proposal.to, problem)
|
|
705
|
+
|
|
706
|
+
connections = None if skill is None else skill.connections
|
|
707
|
+
self._actions.propose(proposal, connections)
|
|
708
|
+
self._secrets.propose(proposal, connections)
|
|
709
|
+
self._commits.propose(proposal, skill)
|
|
710
|
+
self._resumptions.propose(proposal, skill)
|
|
711
|
+
self._book.propose(proposal, skill)
|
|
712
|
+
|
|
713
|
+
def _admit_follow_up(
|
|
714
|
+
self, proposal: ProposeEnvelope, skill: SkillCard | None
|
|
715
|
+
) -> None:
|
|
716
|
+
"""Checks a schedule's follow-up before the schedule is admitted, as the AgentJam relay does."""
|
|
717
|
+
then = proposal.then
|
|
718
|
+
if then is None:
|
|
719
|
+
return
|
|
720
|
+
|
|
721
|
+
if problem := follow_up_problem(then, proposal.sender, skill):
|
|
722
|
+
raise AgentJamError(problem)
|
|
723
|
+
|
|
724
|
+
target = find_target_skill(then, self._profiles.get(then.to))
|
|
725
|
+
if problem := input_problem(then.input, target):
|
|
726
|
+
raise InvalidInputError(then.to, problem)
|
|
727
|
+
|
|
728
|
+
self._lineage.assert_follow_up(proposal.sender, proposal.id, then.to)
|
|
729
|
+
|
|
730
|
+
def _assert_output(self, completion: CompleteEnvelope) -> None:
|
|
731
|
+
"""Refuses a completion whose output doesn't suit its skill's output schema, as the AgentJam relay does."""
|
|
732
|
+
work = self._lineage.find_skill(completion.to, completion.task_id)
|
|
733
|
+
if work is None:
|
|
734
|
+
return
|
|
735
|
+
|
|
736
|
+
card = self._profiles.get(work.executor)
|
|
737
|
+
skills = [] if card is None else card.skills
|
|
738
|
+
skill = next(
|
|
739
|
+
(offered for offered in skills if offered.name == work.skill), None
|
|
740
|
+
)
|
|
741
|
+
if problem := output_problem(completion.output, skill):
|
|
742
|
+
raise AgentJamError(problem)
|
|
743
|
+
|
|
744
|
+
def _respond(
|
|
745
|
+
self, verdict: AcceptEnvelope | RequireEnvelope | RejectEnvelope | ErrorEnvelope
|
|
746
|
+
) -> None:
|
|
747
|
+
match verdict:
|
|
748
|
+
case AcceptEnvelope():
|
|
749
|
+
self._actions.accept(verdict)
|
|
750
|
+
self._revisions.end(verdict.to, verdict.reply_to)
|
|
751
|
+
self._resumptions.accept(verdict.to, verdict.reply_to)
|
|
752
|
+
self._lineage.accept(verdict.to, verdict.reply_to)
|
|
753
|
+
|
|
754
|
+
case RequireEnvelope():
|
|
755
|
+
self._lineage.accept(verdict.to, verdict.reply_to)
|
|
756
|
+
|
|
757
|
+
case RejectEnvelope() | ErrorEnvelope():
|
|
758
|
+
self._end_work(verdict.to, verdict.reply_to)
|
|
759
|
+
|
|
760
|
+
case _:
|
|
761
|
+
assert_never(verdict)
|
|
762
|
+
|
|
763
|
+
self._book.respond(verdict)
|
|
764
|
+
|
|
765
|
+
def _start(self, ready: ConnectionReadyEnvelope) -> None:
|
|
766
|
+
"""Starts a schedule whose requester's human took its last action."""
|
|
767
|
+
if self._book.is_schedule(ready.to, ready.proposal_id):
|
|
768
|
+
self._book.activate(ready.to, ready.proposal_id)
|
|
769
|
+
else:
|
|
770
|
+
self._resumptions.accept(ready.to, ready.proposal_id)
|
|
771
|
+
|
|
772
|
+
def _revoke(self, revoked: ConnectionRevokedEnvelope) -> None:
|
|
773
|
+
reason = CONNECTION_REVOKED if revoked.reason is None else revoked.reason
|
|
774
|
+
for id in self._actions.using(revoked):
|
|
775
|
+
if self._book.is_schedule(revoked.to, id):
|
|
776
|
+
self._book.revoke(revoked.to, id)
|
|
777
|
+
else:
|
|
778
|
+
task = ActionOrigin(
|
|
779
|
+
requester=revoked.to, task_id=id, executor=revoked.sender
|
|
780
|
+
)
|
|
781
|
+
self._abort(task, reason, "connection_revoked")
|
|
782
|
+
|
|
783
|
+
def _abort(self, task: ActionOrigin, error: str, code: TaskEndCode) -> None:
|
|
784
|
+
"""Ends a task on the relay's own account, telling both its parties."""
|
|
785
|
+
self._end_work(task.requester, task.task_id)
|
|
786
|
+
|
|
787
|
+
failure = FailEnvelope(
|
|
788
|
+
id=f"{task.task_id}:{code}",
|
|
789
|
+
sender=task.executor,
|
|
790
|
+
to=task.requester,
|
|
791
|
+
task_id=task.task_id,
|
|
792
|
+
error=error,
|
|
793
|
+
code=code,
|
|
794
|
+
)
|
|
795
|
+
self._follow_ups.observe(failure)
|
|
796
|
+
self._deliver_to(failure, task.requester)
|
|
797
|
+
|
|
798
|
+
cancel = CancelEnvelope(
|
|
799
|
+
id=f"{task.task_id}:{code}:cancel",
|
|
800
|
+
sender=task.requester,
|
|
801
|
+
to=task.executor,
|
|
802
|
+
task_id=task.task_id,
|
|
803
|
+
reason=error,
|
|
804
|
+
)
|
|
805
|
+
self._deliver_to(cancel, task.executor)
|
|
806
|
+
|
|
807
|
+
def _schedule(self, envelope: DeliveredEnvelope) -> None:
|
|
808
|
+
match envelope:
|
|
809
|
+
case ProposeEnvelope():
|
|
810
|
+
self._propose(envelope)
|
|
811
|
+
|
|
812
|
+
case RequireEnvelope():
|
|
813
|
+
self._actions.require(envelope)
|
|
814
|
+
self._mirror_actions(envelope.to, envelope.reply_to)
|
|
815
|
+
|
|
816
|
+
case ConnectionRequiredEnvelope():
|
|
817
|
+
self._commits.require_access(envelope)
|
|
818
|
+
self._actions.require_access(envelope)
|
|
819
|
+
self._mirror_actions(envelope.to, envelope.proposal_id)
|
|
820
|
+
|
|
821
|
+
case CommitEnvelope():
|
|
822
|
+
self._commits.commit(envelope)
|
|
823
|
+
|
|
824
|
+
case ArtifactEnvelope():
|
|
825
|
+
self._artifacts.record(envelope)
|
|
826
|
+
self._commits.deliver(envelope)
|
|
827
|
+
|
|
828
|
+
case CompleteEnvelope():
|
|
829
|
+
self._assert_output(envelope)
|
|
830
|
+
self._end_work(envelope.to, envelope.task_id)
|
|
831
|
+
self._book.settle(envelope)
|
|
832
|
+
|
|
833
|
+
case FailEnvelope():
|
|
834
|
+
self._end_work(envelope.to, envelope.task_id)
|
|
835
|
+
self._book.settle(envelope)
|
|
836
|
+
|
|
837
|
+
case CancelEnvelope():
|
|
838
|
+
self._commits.cancel(envelope)
|
|
839
|
+
self._end_work(envelope.sender, envelope.task_id)
|
|
840
|
+
self._book.cancel(envelope)
|
|
841
|
+
|
|
842
|
+
case ScheduleEndEnvelope():
|
|
843
|
+
self._book.end(envelope)
|
|
844
|
+
|
|
845
|
+
case (
|
|
846
|
+
MessageEnvelope()
|
|
847
|
+
| ReplyEnvelope()
|
|
848
|
+
| ErrorEnvelope()
|
|
849
|
+
| AcceptEnvelope()
|
|
850
|
+
| RejectEnvelope()
|
|
851
|
+
| UpdateEnvelope()
|
|
852
|
+
| DisconnectEnvelope()
|
|
853
|
+
| ScheduleStartEnvelope()
|
|
854
|
+
| ScheduleHandoverEnvelope()
|
|
855
|
+
| TriggerFailedEnvelope()
|
|
856
|
+
| FollowUpEnvelope()
|
|
857
|
+
| RecurEnvelope()
|
|
858
|
+
| BudgetEnvelope()
|
|
859
|
+
| ActionsEnvelope()
|
|
860
|
+
| ConnectionReadyEnvelope()
|
|
861
|
+
| ConnectionStoredEnvelope()
|
|
862
|
+
| ConnectionRevokedEnvelope()
|
|
863
|
+
):
|
|
864
|
+
return
|
|
865
|
+
|
|
866
|
+
case _:
|
|
867
|
+
assert_never(envelope)
|
|
868
|
+
|
|
869
|
+
def _end_work(self, requester: str, id: str) -> None:
|
|
870
|
+
"""Forgets the ended task `id` of `requester`, and cancels the open tasks delegated as part of it except committed ones."""
|
|
871
|
+
self._actions.end(requester, id)
|
|
872
|
+
self._secrets.end(requester, id)
|
|
873
|
+
self._commits.end(requester, id)
|
|
874
|
+
self._artifacts.end(requester, id)
|
|
875
|
+
self._revisions.end(requester, id)
|
|
876
|
+
self._mirror_actions(requester, id)
|
|
877
|
+
self._lineage.end(requester, id)
|
|
878
|
+
self._resumptions.end(requester, id)
|
|
879
|
+
|
|
880
|
+
for child in self._lineage.list_children(requester, id):
|
|
881
|
+
if not self._commits.is_committed(child.requester, child.task_id):
|
|
882
|
+
self._abort(child, PARENT_ENDED, "parent_ended")
|
|
883
|
+
|
|
884
|
+
def _mirror_actions(self, requester: str, id: str) -> None:
|
|
885
|
+
"""Mirrors the own actions of the task or run `id` of `requester` onto the open tasks above it, while it's open."""
|
|
886
|
+
required = self._actions.find_required(requester, id)
|
|
887
|
+
actions = [action for action in required.actions if action.is_own]
|
|
888
|
+
if not actions:
|
|
889
|
+
return
|
|
890
|
+
|
|
891
|
+
chain = self._lineage.list_chain(requester, id)
|
|
892
|
+
for notice in self._copies.mirror(chain, actions if required.open else []):
|
|
893
|
+
self._deliver_to(notice, notice.to)
|
|
894
|
+
|
|
895
|
+
def _deliver_message(
|
|
896
|
+
self, envelope: MessageEnvelope, recipient: Member, sender: Member
|
|
897
|
+
) -> None:
|
|
898
|
+
self._follow_ups.check_steering(envelope)
|
|
899
|
+
|
|
900
|
+
history = self._get_history(
|
|
901
|
+
envelope.sender, envelope.to, envelope.conversation_id
|
|
902
|
+
)
|
|
903
|
+
if all(turn.id != envelope.id for turn in history):
|
|
904
|
+
self._unanswered[request_key(envelope.sender, envelope.id)] = Message(
|
|
905
|
+
id=envelope.id,
|
|
906
|
+
sender=envelope.sender,
|
|
907
|
+
to=envelope.to,
|
|
908
|
+
conversation_id=envelope.conversation_id,
|
|
909
|
+
text=envelope.text,
|
|
910
|
+
)
|
|
911
|
+
|
|
912
|
+
task = self._follow_ups.recap_messaged(envelope)
|
|
913
|
+
self._follow_ups.observe(envelope)
|
|
914
|
+
self._sessions.track(envelope, recipient, sender)
|
|
915
|
+
update: dict[str, Any] = {"history": list(history)}
|
|
916
|
+
if task is not None:
|
|
917
|
+
update["task"] = task
|
|
918
|
+
|
|
919
|
+
self._deliver(envelope.model_copy(update=update), recipient)
|
|
920
|
+
|
|
921
|
+
def _record(self, reply: ReplyEnvelope) -> None:
|
|
922
|
+
message = self._unanswered.pop(request_key(reply.to, reply.reply_to), None)
|
|
923
|
+
if message is None:
|
|
924
|
+
return
|
|
925
|
+
|
|
926
|
+
answer = Message(
|
|
927
|
+
id=reply.id,
|
|
928
|
+
sender=reply.sender,
|
|
929
|
+
to=reply.to,
|
|
930
|
+
conversation_id=message.conversation_id,
|
|
931
|
+
text=reply.text,
|
|
932
|
+
)
|
|
933
|
+
history = self._get_history(message.sender, message.to, message.conversation_id)
|
|
934
|
+
history.extend([message, answer])
|
|
935
|
+
|
|
936
|
+
def _get_history(
|
|
937
|
+
self, first: str, second: str, conversation_id: str
|
|
938
|
+
) -> list[Message]:
|
|
939
|
+
key = conversation_key(first, second, conversation_id)
|
|
940
|
+
|
|
941
|
+
return self._conversations.setdefault(key, [])
|
|
942
|
+
|
|
943
|
+
def _deliver_scheduled(self, recipient: str, envelope: DeliveredEnvelope) -> None:
|
|
944
|
+
if isinstance(envelope, RecurEnvelope):
|
|
945
|
+
self._lineage.recur(envelope)
|
|
946
|
+
self._actions.recur(envelope)
|
|
947
|
+
self._follow_ups.recur(envelope)
|
|
948
|
+
|
|
949
|
+
self._deliver_to(envelope, recipient)
|
|
950
|
+
|
|
951
|
+
def _deliver_to(self, envelope: DeliveredEnvelope, name: str) -> None:
|
|
952
|
+
"""Delivers an envelope the relay sends itself to the session of `name` its work is bound to."""
|
|
953
|
+
recipient = self._sessions.find_recipient(envelope, name)
|
|
954
|
+
if recipient is None:
|
|
955
|
+
return
|
|
956
|
+
|
|
957
|
+
self._sessions.track(envelope, recipient)
|
|
958
|
+
self._deliver(envelope, recipient)
|
|
959
|
+
|
|
960
|
+
def _deliver(self, envelope: DeliveredEnvelope, recipient: Member) -> None:
|
|
961
|
+
wire = envelope.to_wire()
|
|
962
|
+
asyncio.get_running_loop().call_soon(self._receive, recipient, wire)
|
|
963
|
+
|
|
964
|
+
def _receive(self, recipient: Member, wire: JsonObject) -> None:
|
|
965
|
+
if self._sessions.is_live(recipient):
|
|
966
|
+
spawn(hand_envelope(recipient, parse_envelope(wire)))
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
class MemoryCredentials:
|
|
970
|
+
"""The credential channel of one session of a `MemoryRelay`, which reaches the relay's secret stubs."""
|
|
971
|
+
|
|
972
|
+
def __init__(self, relay: MemoryRelay, member: Member) -> None:
|
|
973
|
+
self._relay = relay
|
|
974
|
+
self._member = member
|
|
975
|
+
|
|
976
|
+
async def authorize(self, grant: SecretGrant) -> str | None:
|
|
977
|
+
self._relay._assert_open(self._member)
|
|
978
|
+
|
|
979
|
+
return self._relay._secrets.authorize(self._member.name, grant)
|
|
980
|
+
|
|
981
|
+
async def release(self, grant: SecretGrant) -> None:
|
|
982
|
+
self._relay._secrets.release(self._member.name, grant)
|
|
983
|
+
|
|
984
|
+
async def config(self, grant: SecretGrant) -> dict[str, str]:
|
|
985
|
+
self._relay._assert_open(self._member)
|
|
986
|
+
|
|
987
|
+
return self._relay._secrets.config(self._member.name, grant)
|
|
988
|
+
|
|
989
|
+
async def fetch(self, grant: SecretGrant, request: httpx.Request) -> httpx.Response:
|
|
990
|
+
self._relay._assert_open(self._member)
|
|
991
|
+
|
|
992
|
+
return await self._relay._secrets.fetch(self._member.name, grant, request)
|
|
993
|
+
|
|
994
|
+
|
|
995
|
+
class MemoryConnection:
|
|
996
|
+
"""One session of an agent on a `MemoryRelay`."""
|
|
997
|
+
|
|
998
|
+
def __init__(self, relay: MemoryRelay, member: Member) -> None:
|
|
999
|
+
self._relay = relay
|
|
1000
|
+
self._member = member
|
|
1001
|
+
self._credentials = MemoryCredentials(relay, member)
|
|
1002
|
+
|
|
1003
|
+
@property
|
|
1004
|
+
def name(self) -> str:
|
|
1005
|
+
return self._member.name
|
|
1006
|
+
|
|
1007
|
+
@property
|
|
1008
|
+
def card(self) -> AgentCard:
|
|
1009
|
+
return copy_card(self._relay._get_profile(self.name))
|
|
1010
|
+
|
|
1011
|
+
@property
|
|
1012
|
+
def claim_url(self) -> str | None:
|
|
1013
|
+
return None
|
|
1014
|
+
|
|
1015
|
+
@property
|
|
1016
|
+
def payouts_url(self) -> str | None:
|
|
1017
|
+
return None
|
|
1018
|
+
|
|
1019
|
+
@property
|
|
1020
|
+
def credentials(self) -> MemoryCredentials:
|
|
1021
|
+
return self._credentials
|
|
1022
|
+
|
|
1023
|
+
async def send(self, envelope: Draft) -> None:
|
|
1024
|
+
self._relay._send(self._member, envelope)
|
|
1025
|
+
|
|
1026
|
+
async def find(self, query: AgentQuery) -> list[AgentCard]:
|
|
1027
|
+
return self._relay._find_cards(query)
|
|
1028
|
+
|
|
1029
|
+
async def recall(self, task: TaskRef) -> TaskRecapRef:
|
|
1030
|
+
self._relay._assert_open(self._member)
|
|
1031
|
+
|
|
1032
|
+
return self._relay._follow_ups.recall(self.name, task)
|
|
1033
|
+
|
|
1034
|
+
async def history(self, anchor: TaskRef, query: HistoryQuery) -> HistoryPage:
|
|
1035
|
+
self._relay._assert_open(self._member)
|
|
1036
|
+
|
|
1037
|
+
return self._relay._follow_ups.list_history(self.name, anchor, query)
|
|
1038
|
+
|
|
1039
|
+
async def upload(self, file: File, signal: Signal | None = None) -> str:
|
|
1040
|
+
self._relay._assert_open(self._member)
|
|
1041
|
+
|
|
1042
|
+
return self._relay._store_upload(self.name, file)
|
|
1043
|
+
|
|
1044
|
+
async def close(self) -> None:
|
|
1045
|
+
self._relay._close(self._member)
|