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,472 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any, Protocol, assert_never, overload
|
|
5
|
+
|
|
6
|
+
from agentjam._artifacts import ArtifactAssembler
|
|
7
|
+
from agentjam._attachments import AttachmentSource
|
|
8
|
+
from agentjam._errors import TaskCanceledError, TaskCommittedError, TaskFailedError
|
|
9
|
+
from agentjam._protocol import (
|
|
10
|
+
ArtifactEnvelope,
|
|
11
|
+
CancelEnvelope,
|
|
12
|
+
CommitEnvelope,
|
|
13
|
+
CompleteEnvelope,
|
|
14
|
+
CopiedAction,
|
|
15
|
+
FailEnvelope,
|
|
16
|
+
ParentRef,
|
|
17
|
+
TaskEnvelope,
|
|
18
|
+
UpdateEnvelope,
|
|
19
|
+
)
|
|
20
|
+
from agentjam._tasks.incoming import TaskSender, parse_output
|
|
21
|
+
from agentjam._tasks.serial import SerialQueue, retrieve
|
|
22
|
+
from agentjam._types import (
|
|
23
|
+
ActionsEvent,
|
|
24
|
+
Artifact,
|
|
25
|
+
ArtifactEvent,
|
|
26
|
+
CommitEvent,
|
|
27
|
+
JsonObject,
|
|
28
|
+
MessageReply,
|
|
29
|
+
OutputT,
|
|
30
|
+
ProposalAction,
|
|
31
|
+
RestartEvent,
|
|
32
|
+
SkillHandler,
|
|
33
|
+
TaskEvent,
|
|
34
|
+
TriggerEvent,
|
|
35
|
+
UpdateEvent,
|
|
36
|
+
)
|
|
37
|
+
from agentjam._utils import create_id
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class OutgoingTask(Protocol):
|
|
41
|
+
"""A task delegated to another agent, returned by `propose()`."""
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def id(self) -> str:
|
|
45
|
+
"""The task's unique id, which `rate()` takes."""
|
|
46
|
+
...
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def to(self) -> str:
|
|
50
|
+
"""The agent executing the task."""
|
|
51
|
+
...
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def schedule_id(self) -> str | None:
|
|
55
|
+
"""The schedule this task is a run of, if any."""
|
|
56
|
+
...
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def event(self) -> TriggerEvent | None:
|
|
60
|
+
"""The trigger event that started this run, if it's a run of a trigger schedule."""
|
|
61
|
+
...
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def parent(self) -> ParentRef | None:
|
|
65
|
+
"""The task this agent proposed this one as part of, or for a preparation, the schedule it prepares, if any."""
|
|
66
|
+
...
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def actions(self) -> list[ProposalAction]:
|
|
70
|
+
"""What the requester's human must still do, such as connecting an account at a link.
|
|
71
|
+
|
|
72
|
+
First what the executor needs before it starts, then what agents it delegated to need to go on, each naming its `origin`.
|
|
73
|
+
"""
|
|
74
|
+
...
|
|
75
|
+
|
|
76
|
+
def events(self) -> AsyncIterator[TaskEvent]:
|
|
77
|
+
"""Streams the task's events from the start, ending once the task completes.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
An async iterator of every event, in the order the executor produced them.
|
|
81
|
+
Raises:
|
|
82
|
+
TaskFailedError: If the executor fails the task.
|
|
83
|
+
TaskRejectedError: If the executor declines the task after restarting.
|
|
84
|
+
TaskCanceledError: If the task is canceled.
|
|
85
|
+
"""
|
|
86
|
+
...
|
|
87
|
+
|
|
88
|
+
async def result(self) -> list[Artifact]:
|
|
89
|
+
"""Waits for the task to complete.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
Every artifact since the last restart, in delivery order, keeping only the latest revision of each key.
|
|
93
|
+
Raises:
|
|
94
|
+
TaskFailedError: If the executor fails the task.
|
|
95
|
+
TaskRejectedError: If the executor declines the task after restarting.
|
|
96
|
+
TaskCanceledError: If the task is canceled.
|
|
97
|
+
"""
|
|
98
|
+
...
|
|
99
|
+
|
|
100
|
+
@overload
|
|
101
|
+
async def get_output(self) -> JsonObject | None: ...
|
|
102
|
+
|
|
103
|
+
@overload
|
|
104
|
+
async def get_output(self, skill: SkillHandler[Any, OutputT]) -> OutputT | None: ...
|
|
105
|
+
|
|
106
|
+
async def get_output(
|
|
107
|
+
self, skill: SkillHandler[Any, OutputT] | None = None
|
|
108
|
+
) -> OutputT | JsonObject | None:
|
|
109
|
+
"""Waits for the task to complete and returns the structured output the executor set.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
skill: The skill the task called for, whose `output` schema parses the output. Defaults to the raw JSON.
|
|
113
|
+
Returns:
|
|
114
|
+
The output, which matches its skill's `output_schema`, or None if the executor set none.
|
|
115
|
+
Raises:
|
|
116
|
+
TaskFailedError: If the executor fails the task.
|
|
117
|
+
TaskRejectedError: If the executor declines the task after restarting.
|
|
118
|
+
TaskCanceledError: If the task is canceled.
|
|
119
|
+
AgentJamError: If `skill` has no output schema, or its schema refuses the output.
|
|
120
|
+
"""
|
|
121
|
+
...
|
|
122
|
+
|
|
123
|
+
async def cancel(self, reason: str | None = None) -> None:
|
|
124
|
+
"""Asks the executor to stop, which charges a `cost_plus` task the cost it reported so far plus its markup.
|
|
125
|
+
|
|
126
|
+
Does nothing if the task has already ended.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
reason: Why the task is being canceled, shown to the executor.
|
|
130
|
+
Raises:
|
|
131
|
+
TaskCommittedError: If the executor committed to an action it can't undo, or the task has a `flat` price and its executor sent part of its result, so the task keeps running.
|
|
132
|
+
"""
|
|
133
|
+
...
|
|
134
|
+
|
|
135
|
+
async def send(
|
|
136
|
+
self,
|
|
137
|
+
text: str,
|
|
138
|
+
*,
|
|
139
|
+
conversation_id: str | None = None,
|
|
140
|
+
attachments: Sequence[AttachmentSource] | None = None,
|
|
141
|
+
steer: bool = False,
|
|
142
|
+
timeout: float | None = None,
|
|
143
|
+
idempotency_key: str | None = None,
|
|
144
|
+
) -> MessageReply:
|
|
145
|
+
"""Sends the executor a message about this task and returns its reply.
|
|
146
|
+
|
|
147
|
+
It reaches the session running the task, in a conversation named after the task unless `conversation_id` names
|
|
148
|
+
another. With `steer`, a running task that opened its inbox takes the message as a change instead.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
text: The message to send.
|
|
152
|
+
conversation_id: The conversation to continue.
|
|
153
|
+
attachments: Files to attach, at most 10 of up to 100 MiB each.
|
|
154
|
+
steer: Whether to pass the message to the work in progress.
|
|
155
|
+
timeout: How long to wait for the reply, in seconds. Defaults to the one passed to `connect()`.
|
|
156
|
+
idempotency_key: Makes retrying safe, since the executor answers a repeat instead of handling it twice.
|
|
157
|
+
Returns:
|
|
158
|
+
The executor's reply, with its files downloaded.
|
|
159
|
+
Raises:
|
|
160
|
+
AgentNotFoundError: If the session running the task is gone.
|
|
161
|
+
TimeoutError: If no reply arrives within the timeout.
|
|
162
|
+
"""
|
|
163
|
+
...
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def compute_failure(envelope: FailEnvelope) -> Exception:
|
|
167
|
+
match envelope.code:
|
|
168
|
+
case "action_expired" | "connection_revoked" | None:
|
|
169
|
+
return TaskFailedError(envelope.error, envelope.uncovered)
|
|
170
|
+
|
|
171
|
+
case (
|
|
172
|
+
"parent_ended"
|
|
173
|
+
| "max_price_reached"
|
|
174
|
+
| "cap_reached"
|
|
175
|
+
| "insufficient_credits"
|
|
176
|
+
| "reload_failed"
|
|
177
|
+
):
|
|
178
|
+
return TaskCanceledError(envelope.error, envelope.code)
|
|
179
|
+
|
|
180
|
+
case _:
|
|
181
|
+
assert_never(envelope.code)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@dataclass(frozen=True)
|
|
185
|
+
class TaskLink:
|
|
186
|
+
post: Callable[[CancelEnvelope], Awaitable[None]]
|
|
187
|
+
send: TaskSender
|
|
188
|
+
release: Callable[[], None]
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@dataclass(frozen=True)
|
|
192
|
+
class RunDetails:
|
|
193
|
+
"""What makes a task a run of a schedule."""
|
|
194
|
+
|
|
195
|
+
schedule_id: str
|
|
196
|
+
event: TriggerEvent | None
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class TaskHandle:
|
|
200
|
+
"""A task this agent delegated, which replays the executor's events in order and settles with its result."""
|
|
201
|
+
|
|
202
|
+
def __init__(
|
|
203
|
+
self,
|
|
204
|
+
id: str,
|
|
205
|
+
to: str,
|
|
206
|
+
attempt: str | None,
|
|
207
|
+
link: TaskLink,
|
|
208
|
+
*,
|
|
209
|
+
run: RunDetails | None = None,
|
|
210
|
+
parent: ParentRef | None = None,
|
|
211
|
+
actions: Sequence[ProposalAction] = (),
|
|
212
|
+
) -> None:
|
|
213
|
+
self.id = id
|
|
214
|
+
self.to = to
|
|
215
|
+
self.schedule_id = run.schedule_id if run else None
|
|
216
|
+
self.event = run.event if run else None
|
|
217
|
+
self.parent = parent
|
|
218
|
+
self._attempt = attempt
|
|
219
|
+
self._link = link
|
|
220
|
+
self._required: list[ProposalAction] = []
|
|
221
|
+
self._inherited: list[ProposalAction] = []
|
|
222
|
+
self._log: list[TaskEvent] = []
|
|
223
|
+
self._received: set[str] = set()
|
|
224
|
+
self._artifacts: list[Artifact] = []
|
|
225
|
+
self._output: JsonObject | None = None
|
|
226
|
+
self._assembler = ArtifactAssembler()
|
|
227
|
+
self._changed = asyncio.Event()
|
|
228
|
+
self._queue = SerialQueue()
|
|
229
|
+
self._ended = False
|
|
230
|
+
self._outcome: asyncio.Future[list[Artifact]] = (
|
|
231
|
+
asyncio.get_running_loop().create_future()
|
|
232
|
+
)
|
|
233
|
+
self._store_actions(actions)
|
|
234
|
+
# WARNING: callers may never call result(), so a failed outcome must not be logged as never retrieved.
|
|
235
|
+
self._outcome.add_done_callback(retrieve)
|
|
236
|
+
|
|
237
|
+
@property
|
|
238
|
+
def actions(self) -> list[ProposalAction]:
|
|
239
|
+
return [*self._required, *self._inherited]
|
|
240
|
+
|
|
241
|
+
async def events(self) -> AsyncIterator[TaskEvent]:
|
|
242
|
+
index = 0
|
|
243
|
+
|
|
244
|
+
while index < len(self._log) or not self._ended:
|
|
245
|
+
if index == len(self._log):
|
|
246
|
+
await self._changed.wait()
|
|
247
|
+
continue
|
|
248
|
+
|
|
249
|
+
index += 1
|
|
250
|
+
yield self._log[index - 1]
|
|
251
|
+
|
|
252
|
+
await asyncio.shield(self._outcome)
|
|
253
|
+
|
|
254
|
+
async def result(self) -> list[Artifact]:
|
|
255
|
+
return await asyncio.shield(self._outcome)
|
|
256
|
+
|
|
257
|
+
@overload
|
|
258
|
+
async def get_output(self) -> JsonObject | None: ...
|
|
259
|
+
|
|
260
|
+
@overload
|
|
261
|
+
async def get_output(self, skill: SkillHandler[Any, OutputT]) -> OutputT | None: ...
|
|
262
|
+
|
|
263
|
+
async def get_output(
|
|
264
|
+
self, skill: SkillHandler[Any, OutputT] | None = None
|
|
265
|
+
) -> OutputT | JsonObject | None:
|
|
266
|
+
await asyncio.shield(self._outcome)
|
|
267
|
+
if skill is None or self._output is None:
|
|
268
|
+
return self._output
|
|
269
|
+
|
|
270
|
+
return parse_output(skill, self._output)
|
|
271
|
+
|
|
272
|
+
async def cancel(self, reason: str | None = None) -> None:
|
|
273
|
+
if self._ended:
|
|
274
|
+
return
|
|
275
|
+
|
|
276
|
+
canceled = TaskCanceledError(
|
|
277
|
+
reason if reason is not None else "The task was canceled"
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
try:
|
|
281
|
+
await self._link.post(
|
|
282
|
+
CancelEnvelope(
|
|
283
|
+
id=create_id(), to=self.to, task_id=self.id, reason=reason
|
|
284
|
+
)
|
|
285
|
+
)
|
|
286
|
+
except Exception as error:
|
|
287
|
+
if not isinstance(error, TaskCommittedError):
|
|
288
|
+
self.fail(canceled)
|
|
289
|
+
|
|
290
|
+
raise
|
|
291
|
+
|
|
292
|
+
self.fail(canceled)
|
|
293
|
+
|
|
294
|
+
async def send(
|
|
295
|
+
self,
|
|
296
|
+
text: str,
|
|
297
|
+
*,
|
|
298
|
+
conversation_id: str | None = None,
|
|
299
|
+
attachments: Sequence[AttachmentSource] | None = None,
|
|
300
|
+
steer: bool = False,
|
|
301
|
+
timeout: float | None = None,
|
|
302
|
+
idempotency_key: str | None = None,
|
|
303
|
+
) -> MessageReply:
|
|
304
|
+
return await self._link.send(
|
|
305
|
+
text,
|
|
306
|
+
conversation_id=conversation_id,
|
|
307
|
+
attachments=attachments,
|
|
308
|
+
steer=steer,
|
|
309
|
+
timeout=timeout,
|
|
310
|
+
idempotency_key=idempotency_key,
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
def restart(
|
|
314
|
+
self, attempt: str, actions: Sequence[ProposalAction]
|
|
315
|
+
) -> asyncio.Task[None]:
|
|
316
|
+
"""Queues a restart, which starts over if `attempt`, the id of a `task.accept` or `task.require`, is a new acceptance."""
|
|
317
|
+
return self._queue.enqueue(lambda: self._start_over(attempt, actions))
|
|
318
|
+
|
|
319
|
+
def complete(self, provider: str) -> None:
|
|
320
|
+
"""Marks the human's action for `provider` as taken."""
|
|
321
|
+
self._required = [
|
|
322
|
+
action for action in self._required if action.provider != provider
|
|
323
|
+
]
|
|
324
|
+
|
|
325
|
+
def require_access(self, action: ProposalAction) -> bool:
|
|
326
|
+
"""Waits on an action the executor requires once running, in place of its earlier one for the same provider.
|
|
327
|
+
|
|
328
|
+
Returns whether the task is still open.
|
|
329
|
+
"""
|
|
330
|
+
if self._ended:
|
|
331
|
+
return False
|
|
332
|
+
|
|
333
|
+
self._required = [
|
|
334
|
+
*(kept for kept in self._required if kept.provider != action.provider),
|
|
335
|
+
action,
|
|
336
|
+
]
|
|
337
|
+
self._emit(ActionsEvent(actions=self.actions))
|
|
338
|
+
|
|
339
|
+
return True
|
|
340
|
+
|
|
341
|
+
def inherit(self, actions: Sequence[CopiedAction]) -> list[ProposalAction]:
|
|
342
|
+
"""Replaces the actions copied from tasks the executor delegated, returning the ones newly pending."""
|
|
343
|
+
known = {action.url for action in self._inherited}
|
|
344
|
+
pending = [
|
|
345
|
+
ProposalAction(
|
|
346
|
+
kind=action.kind,
|
|
347
|
+
provider=action.provider,
|
|
348
|
+
url=action.url,
|
|
349
|
+
origin=action.origin,
|
|
350
|
+
reason=action.reason,
|
|
351
|
+
)
|
|
352
|
+
for action in actions
|
|
353
|
+
if action.status == "pending"
|
|
354
|
+
]
|
|
355
|
+
|
|
356
|
+
fresh = [action for action in pending if action.url not in known]
|
|
357
|
+
if self._ended or (not fresh and len(pending) == len(known)):
|
|
358
|
+
return []
|
|
359
|
+
|
|
360
|
+
self._inherited = pending
|
|
361
|
+
self._emit(ActionsEvent(actions=self.actions))
|
|
362
|
+
|
|
363
|
+
return fresh
|
|
364
|
+
|
|
365
|
+
def fail(self, error: Exception) -> None:
|
|
366
|
+
"""Ends the task with an error the executor didn't report through a `task.fail`."""
|
|
367
|
+
if not self._ended:
|
|
368
|
+
self._end(error)
|
|
369
|
+
|
|
370
|
+
def receive(self, envelope: TaskEnvelope) -> Awaitable[None]:
|
|
371
|
+
"""Queues an envelope, settling once it and everything received before it are handled."""
|
|
372
|
+
if self._ended or envelope.id in self._received:
|
|
373
|
+
return self._queue.wait()
|
|
374
|
+
|
|
375
|
+
self._received.add(envelope.id)
|
|
376
|
+
|
|
377
|
+
return self._queue.enqueue(lambda: self._handle(envelope))
|
|
378
|
+
|
|
379
|
+
async def _start_over(
|
|
380
|
+
self, attempt: str, actions: Sequence[ProposalAction]
|
|
381
|
+
) -> None:
|
|
382
|
+
if self._ended or attempt == self._attempt:
|
|
383
|
+
return
|
|
384
|
+
|
|
385
|
+
reattached = self._attempt is None
|
|
386
|
+
self._attempt = attempt
|
|
387
|
+
self._store_actions(actions)
|
|
388
|
+
if reattached:
|
|
389
|
+
return
|
|
390
|
+
|
|
391
|
+
self._artifacts = []
|
|
392
|
+
self._assembler = ArtifactAssembler()
|
|
393
|
+
self._emit(RestartEvent())
|
|
394
|
+
|
|
395
|
+
def _store_actions(self, actions: Sequence[ProposalAction]) -> None:
|
|
396
|
+
"""Splits a verdict's actions into the executor's own and the copies of its delegates'."""
|
|
397
|
+
self._required = [action for action in actions if action.origin is None]
|
|
398
|
+
self._inherited = [action for action in actions if action.origin is not None]
|
|
399
|
+
|
|
400
|
+
async def _handle(self, envelope: TaskEnvelope) -> None:
|
|
401
|
+
if self._ended:
|
|
402
|
+
return
|
|
403
|
+
|
|
404
|
+
match envelope:
|
|
405
|
+
case UpdateEnvelope():
|
|
406
|
+
self._emit(UpdateEvent(text=envelope.text))
|
|
407
|
+
|
|
408
|
+
case ArtifactEnvelope():
|
|
409
|
+
await self._assemble(envelope)
|
|
410
|
+
|
|
411
|
+
case CommitEnvelope():
|
|
412
|
+
self._emit(CommitEvent())
|
|
413
|
+
|
|
414
|
+
case CompleteEnvelope():
|
|
415
|
+
self._output = envelope.output
|
|
416
|
+
self._end()
|
|
417
|
+
|
|
418
|
+
case FailEnvelope():
|
|
419
|
+
self._end(compute_failure(envelope))
|
|
420
|
+
|
|
421
|
+
case _:
|
|
422
|
+
assert_never(envelope)
|
|
423
|
+
|
|
424
|
+
async def _assemble(self, envelope: ArtifactEnvelope) -> None:
|
|
425
|
+
try:
|
|
426
|
+
events = await self._assembler.add(envelope)
|
|
427
|
+
except Exception as error:
|
|
428
|
+
self.fail(error)
|
|
429
|
+
events = []
|
|
430
|
+
|
|
431
|
+
if not self._ended:
|
|
432
|
+
for event in events:
|
|
433
|
+
self._emit(event)
|
|
434
|
+
|
|
435
|
+
def _emit(self, event: TaskEvent) -> None:
|
|
436
|
+
if isinstance(event, ArtifactEvent):
|
|
437
|
+
self._store_artifact(event.artifact)
|
|
438
|
+
|
|
439
|
+
self._log.append(event)
|
|
440
|
+
self._notify()
|
|
441
|
+
|
|
442
|
+
def _store_artifact(self, artifact: Artifact) -> None:
|
|
443
|
+
kept = (
|
|
444
|
+
None
|
|
445
|
+
if artifact.key is None
|
|
446
|
+
else next(
|
|
447
|
+
(stored for stored in self._artifacts if stored.key == artifact.key),
|
|
448
|
+
None,
|
|
449
|
+
)
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
if kept and (kept.revision or 0) > (artifact.revision or 0):
|
|
453
|
+
return
|
|
454
|
+
|
|
455
|
+
self._artifacts = [
|
|
456
|
+
*(stored for stored in self._artifacts if stored is not kept),
|
|
457
|
+
artifact,
|
|
458
|
+
]
|
|
459
|
+
|
|
460
|
+
def _end(self, error: Exception | None = None) -> None:
|
|
461
|
+
self._ended = True
|
|
462
|
+
if error is not None:
|
|
463
|
+
self._outcome.set_exception(error)
|
|
464
|
+
else:
|
|
465
|
+
self._outcome.set_result(self._artifacts)
|
|
466
|
+
|
|
467
|
+
self._link.release()
|
|
468
|
+
self._notify()
|
|
469
|
+
|
|
470
|
+
def _notify(self) -> None:
|
|
471
|
+
self._changed.set()
|
|
472
|
+
self._changed = asyncio.Event()
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from collections import deque
|
|
3
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
from agentjam._protocol import ParentRef, ScheduleEndEnvelope
|
|
8
|
+
from agentjam._tasks.outgoing import OutgoingTask
|
|
9
|
+
from agentjam._types import ActionOrigin, ProposalAction
|
|
10
|
+
from agentjam._utils import create_id
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Schedule(Protocol):
|
|
14
|
+
"""A recurring task delegated to another agent, returned by `schedule()`."""
|
|
15
|
+
|
|
16
|
+
@property
|
|
17
|
+
def id(self) -> str:
|
|
18
|
+
"""The schedule's unique id."""
|
|
19
|
+
...
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def to(self) -> str:
|
|
23
|
+
"""The agent executing the runs."""
|
|
24
|
+
...
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def actions(self) -> list[ProposalAction]:
|
|
28
|
+
"""What the requester's human must still do before the first run, such as connecting an account at a link."""
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
def runs(self) -> AsyncIterator[OutgoingTask]:
|
|
32
|
+
"""Streams the schedule's runs as they start, including runs that started while this agent was offline.
|
|
33
|
+
|
|
34
|
+
Each run is yielded once, and the stream ends once the schedule ends.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
An async iterator of runs, in the order they started.
|
|
38
|
+
"""
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
def follow_ups(self) -> AsyncIterator[OutgoingTask]:
|
|
42
|
+
"""Streams the follow-ups the relay proposed on this agent's behalf after runs that met the schedule's `then` condition.
|
|
43
|
+
|
|
44
|
+
Each is yielded once, and the stream ends once the schedule ends.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
An async iterator of follow-up tasks, in the order they were proposed.
|
|
48
|
+
"""
|
|
49
|
+
...
|
|
50
|
+
|
|
51
|
+
async def ended(self) -> str:
|
|
52
|
+
"""Waits for the schedule to end, whichever party or the relay ended it.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
Why the schedule ended.
|
|
56
|
+
"""
|
|
57
|
+
...
|
|
58
|
+
|
|
59
|
+
async def end(self, reason: str | None = None) -> None:
|
|
60
|
+
"""Stops the schedule so no more runs start, leaving a run in progress to finish.
|
|
61
|
+
|
|
62
|
+
Does nothing if the schedule has already ended.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
reason: Why the schedule is ending, shown to the executor.
|
|
66
|
+
"""
|
|
67
|
+
...
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class ScheduleLink:
|
|
72
|
+
post: Callable[[ScheduleEndEnvelope], Awaitable[None]]
|
|
73
|
+
hand: Callable[[OutgoingTask], None]
|
|
74
|
+
"""Called once per run, when the app receives it."""
|
|
75
|
+
release: Callable[[], None]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class TaskFeed:
|
|
79
|
+
"""Invariant: `queued` holds tasks not yet yielded, and `known` every task ever added, so each task is yielded once."""
|
|
80
|
+
|
|
81
|
+
def __init__(self) -> None:
|
|
82
|
+
self._queued: deque[OutgoingTask] = deque()
|
|
83
|
+
self._known: set[str] = set()
|
|
84
|
+
|
|
85
|
+
def __len__(self) -> int:
|
|
86
|
+
return len(self._queued)
|
|
87
|
+
|
|
88
|
+
def add(self, task: OutgoingTask) -> bool:
|
|
89
|
+
"""Queues a task unless it was added before, returning whether it was new."""
|
|
90
|
+
if task.id in self._known:
|
|
91
|
+
return False
|
|
92
|
+
|
|
93
|
+
self._known.add(task.id)
|
|
94
|
+
self._queued.append(task)
|
|
95
|
+
|
|
96
|
+
return True
|
|
97
|
+
|
|
98
|
+
def shift(self) -> OutgoingTask | None:
|
|
99
|
+
return self._queued.popleft() if self._queued else None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class ScheduleHandle:
|
|
103
|
+
"""A schedule this agent requested, which follows its runs and follow-ups as the relay reports them."""
|
|
104
|
+
|
|
105
|
+
def __init__(
|
|
106
|
+
self,
|
|
107
|
+
id: str,
|
|
108
|
+
to: str,
|
|
109
|
+
link: ScheduleLink,
|
|
110
|
+
actions: list[ProposalAction] | None = None,
|
|
111
|
+
parent: ParentRef | None = None,
|
|
112
|
+
) -> None:
|
|
113
|
+
self.id = id
|
|
114
|
+
self.to = to
|
|
115
|
+
self.actions = actions or []
|
|
116
|
+
self.parent = parent
|
|
117
|
+
self._link = link
|
|
118
|
+
self._run_feed = TaskFeed()
|
|
119
|
+
self._follow_up_feed = TaskFeed()
|
|
120
|
+
self._changed = asyncio.Event()
|
|
121
|
+
self._ending = asyncio.Event()
|
|
122
|
+
self._reason = ""
|
|
123
|
+
self._closed = False
|
|
124
|
+
|
|
125
|
+
async def runs(self) -> AsyncIterator[OutgoingTask]:
|
|
126
|
+
async for run in self._drain(self._run_feed):
|
|
127
|
+
self._link.hand(run)
|
|
128
|
+
yield run
|
|
129
|
+
|
|
130
|
+
def follow_ups(self) -> AsyncIterator[OutgoingTask]:
|
|
131
|
+
return self._drain(self._follow_up_feed)
|
|
132
|
+
|
|
133
|
+
async def ended(self) -> str:
|
|
134
|
+
await self._ending.wait()
|
|
135
|
+
|
|
136
|
+
return self._reason
|
|
137
|
+
|
|
138
|
+
async def end(self, reason: str | None = None) -> None:
|
|
139
|
+
if self._closed:
|
|
140
|
+
return
|
|
141
|
+
|
|
142
|
+
self.close(reason if reason is not None else "The requester ended the schedule")
|
|
143
|
+
await self._link.post(
|
|
144
|
+
ScheduleEndEnvelope(
|
|
145
|
+
id=create_id(), to=self.to, schedule_id=self.id, reason=reason
|
|
146
|
+
)
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
def add(self, run: OutgoingTask) -> None:
|
|
150
|
+
"""Queues a run for `runs()`, unless it was added before."""
|
|
151
|
+
if self._run_feed.add(run):
|
|
152
|
+
self._notify()
|
|
153
|
+
|
|
154
|
+
def add_follow_up(self, task: OutgoingTask) -> None:
|
|
155
|
+
"""Queues a follow-up for `follow_ups()`, unless it was added before."""
|
|
156
|
+
if self._follow_up_feed.add(task):
|
|
157
|
+
self._notify()
|
|
158
|
+
|
|
159
|
+
def complete(self, provider: str, origin: ActionOrigin | None = None) -> None:
|
|
160
|
+
"""Marks the human's action for `provider` as taken, the one copied from the preparation `origin` when it's set."""
|
|
161
|
+
self.actions = [
|
|
162
|
+
action
|
|
163
|
+
for action in self.actions
|
|
164
|
+
if action.provider != provider or action.origin != origin
|
|
165
|
+
]
|
|
166
|
+
|
|
167
|
+
def require_access(self, action: ProposalAction) -> bool:
|
|
168
|
+
"""Waits on an action the executor requires in place of its own earlier one for the same provider.
|
|
169
|
+
|
|
170
|
+
Returns whether the schedule is still open.
|
|
171
|
+
"""
|
|
172
|
+
if self._closed:
|
|
173
|
+
return False
|
|
174
|
+
|
|
175
|
+
self.actions = [
|
|
176
|
+
*(
|
|
177
|
+
kept
|
|
178
|
+
for kept in self.actions
|
|
179
|
+
if kept.origin is not None or kept.provider != action.provider
|
|
180
|
+
),
|
|
181
|
+
action,
|
|
182
|
+
]
|
|
183
|
+
|
|
184
|
+
return True
|
|
185
|
+
|
|
186
|
+
def close(self, reason: str) -> None:
|
|
187
|
+
"""Ends the schedule without telling the executor, such as when the executor or relay ended it."""
|
|
188
|
+
if self._closed:
|
|
189
|
+
return
|
|
190
|
+
|
|
191
|
+
self._closed = True
|
|
192
|
+
self._reason = reason
|
|
193
|
+
self._ending.set()
|
|
194
|
+
self._link.release()
|
|
195
|
+
self._notify()
|
|
196
|
+
|
|
197
|
+
async def _drain(self, feed: TaskFeed) -> AsyncIterator[OutgoingTask]:
|
|
198
|
+
while feed or not self._closed:
|
|
199
|
+
if task := feed.shift():
|
|
200
|
+
yield task
|
|
201
|
+
else:
|
|
202
|
+
await self._changed.wait()
|
|
203
|
+
|
|
204
|
+
def _notify(self) -> None:
|
|
205
|
+
self._changed.set()
|
|
206
|
+
self._changed = asyncio.Event()
|