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,952 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import contextvars
|
|
3
|
+
import math
|
|
4
|
+
import time
|
|
5
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
6
|
+
from contextlib import aclosing
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, Protocol, TypeAlias, TypeVar, cast
|
|
9
|
+
|
|
10
|
+
from pydantic_core import to_jsonable_python
|
|
11
|
+
|
|
12
|
+
from agentjam._artifacts import (
|
|
13
|
+
ArtifactChunk,
|
|
14
|
+
ArtifactSource,
|
|
15
|
+
Backlog,
|
|
16
|
+
assert_artifact_key,
|
|
17
|
+
encode,
|
|
18
|
+
encode_upload,
|
|
19
|
+
)
|
|
20
|
+
from agentjam._attachments import AttachmentSource
|
|
21
|
+
from agentjam._content import LabeledContent, unlabel
|
|
22
|
+
from agentjam._errors import (
|
|
23
|
+
AgentJamError,
|
|
24
|
+
ReassignedError,
|
|
25
|
+
TaskCanceledError,
|
|
26
|
+
TaskCommittedError,
|
|
27
|
+
UncoveredCostError,
|
|
28
|
+
describe_error,
|
|
29
|
+
)
|
|
30
|
+
from agentjam._files import File
|
|
31
|
+
from agentjam._inputs import SchemaField, ValueProblem, parse_value
|
|
32
|
+
from agentjam._protocol import (
|
|
33
|
+
ArtifactEnvelope,
|
|
34
|
+
CommitEnvelope,
|
|
35
|
+
CompleteEnvelope,
|
|
36
|
+
CostDraft,
|
|
37
|
+
FailEnvelope,
|
|
38
|
+
TaskEndCode,
|
|
39
|
+
TaskEnvelope,
|
|
40
|
+
UpdateEnvelope,
|
|
41
|
+
)
|
|
42
|
+
from agentjam._relay.inputs import output_problem
|
|
43
|
+
from agentjam._signals import Signal, guard
|
|
44
|
+
from agentjam._tasks.access import AccessOptions
|
|
45
|
+
from agentjam._types import (
|
|
46
|
+
Account,
|
|
47
|
+
Attachment,
|
|
48
|
+
ConnectionFetch,
|
|
49
|
+
CostPlusPrice,
|
|
50
|
+
Delegate,
|
|
51
|
+
HistoryPage,
|
|
52
|
+
HistoryQuery,
|
|
53
|
+
IncomingMessage,
|
|
54
|
+
InputT,
|
|
55
|
+
JsonObject,
|
|
56
|
+
MessageReply,
|
|
57
|
+
OutputT,
|
|
58
|
+
Price,
|
|
59
|
+
SkillCard,
|
|
60
|
+
SkillHandler,
|
|
61
|
+
TaskInbox,
|
|
62
|
+
TaskRecap,
|
|
63
|
+
TriggerEvent,
|
|
64
|
+
)
|
|
65
|
+
from agentjam._utils import create_id, spawn
|
|
66
|
+
|
|
67
|
+
T = TypeVar("T")
|
|
68
|
+
|
|
69
|
+
TaskOutput: TypeAlias = ArtifactSource | list[ArtifactSource] | None
|
|
70
|
+
"""What `on_task` may return: nothing, one artifact source, or several to send in order."""
|
|
71
|
+
|
|
72
|
+
COST_REPORT_INTERVAL = 1.0
|
|
73
|
+
|
|
74
|
+
HOLD_MARKS = (0.5, 1.0)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class IncomingTask(Protocol):
|
|
78
|
+
"""A task this agent accepted. It's passed to `on_task` and available through `current_task()`."""
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def id(self) -> str:
|
|
82
|
+
"""The task's unique id."""
|
|
83
|
+
...
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def sender(self) -> str:
|
|
87
|
+
"""The agent that proposed the task."""
|
|
88
|
+
...
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def principal(self) -> str | None:
|
|
92
|
+
"""The human whose request started the task's chain, as their email or `guest:<agent>`, when the relay tracks one."""
|
|
93
|
+
...
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def text(self) -> str:
|
|
97
|
+
"""The requester's description of the task."""
|
|
98
|
+
...
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def skill(self) -> str | None:
|
|
102
|
+
"""The name of the skill the task calls for, if the requester named one."""
|
|
103
|
+
...
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def input(self) -> JsonObject | None:
|
|
107
|
+
"""The requester's structured input, which the relay validated against the skill's input schema."""
|
|
108
|
+
...
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def attachments(self) -> list[Attachment]:
|
|
112
|
+
"""The files the requester attached, already downloaded."""
|
|
113
|
+
...
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def previous(self) -> TaskRecap | None:
|
|
117
|
+
"""What the earlier task this one follows up on asked for and produced, when it's a follow-up."""
|
|
118
|
+
...
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def schedule_id(self) -> str | None:
|
|
122
|
+
"""The schedule this task is a run of, if any."""
|
|
123
|
+
...
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def run(self) -> int | None:
|
|
127
|
+
"""The run's number, starting from 1, if the task is a run of a schedule."""
|
|
128
|
+
...
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def event(self) -> TriggerEvent | None:
|
|
132
|
+
"""The trigger event that started this run, if it's a run of a trigger schedule."""
|
|
133
|
+
...
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def resumed(self) -> bool:
|
|
137
|
+
"""Whether another session of this agent started the task before it left, so the work may be partly done."""
|
|
138
|
+
...
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def attempt(self) -> int:
|
|
142
|
+
"""Which attempt at the task this is: 1 for the first, plus one for each time it resumed."""
|
|
143
|
+
...
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def held_cents(self) -> float | None:
|
|
147
|
+
"""What the relay holds from the requester for this task, in cents, which caps what it can charge until the hold grows.
|
|
148
|
+
|
|
149
|
+
It's None for free tasks and on relays that don't hold funds.
|
|
150
|
+
"""
|
|
151
|
+
...
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def cancellation(self) -> Exception | None:
|
|
155
|
+
"""Why the task stopped, such as a `TaskCanceledError` once its requester canceled it, or None while it runs.
|
|
156
|
+
|
|
157
|
+
`on_task` gets an `asyncio.CancelledError` at its next await once it's set. A `ReassignedError` means the task
|
|
158
|
+
moved to another session of this agent, after which nothing this session sends for it reaches the requester.
|
|
159
|
+
"""
|
|
160
|
+
...
|
|
161
|
+
|
|
162
|
+
async def update(self, text: str) -> None:
|
|
163
|
+
"""Sends a progress update to the requester. Does nothing once the task has ended.
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
text: The update to show the requester.
|
|
167
|
+
"""
|
|
168
|
+
...
|
|
169
|
+
|
|
170
|
+
async def send(
|
|
171
|
+
self,
|
|
172
|
+
text: str,
|
|
173
|
+
*,
|
|
174
|
+
conversation_id: str | None = None,
|
|
175
|
+
attachments: Sequence[AttachmentSource] | None = None,
|
|
176
|
+
timeout: float | None = None,
|
|
177
|
+
idempotency_key: str | None = None,
|
|
178
|
+
) -> MessageReply:
|
|
179
|
+
"""Sends the requester a message about this task and returns its reply, waiting until the task ends by default.
|
|
180
|
+
|
|
181
|
+
It reaches the session that proposed the task, in a conversation named after the task unless
|
|
182
|
+
`conversation_id` names another, since a human may need to answer.
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
text: The message to send.
|
|
186
|
+
conversation_id: The conversation to continue.
|
|
187
|
+
attachments: Files to attach, at most 10 of up to 100 MiB each.
|
|
188
|
+
timeout: How long to wait for the reply, in seconds. Defaults to waiting until the task ends.
|
|
189
|
+
idempotency_key: Makes retrying safe, since the requester answers a repeat instead of handling it twice.
|
|
190
|
+
Returns:
|
|
191
|
+
The requester's reply, with its files downloaded.
|
|
192
|
+
Raises:
|
|
193
|
+
AgentNotFoundError: If the session that proposed the task is gone.
|
|
194
|
+
TimeoutError: If `timeout` is set and no reply arrives within it.
|
|
195
|
+
"""
|
|
196
|
+
...
|
|
197
|
+
|
|
198
|
+
def open_inbox(self) -> TaskInbox:
|
|
199
|
+
"""Opens the task's inbox, so the requester's messages about the task queue up for the work in progress.
|
|
200
|
+
|
|
201
|
+
They no longer reach `on_message`, and each is answered right away with an acknowledgement. It closes once the task ends.
|
|
202
|
+
|
|
203
|
+
Returns:
|
|
204
|
+
The inbox, which every call shares.
|
|
205
|
+
"""
|
|
206
|
+
...
|
|
207
|
+
|
|
208
|
+
async def deliver(self, source: ArtifactSource) -> None:
|
|
209
|
+
"""Sends an artifact right away, streaming async iterables. Does nothing once the task has ended.
|
|
210
|
+
|
|
211
|
+
Requesters keep only the latest delivery of each key that `artifact()` names, so repeated deliveries replace it.
|
|
212
|
+
|
|
213
|
+
Args:
|
|
214
|
+
source: The artifact content, optionally labeled with `artifact()`.
|
|
215
|
+
Raises:
|
|
216
|
+
AgentJamError: If the artifact's key isn't a string of 1 to 256 characters, which also fails the task.
|
|
217
|
+
"""
|
|
218
|
+
...
|
|
219
|
+
|
|
220
|
+
def increment_cost(self, cost_cents: float) -> None:
|
|
221
|
+
"""Adds to the task's running cost, which a `cost_plus` skill charges plus its markup once the task ends.
|
|
222
|
+
|
|
223
|
+
A `cost_plus` task that never calls this fails instead of completing. A `cost_plus` task, or one the agent
|
|
224
|
+
proposed to itself, reports its running cost to the relay at most once a second.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
cost_cents: The cost to add in cents, at least 0 and as precise as a millionth of a cent, such as 0.0137.
|
|
228
|
+
Raises:
|
|
229
|
+
AgentJamError: If `cost_cents` isn't a finite number of at least 0.
|
|
230
|
+
"""
|
|
231
|
+
...
|
|
232
|
+
|
|
233
|
+
async def commit(self, *, cost_cents: float | None = None) -> None:
|
|
234
|
+
"""Commits to an action that can't be undone, such as a purchase, after which the requester can't cancel the task.
|
|
235
|
+
|
|
236
|
+
Only an irreversible skill's tasks can commit, and a `cost_plus` one first grows `held_cents` to cover its
|
|
237
|
+
running cost with the action's cost added, plus the skill's markup.
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
cost_cents: The action's cost in cents, added to the running cost once the commit is recorded.
|
|
241
|
+
Raises:
|
|
242
|
+
UncoveredCostError: If the requester can't fund the cost plus the skill's markup, which commits nothing.
|
|
243
|
+
AgentJamError: If the skill isn't irreversible, the task has ended, or a `cost_plus` task has no cost.
|
|
244
|
+
"""
|
|
245
|
+
...
|
|
246
|
+
|
|
247
|
+
async def credentials(self, provider: str, name: str | None = None) -> str:
|
|
248
|
+
"""Gets an access token for the requester's account with `provider`, refreshing it when it expired.
|
|
249
|
+
|
|
250
|
+
Args:
|
|
251
|
+
provider: A provider in the `connections` of the task's skill.
|
|
252
|
+
name: The token to get, such as Slack's `user` token, for a provider that issues several.
|
|
253
|
+
Returns:
|
|
254
|
+
A current access token.
|
|
255
|
+
Raises:
|
|
256
|
+
ConnectionRevokedError: If the account is no longer connected.
|
|
257
|
+
AgentJamError: If the task's skill declares no connection to `provider`, or the grant has no token named `name`.
|
|
258
|
+
"""
|
|
259
|
+
...
|
|
260
|
+
|
|
261
|
+
async def account(self, provider: str) -> Account | None:
|
|
262
|
+
"""Gets the requester's account with `provider`, such as their Slack workspace and user.
|
|
263
|
+
|
|
264
|
+
Args:
|
|
265
|
+
provider: A provider in the `connections` of the task's skill.
|
|
266
|
+
Returns:
|
|
267
|
+
The account, or None if the connection doesn't know it.
|
|
268
|
+
Raises:
|
|
269
|
+
ConnectionRevokedError: If the account is no longer connected.
|
|
270
|
+
AgentJamError: If the task's skill declares no connection to `provider`.
|
|
271
|
+
"""
|
|
272
|
+
...
|
|
273
|
+
|
|
274
|
+
async def require_access(
|
|
275
|
+
self,
|
|
276
|
+
provider: str,
|
|
277
|
+
*,
|
|
278
|
+
reason: str,
|
|
279
|
+
verify: Callable[[], Awaitable[bool] | bool],
|
|
280
|
+
url: str | None = None,
|
|
281
|
+
) -> None:
|
|
282
|
+
"""Asks the requester's human for access the task turned out to lack, then waits until `verify` passes.
|
|
283
|
+
|
|
284
|
+
The relay passes the link up the chain to the human, so nothing needs relaying. Gather and verify all
|
|
285
|
+
access before `commit()`, since a committed task can't wait on the human.
|
|
286
|
+
|
|
287
|
+
Args:
|
|
288
|
+
provider: A provider in the `connections` of the task's skill.
|
|
289
|
+
reason: What the human must do, shown beside the link, such as "Give the app access to acme/api".
|
|
290
|
+
verify: Checks whether the task has the access it needs yet, such as by fetching what it lacked.
|
|
291
|
+
url: Where the human grants the access. Defaults to the connection's own page for it.
|
|
292
|
+
Raises:
|
|
293
|
+
TaskCanceledError: If the human didn't act within an hour, or the requester canceled the task.
|
|
294
|
+
TaskCommittedError: If the task was committed, which also fails the task.
|
|
295
|
+
AgentJamError: If the task has ended, its skill declares no connection to `provider`, or no link is known.
|
|
296
|
+
"""
|
|
297
|
+
...
|
|
298
|
+
|
|
299
|
+
def connection_fetch(self, provider: str) -> ConnectionFetch:
|
|
300
|
+
"""Returns a fetch that sends requests to a secret connection's provider through the platform's proxy.
|
|
301
|
+
|
|
302
|
+
The proxy adds the human's credential, so the agent never sees it. Pass a path under the credential's base URL,
|
|
303
|
+
such as `/api/search`, or a full URL under it.
|
|
304
|
+
|
|
305
|
+
Args:
|
|
306
|
+
provider: A provider in the secret `connections` of the task's skill.
|
|
307
|
+
Returns:
|
|
308
|
+
A fetch that raises `ConnectionRevokedError` once the credential is gone and `RequestRefusedError` for requests the platform refuses.
|
|
309
|
+
Raises:
|
|
310
|
+
AgentJamError: If the task's skill declares no secret connection to `provider`.
|
|
311
|
+
"""
|
|
312
|
+
...
|
|
313
|
+
|
|
314
|
+
async def connection_config(self, provider: str) -> dict[str, str]:
|
|
315
|
+
"""Gets the non-secret fields the human entered for a secret connection, such as their Grafana URL.
|
|
316
|
+
|
|
317
|
+
Args:
|
|
318
|
+
provider: A provider in the secret `connections` of the task's skill.
|
|
319
|
+
Returns:
|
|
320
|
+
The non-secret fields by name.
|
|
321
|
+
Raises:
|
|
322
|
+
ConnectionRevokedError: If the credential is gone.
|
|
323
|
+
AgentJamError: If the task's skill declares no secret connection to `provider`.
|
|
324
|
+
"""
|
|
325
|
+
...
|
|
326
|
+
|
|
327
|
+
async def prepare(self, delegates: list[Delegate]) -> None:
|
|
328
|
+
"""Asks agents this task is about to hand work off to for the accounts their skills need.
|
|
329
|
+
|
|
330
|
+
The requester's human connects them now rather than once each handoff starts, so prepare only the delegates
|
|
331
|
+
the task will use. Does nothing once the task has ended, and reports the ones that couldn't prepare to `on_error`.
|
|
332
|
+
|
|
333
|
+
Args:
|
|
334
|
+
delegates: The agents and the skills of theirs the task will call for.
|
|
335
|
+
"""
|
|
336
|
+
...
|
|
337
|
+
|
|
338
|
+
async def list_history(
|
|
339
|
+
self, *, cursor: str | None = None, limit: int | None = None
|
|
340
|
+
) -> HistoryPage:
|
|
341
|
+
"""Lists the ended tasks this agent ran before this one, newest first.
|
|
342
|
+
|
|
343
|
+
That's earlier runs of its schedule for a run, or earlier tasks of its skill for the same human for a one-off.
|
|
344
|
+
Recall what any of them produced with `recall_task()`.
|
|
345
|
+
|
|
346
|
+
Args:
|
|
347
|
+
cursor: The `next` of an earlier page.
|
|
348
|
+
limit: The page size.
|
|
349
|
+
Returns:
|
|
350
|
+
A page of past tasks, with `next` set when older ones remain.
|
|
351
|
+
Raises:
|
|
352
|
+
AgentJamError: If the relay doesn't keep tasks, or the query is invalid.
|
|
353
|
+
"""
|
|
354
|
+
...
|
|
355
|
+
|
|
356
|
+
def get_input(self, skill: SkillHandler[InputT, Any]) -> InputT:
|
|
357
|
+
"""Gets the task's input as the skill's input schema parsed it before the task was accepted.
|
|
358
|
+
|
|
359
|
+
Args:
|
|
360
|
+
skill: The skill the task calls for, with its `input` schema.
|
|
361
|
+
Returns:
|
|
362
|
+
The requester's input, parsed.
|
|
363
|
+
Raises:
|
|
364
|
+
AgentJamError: If the task calls for another skill, or this process wasn't connected with the skill's input schema.
|
|
365
|
+
"""
|
|
366
|
+
...
|
|
367
|
+
|
|
368
|
+
async def set_output(
|
|
369
|
+
self, skill: SkillHandler[Any, OutputT], value: OutputT
|
|
370
|
+
) -> None:
|
|
371
|
+
"""Sets the task's structured output, which the requester reads with `get_output()` once the task completes.
|
|
372
|
+
|
|
373
|
+
A task whose skill has an output schema must set it before it completes, and setting it again replaces it.
|
|
374
|
+
|
|
375
|
+
Args:
|
|
376
|
+
skill: The skill the task calls for, with its `output` schema.
|
|
377
|
+
value: The output, matching the schema.
|
|
378
|
+
Raises:
|
|
379
|
+
AgentJamError: If the task calls for another skill, or the schema refuses the output.
|
|
380
|
+
"""
|
|
381
|
+
...
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
class TaskSender(Protocol):
|
|
385
|
+
"""Sends a message about one task to the agent on its other side."""
|
|
386
|
+
|
|
387
|
+
async def __call__(
|
|
388
|
+
self,
|
|
389
|
+
text: str,
|
|
390
|
+
*,
|
|
391
|
+
conversation_id: str | None = None,
|
|
392
|
+
attachments: Sequence[AttachmentSource] | None = None,
|
|
393
|
+
steer: bool = False,
|
|
394
|
+
timeout: float | None = None,
|
|
395
|
+
idempotency_key: str | None = None,
|
|
396
|
+
) -> MessageReply: ...
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
@dataclass(frozen=True)
|
|
400
|
+
class ConnectionAccess:
|
|
401
|
+
"""How a task or schedule reaches the accounts its skill's connections hold."""
|
|
402
|
+
|
|
403
|
+
credentials: Callable[[str, str | None], Awaitable[str]]
|
|
404
|
+
account: Callable[[str], Awaitable[Account | None]]
|
|
405
|
+
connection_fetch: Callable[[str], ConnectionFetch]
|
|
406
|
+
connection_config: Callable[[str], Awaitable[dict[str, str]]]
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
@dataclass(frozen=True)
|
|
410
|
+
class ParsedInput:
|
|
411
|
+
"""A task's input as its skill's input schema parsed it."""
|
|
412
|
+
|
|
413
|
+
value: Any
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
@dataclass(frozen=True, kw_only=True)
|
|
417
|
+
class TaskDetails:
|
|
418
|
+
id: str
|
|
419
|
+
sender: str
|
|
420
|
+
text: str
|
|
421
|
+
access: ConnectionAccess
|
|
422
|
+
principal: str | None = None
|
|
423
|
+
skill: str | None = None
|
|
424
|
+
input: JsonObject | None = None
|
|
425
|
+
parsed_input: ParsedInput | None = None
|
|
426
|
+
attachments: list[Attachment] = field(default_factory=list)
|
|
427
|
+
previous: TaskRecap | None = None
|
|
428
|
+
schedule_id: str | None = None
|
|
429
|
+
run: int | None = None
|
|
430
|
+
event: TriggerEvent | None = None
|
|
431
|
+
attempt: int = 1
|
|
432
|
+
resumable: bool = False
|
|
433
|
+
"""Whether another session of this agent picks the task up once this one leaves, rather than it failing."""
|
|
434
|
+
price: Price | None = None
|
|
435
|
+
card: SkillCard | None = None
|
|
436
|
+
is_self: bool = False
|
|
437
|
+
held_cents: float | None = None
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
@dataclass(frozen=True)
|
|
441
|
+
class ExecutionLink:
|
|
442
|
+
post: Callable[[TaskEnvelope | CostDraft], Awaitable[None]]
|
|
443
|
+
send: TaskSender
|
|
444
|
+
upload: Callable[[File, Signal], Awaitable[str | None]]
|
|
445
|
+
"""Uploads a file artifact, returning None when the relay can't store files."""
|
|
446
|
+
prepare: Callable[[list[Delegate]], Awaitable[None]]
|
|
447
|
+
list_history: Callable[[HistoryQuery], Awaitable[HistoryPage]]
|
|
448
|
+
require_access: Callable[[str, AccessOptions, Signal], Awaitable[None]]
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
current: contextvars.ContextVar["TaskExecution | None"] = contextvars.ContextVar(
|
|
452
|
+
"agentjam_task", default=None
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def current_task() -> IncomingTask | None:
|
|
457
|
+
"""Looks up the task being executed in the current context.
|
|
458
|
+
|
|
459
|
+
Returns:
|
|
460
|
+
The current task, or None outside a task.
|
|
461
|
+
"""
|
|
462
|
+
return current.get()
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def current_execution() -> "TaskExecution | None":
|
|
466
|
+
return current.get()
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def to_sources(output: TaskOutput) -> list[ArtifactSource]:
|
|
470
|
+
if output is None:
|
|
471
|
+
return []
|
|
472
|
+
|
|
473
|
+
return output if isinstance(output, list) else [output]
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def parse_output(skill: SkillHandler[Any, OutputT], output: JsonObject) -> OutputT:
|
|
477
|
+
if skill.output is None:
|
|
478
|
+
raise AgentJamError(
|
|
479
|
+
f'The "{skill.name}" skill has no output schema to parse its output with'
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
parsed = parse_value(skill.name, "output", skill.output, output)
|
|
483
|
+
if isinstance(parsed, ValueProblem):
|
|
484
|
+
raise AgentJamError(parsed.problem)
|
|
485
|
+
|
|
486
|
+
return cast(OutputT, parsed.value)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
class Inbox:
|
|
490
|
+
"""The requester's messages about a running task, queued until the work in progress takes them."""
|
|
491
|
+
|
|
492
|
+
def __init__(self) -> None:
|
|
493
|
+
self._messages: list[IncomingMessage] = []
|
|
494
|
+
|
|
495
|
+
def take(self) -> list[IncomingMessage]:
|
|
496
|
+
taken, self._messages = self._messages, []
|
|
497
|
+
|
|
498
|
+
return taken
|
|
499
|
+
|
|
500
|
+
def push(self, message: IncomingMessage) -> None:
|
|
501
|
+
self._messages.append(message)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
class TaskExecution:
|
|
505
|
+
"""A task this agent runs, which reports its progress and outcome to the requester.
|
|
506
|
+
|
|
507
|
+
Invariant: a task sends exactly one terminal envelope, and `task.complete` follows the last chunk of every
|
|
508
|
+
delivered artifact. A `task.update` follows every streamed piece read before it was sent. Nothing is sent
|
|
509
|
+
once the task has ended.
|
|
510
|
+
"""
|
|
511
|
+
|
|
512
|
+
def __init__(self, details: TaskDetails, link: ExecutionLink) -> None:
|
|
513
|
+
self.id = details.id
|
|
514
|
+
self.sender = details.sender
|
|
515
|
+
self.principal = details.principal
|
|
516
|
+
self.text = details.text
|
|
517
|
+
self.skill = details.skill
|
|
518
|
+
self.input = details.input
|
|
519
|
+
self.attachments = details.attachments
|
|
520
|
+
self.previous = details.previous
|
|
521
|
+
self.schedule_id = details.schedule_id
|
|
522
|
+
self.run = details.run
|
|
523
|
+
self.event = details.event
|
|
524
|
+
self.attempt = details.attempt
|
|
525
|
+
self.resumable = details.resumable
|
|
526
|
+
self.signal = Signal()
|
|
527
|
+
self._access = details.access
|
|
528
|
+
self._parsed_input = details.parsed_input
|
|
529
|
+
self._price = details.price
|
|
530
|
+
self._card = details.card
|
|
531
|
+
self._is_self = details.is_self
|
|
532
|
+
self._held = details.held_cents
|
|
533
|
+
self._link = link
|
|
534
|
+
self._deliveries: list[asyncio.Task[None]] = []
|
|
535
|
+
self._backlogs: set[Backlog] = set()
|
|
536
|
+
self._settled = asyncio.Event()
|
|
537
|
+
self._ended = False
|
|
538
|
+
self._cost_cents: float | None = None
|
|
539
|
+
self._reported_cents = 0.0
|
|
540
|
+
self._reported_at = -math.inf
|
|
541
|
+
self._cost_report: asyncio.TimerHandle | None = None
|
|
542
|
+
self._inbox: Inbox | None = None
|
|
543
|
+
self._output: JsonObject | None = None
|
|
544
|
+
|
|
545
|
+
@property
|
|
546
|
+
def resumed(self) -> bool:
|
|
547
|
+
return self.attempt > 1
|
|
548
|
+
|
|
549
|
+
@property
|
|
550
|
+
def held_cents(self) -> float | None:
|
|
551
|
+
return self._held
|
|
552
|
+
|
|
553
|
+
@property
|
|
554
|
+
def cancellation(self) -> Exception | None:
|
|
555
|
+
reason = self.signal.reason
|
|
556
|
+
|
|
557
|
+
return reason if isinstance(reason, Exception) else None
|
|
558
|
+
|
|
559
|
+
def set_held_cents(self, held_cents: float) -> None:
|
|
560
|
+
"""Records what the relay holds for the task once its hold changed."""
|
|
561
|
+
self._held = held_cents
|
|
562
|
+
|
|
563
|
+
async def wait_settled(self) -> None:
|
|
564
|
+
"""Waits until the task has ended and its terminal envelope, if any, has been sent."""
|
|
565
|
+
await self._settled.wait()
|
|
566
|
+
|
|
567
|
+
async def update(self, text: str) -> None:
|
|
568
|
+
await asyncio.gather(*(backlog.wait_for_sent() for backlog in self._backlogs))
|
|
569
|
+
|
|
570
|
+
if self._ended:
|
|
571
|
+
return
|
|
572
|
+
|
|
573
|
+
await self._post(
|
|
574
|
+
UpdateEnvelope(id=create_id(), to=self.sender, task_id=self.id, text=text)
|
|
575
|
+
)
|
|
576
|
+
|
|
577
|
+
async def send(
|
|
578
|
+
self,
|
|
579
|
+
text: str,
|
|
580
|
+
*,
|
|
581
|
+
conversation_id: str | None = None,
|
|
582
|
+
attachments: Sequence[AttachmentSource] | None = None,
|
|
583
|
+
timeout: float | None = None,
|
|
584
|
+
idempotency_key: str | None = None,
|
|
585
|
+
) -> MessageReply:
|
|
586
|
+
return await self._fence_request(
|
|
587
|
+
self._link.send(
|
|
588
|
+
text,
|
|
589
|
+
conversation_id=conversation_id,
|
|
590
|
+
attachments=attachments,
|
|
591
|
+
timeout=timeout,
|
|
592
|
+
idempotency_key=idempotency_key,
|
|
593
|
+
)
|
|
594
|
+
)
|
|
595
|
+
|
|
596
|
+
def open_inbox(self) -> TaskInbox:
|
|
597
|
+
if self._inbox is None:
|
|
598
|
+
self._inbox = Inbox()
|
|
599
|
+
|
|
600
|
+
return self._inbox
|
|
601
|
+
|
|
602
|
+
def queue_message(self, message: IncomingMessage) -> bool:
|
|
603
|
+
"""Queues a requester's message about the task for the work in progress, returning whether its open inbox took it."""
|
|
604
|
+
if self._ended or self._inbox is None:
|
|
605
|
+
return False
|
|
606
|
+
|
|
607
|
+
self._inbox.push(message)
|
|
608
|
+
|
|
609
|
+
return True
|
|
610
|
+
|
|
611
|
+
async def prepare(self, delegates: list[Delegate]) -> None:
|
|
612
|
+
if not self._ended:
|
|
613
|
+
await self._link.prepare(delegates)
|
|
614
|
+
|
|
615
|
+
async def list_history(
|
|
616
|
+
self, *, cursor: str | None = None, limit: int | None = None
|
|
617
|
+
) -> HistoryPage:
|
|
618
|
+
return await self._link.list_history(HistoryQuery(cursor=cursor, limit=limit))
|
|
619
|
+
|
|
620
|
+
async def credentials(self, provider: str, name: str | None = None) -> str:
|
|
621
|
+
return await self._access.credentials(provider, name)
|
|
622
|
+
|
|
623
|
+
async def account(self, provider: str) -> Account | None:
|
|
624
|
+
return await self._access.account(provider)
|
|
625
|
+
|
|
626
|
+
def connection_fetch(self, provider: str) -> ConnectionFetch:
|
|
627
|
+
return self._access.connection_fetch(provider)
|
|
628
|
+
|
|
629
|
+
async def connection_config(self, provider: str) -> dict[str, str]:
|
|
630
|
+
return await self._access.connection_config(provider)
|
|
631
|
+
|
|
632
|
+
async def require_access(
|
|
633
|
+
self,
|
|
634
|
+
provider: str,
|
|
635
|
+
*,
|
|
636
|
+
reason: str,
|
|
637
|
+
verify: Callable[[], Awaitable[bool] | bool],
|
|
638
|
+
url: str | None = None,
|
|
639
|
+
) -> None:
|
|
640
|
+
if self._ended:
|
|
641
|
+
raise AgentJamError(
|
|
642
|
+
f'Task "{self.id}" has ended, so it can\'t require access'
|
|
643
|
+
)
|
|
644
|
+
|
|
645
|
+
options = AccessOptions(reason=reason, verify=verify, url=url)
|
|
646
|
+
|
|
647
|
+
try:
|
|
648
|
+
await self._link.require_access(provider, options, self.signal)
|
|
649
|
+
except TaskCommittedError as error:
|
|
650
|
+
await self.fail(error)
|
|
651
|
+
raise
|
|
652
|
+
|
|
653
|
+
def increment_cost(self, cost_cents: float) -> None:
|
|
654
|
+
self._cost_cents = self._compute_cost(cost_cents)
|
|
655
|
+
self._schedule_cost_report()
|
|
656
|
+
|
|
657
|
+
async def commit(self, *, cost_cents: float | None = None) -> None:
|
|
658
|
+
if self._ended:
|
|
659
|
+
raise AgentJamError(
|
|
660
|
+
f'Task "{self.id}" has ended, so it can\'t be committed'
|
|
661
|
+
)
|
|
662
|
+
|
|
663
|
+
total = (
|
|
664
|
+
self._cost_cents if cost_cents is None else self._compute_cost(cost_cents)
|
|
665
|
+
)
|
|
666
|
+
is_cost_plus = isinstance(self._price, CostPlusPrice)
|
|
667
|
+
|
|
668
|
+
if is_cost_plus and total is None:
|
|
669
|
+
raise AgentJamError(
|
|
670
|
+
f'The "{self.skill}" skill is priced cost-plus, so commit() must pass the cost_cents being committed to'
|
|
671
|
+
)
|
|
672
|
+
|
|
673
|
+
await self._post(
|
|
674
|
+
CommitEnvelope(
|
|
675
|
+
id=create_id(),
|
|
676
|
+
to=self.sender,
|
|
677
|
+
task_id=self.id,
|
|
678
|
+
cost_cents=total if is_cost_plus else None,
|
|
679
|
+
)
|
|
680
|
+
)
|
|
681
|
+
|
|
682
|
+
self._cost_cents = total
|
|
683
|
+
|
|
684
|
+
def get_input(self, skill: SkillHandler[InputT, Any]) -> InputT:
|
|
685
|
+
self._assert_skill(skill.name, "input")
|
|
686
|
+
|
|
687
|
+
if self._parsed_input is None:
|
|
688
|
+
raise AgentJamError(
|
|
689
|
+
f'Pass the "{skill.name}" skill with its input schema to connect() to read its tasks\' input'
|
|
690
|
+
)
|
|
691
|
+
|
|
692
|
+
return cast(InputT, self._parsed_input.value)
|
|
693
|
+
|
|
694
|
+
async def set_output(
|
|
695
|
+
self, skill: SkillHandler[Any, OutputT], value: OutputT
|
|
696
|
+
) -> None:
|
|
697
|
+
self._assert_skill(skill.name, "output")
|
|
698
|
+
|
|
699
|
+
output = to_jsonable_python(value)
|
|
700
|
+
parse_output(skill, output)
|
|
701
|
+
|
|
702
|
+
self._output = output
|
|
703
|
+
|
|
704
|
+
async def deliver(self, source: ArtifactSource) -> None:
|
|
705
|
+
try:
|
|
706
|
+
assert_artifact_key(unlabel(source).key)
|
|
707
|
+
except AgentJamError as error:
|
|
708
|
+
# WARNING: failing the task cancels its work, so the caller must see the refusal before that failure runs.
|
|
709
|
+
self._deliveries.append(spawn(self.fail(error)))
|
|
710
|
+
raise
|
|
711
|
+
|
|
712
|
+
stream = asyncio.ensure_future(guard(self._stream(source), self.signal))
|
|
713
|
+
self._deliveries.append(spawn(self._fail_on_error(stream)))
|
|
714
|
+
await asyncio.shield(stream)
|
|
715
|
+
|
|
716
|
+
async def perform(
|
|
717
|
+
self, work: Callable[["TaskExecution"], Awaitable[TaskOutput]]
|
|
718
|
+
) -> None:
|
|
719
|
+
"""Runs `work` with this task as the current one, raced against its signal, then completes or fails the task."""
|
|
720
|
+
if self._ended:
|
|
721
|
+
return
|
|
722
|
+
|
|
723
|
+
context = contextvars.copy_context()
|
|
724
|
+
context.run(current.set, self)
|
|
725
|
+
|
|
726
|
+
try:
|
|
727
|
+
await guard(
|
|
728
|
+
asyncio.create_task(self._run(work), context=context), self.signal
|
|
729
|
+
)
|
|
730
|
+
|
|
731
|
+
if isinstance(self._price, CostPlusPrice) and self._cost_cents is None:
|
|
732
|
+
raise AgentJamError(
|
|
733
|
+
f'The "{self.skill}" skill is priced cost-plus, so its tasks must call increment_cost() before they complete'
|
|
734
|
+
)
|
|
735
|
+
|
|
736
|
+
if problem := output_problem(self._output, self._card):
|
|
737
|
+
raise AgentJamError(problem)
|
|
738
|
+
|
|
739
|
+
await self._report_cost()
|
|
740
|
+
|
|
741
|
+
if self._finish():
|
|
742
|
+
await self._settle(
|
|
743
|
+
CompleteEnvelope(
|
|
744
|
+
id=create_id(),
|
|
745
|
+
to=self.sender,
|
|
746
|
+
task_id=self.id,
|
|
747
|
+
cost_cents=self._cost_cents,
|
|
748
|
+
output=self._output,
|
|
749
|
+
)
|
|
750
|
+
)
|
|
751
|
+
except Exception as error:
|
|
752
|
+
await self.fail(error)
|
|
753
|
+
|
|
754
|
+
async def fail(self, error: Exception) -> None:
|
|
755
|
+
if not self._finish():
|
|
756
|
+
return
|
|
757
|
+
|
|
758
|
+
self.signal.abort(error)
|
|
759
|
+
await self._settle(
|
|
760
|
+
FailEnvelope(
|
|
761
|
+
id=create_id(),
|
|
762
|
+
to=self.sender,
|
|
763
|
+
task_id=self.id,
|
|
764
|
+
error=describe_error(error),
|
|
765
|
+
uncovered=error.code if isinstance(error, UncoveredCostError) else None,
|
|
766
|
+
)
|
|
767
|
+
)
|
|
768
|
+
|
|
769
|
+
def cancel(self, reason: str | None, code: TaskEndCode | None = None) -> None:
|
|
770
|
+
self.abandon(
|
|
771
|
+
TaskCanceledError(
|
|
772
|
+
reason if reason is not None else f"{self.sender} canceled the task",
|
|
773
|
+
code,
|
|
774
|
+
)
|
|
775
|
+
)
|
|
776
|
+
|
|
777
|
+
def abandon(self, error: AgentJamError) -> None:
|
|
778
|
+
"""Ends the task in this session without telling the requester, aborting its signal with `error`."""
|
|
779
|
+
if not self._finish():
|
|
780
|
+
return
|
|
781
|
+
|
|
782
|
+
self.signal.abort(error)
|
|
783
|
+
self._settled.set()
|
|
784
|
+
|
|
785
|
+
async def _run(
|
|
786
|
+
self, work: Callable[["TaskExecution"], Awaitable[TaskOutput]]
|
|
787
|
+
) -> None:
|
|
788
|
+
for source in to_sources(await work(self)):
|
|
789
|
+
await self.deliver(source)
|
|
790
|
+
|
|
791
|
+
for delivery in self._deliveries:
|
|
792
|
+
await delivery
|
|
793
|
+
|
|
794
|
+
async def _fail_on_error(self, stream: asyncio.Future[None]) -> None:
|
|
795
|
+
try:
|
|
796
|
+
await stream
|
|
797
|
+
except Exception as error:
|
|
798
|
+
await self.fail(error)
|
|
799
|
+
|
|
800
|
+
async def _settle(self, envelope: TaskEnvelope) -> None:
|
|
801
|
+
try:
|
|
802
|
+
await self._post(envelope)
|
|
803
|
+
finally:
|
|
804
|
+
self._settled.set()
|
|
805
|
+
|
|
806
|
+
async def _post(self, envelope: TaskEnvelope | CostDraft) -> None:
|
|
807
|
+
await self._fence_request(self._link.post(envelope))
|
|
808
|
+
|
|
809
|
+
async def _fence_request(self, request: Awaitable[T]) -> T:
|
|
810
|
+
"""Abandons the task once the relay refuses `request` because the task moved to another session."""
|
|
811
|
+
try:
|
|
812
|
+
return await request
|
|
813
|
+
except ReassignedError as error:
|
|
814
|
+
self.abandon(error)
|
|
815
|
+
raise
|
|
816
|
+
|
|
817
|
+
def _compute_cost(self, increment: float) -> float:
|
|
818
|
+
if not math.isfinite(increment) or increment < 0:
|
|
819
|
+
raise AgentJamError(
|
|
820
|
+
f"A task's cost increment must be a finite number of cents of at least 0, not {increment}"
|
|
821
|
+
)
|
|
822
|
+
|
|
823
|
+
return (self._cost_cents or 0) + increment
|
|
824
|
+
|
|
825
|
+
@property
|
|
826
|
+
def _is_cost_reported(self) -> bool:
|
|
827
|
+
"""Whether the relay tracks the running cost: for a `cost_plus` skill, or a task the agent proposed to itself."""
|
|
828
|
+
return isinstance(self._price, CostPlusPrice) or self._is_self
|
|
829
|
+
|
|
830
|
+
def _schedule_cost_report(self) -> None:
|
|
831
|
+
if not self._is_cost_reported or self._ended:
|
|
832
|
+
return
|
|
833
|
+
|
|
834
|
+
if self._count_marks(self._cost_cents) > self._count_marks(
|
|
835
|
+
self._reported_cents
|
|
836
|
+
):
|
|
837
|
+
self._send_cost_report()
|
|
838
|
+
return
|
|
839
|
+
|
|
840
|
+
delay = self._reported_at + COST_REPORT_INTERVAL - time.monotonic()
|
|
841
|
+
if self._cost_report is None:
|
|
842
|
+
self._cost_report = asyncio.get_running_loop().call_later(
|
|
843
|
+
max(0.0, delay), self._send_cost_report
|
|
844
|
+
)
|
|
845
|
+
|
|
846
|
+
def _send_cost_report(self) -> None:
|
|
847
|
+
spawn(self._report_cost_or_fail())
|
|
848
|
+
|
|
849
|
+
async def _report_cost_or_fail(self) -> None:
|
|
850
|
+
try:
|
|
851
|
+
await self._report_cost()
|
|
852
|
+
except Exception as error:
|
|
853
|
+
await self.fail(error)
|
|
854
|
+
|
|
855
|
+
async def _report_cost(self) -> None:
|
|
856
|
+
self._cancel_cost_report()
|
|
857
|
+
|
|
858
|
+
cost_cents = self._cost_cents or 0
|
|
859
|
+
is_unreported = self._is_cost_reported and cost_cents != self._reported_cents
|
|
860
|
+
|
|
861
|
+
if self._ended or not is_unreported:
|
|
862
|
+
return
|
|
863
|
+
|
|
864
|
+
self._reported_cents = cost_cents
|
|
865
|
+
self._reported_at = time.monotonic()
|
|
866
|
+
await self._post(
|
|
867
|
+
CostDraft(
|
|
868
|
+
id=create_id(), to=self.sender, task_id=self.id, cost_cents=cost_cents
|
|
869
|
+
)
|
|
870
|
+
)
|
|
871
|
+
|
|
872
|
+
def _count_marks(self, cost_cents: float | None) -> int:
|
|
873
|
+
"""Counts the marks of the hold, half and all of it, that the charge for `cost_cents` reached."""
|
|
874
|
+
if not isinstance(self._price, CostPlusPrice) or self._held is None:
|
|
875
|
+
return 0
|
|
876
|
+
|
|
877
|
+
charge = (cost_cents or 0) * (1 + self._price.markup_bps / 10_000)
|
|
878
|
+
|
|
879
|
+
return sum(1 for mark in HOLD_MARKS if charge >= mark * self._held)
|
|
880
|
+
|
|
881
|
+
def _assert_skill(self, name: str, field: SchemaField) -> None:
|
|
882
|
+
if self.skill == name:
|
|
883
|
+
return
|
|
884
|
+
|
|
885
|
+
called = f'the "{self.skill}" skill' if self.skill else "no skill"
|
|
886
|
+
raise AgentJamError(
|
|
887
|
+
f'The task calls for {called}, so it has no "{name}" {field}'
|
|
888
|
+
)
|
|
889
|
+
|
|
890
|
+
def _finish(self) -> bool:
|
|
891
|
+
was_running = not self._ended
|
|
892
|
+
self._ended = True
|
|
893
|
+
self._cancel_cost_report()
|
|
894
|
+
|
|
895
|
+
return was_running
|
|
896
|
+
|
|
897
|
+
def _cancel_cost_report(self) -> None:
|
|
898
|
+
if self._cost_report is not None:
|
|
899
|
+
self._cost_report.cancel()
|
|
900
|
+
self._cost_report = None
|
|
901
|
+
|
|
902
|
+
async def _stream(self, source: ArtifactSource) -> None:
|
|
903
|
+
labeled = unlabel(source)
|
|
904
|
+
if isinstance(labeled.content, File) and await self._send_upload(
|
|
905
|
+
labeled.content, labeled
|
|
906
|
+
):
|
|
907
|
+
return
|
|
908
|
+
|
|
909
|
+
backlog = Backlog()
|
|
910
|
+
self._backlogs.add(backlog)
|
|
911
|
+
|
|
912
|
+
try:
|
|
913
|
+
async with aclosing(encode(source, backlog)) as chunks:
|
|
914
|
+
async for chunk in chunks:
|
|
915
|
+
if self._ended:
|
|
916
|
+
return
|
|
917
|
+
|
|
918
|
+
await self._post(self._construct_artifact(chunk))
|
|
919
|
+
finally:
|
|
920
|
+
self._backlogs.discard(backlog)
|
|
921
|
+
backlog.close()
|
|
922
|
+
|
|
923
|
+
async def _send_upload(self, file: File, labels: LabeledContent) -> bool:
|
|
924
|
+
try:
|
|
925
|
+
upload_id = await self._link.upload(file, self.signal)
|
|
926
|
+
if upload_id is None:
|
|
927
|
+
return False
|
|
928
|
+
|
|
929
|
+
if not self._ended:
|
|
930
|
+
await self._post(
|
|
931
|
+
self._construct_artifact(encode_upload(file, labels, upload_id))
|
|
932
|
+
)
|
|
933
|
+
except Exception:
|
|
934
|
+
if not self._ended:
|
|
935
|
+
raise
|
|
936
|
+
|
|
937
|
+
return True
|
|
938
|
+
|
|
939
|
+
def _construct_artifact(self, chunk: ArtifactChunk) -> ArtifactEnvelope:
|
|
940
|
+
return ArtifactEnvelope(
|
|
941
|
+
id=create_id(),
|
|
942
|
+
to=self.sender,
|
|
943
|
+
task_id=self.id,
|
|
944
|
+
artifact_id=chunk.artifact_id,
|
|
945
|
+
kind=chunk.kind,
|
|
946
|
+
name=chunk.name,
|
|
947
|
+
mime_type=chunk.mime_type,
|
|
948
|
+
key=chunk.key,
|
|
949
|
+
chunk=chunk.chunk,
|
|
950
|
+
last=chunk.last,
|
|
951
|
+
upload_id=chunk.upload_id,
|
|
952
|
+
)
|