agentjam 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. agentjam/__init__.py +435 -0
  2. agentjam/_adapters/__init__.py +0 -0
  3. agentjam/_adapters/responses.py +73 -0
  4. agentjam/_adapters/shared.py +435 -0
  5. agentjam/_agent.py +1032 -0
  6. agentjam/_agent_access.py +360 -0
  7. agentjam/_agent_delegations.py +376 -0
  8. agentjam/_agent_executions.py +566 -0
  9. agentjam/_agent_judging.py +288 -0
  10. agentjam/_agent_options.py +122 -0
  11. agentjam/_agent_routing.py +214 -0
  12. agentjam/_agent_session.py +195 -0
  13. agentjam/_agent_support.py +415 -0
  14. agentjam/_artifacts.py +565 -0
  15. agentjam/_attachments.py +112 -0
  16. agentjam/_connections.py +1282 -0
  17. agentjam/_content.py +29 -0
  18. agentjam/_cron.py +302 -0
  19. agentjam/_errors.py +238 -0
  20. agentjam/_events.py +113 -0
  21. agentjam/_files.py +55 -0
  22. agentjam/_github.py +742 -0
  23. agentjam/_idempotency.py +68 -0
  24. agentjam/_inputs.py +79 -0
  25. agentjam/_models.py +21 -0
  26. agentjam/_polling.py +139 -0
  27. agentjam/_profile.py +244 -0
  28. agentjam/_protocol.py +480 -0
  29. agentjam/_providers.py +365 -0
  30. agentjam/_recaps.py +67 -0
  31. agentjam/_relay/__init__.py +0 -0
  32. agentjam/_relay/actions.py +234 -0
  33. agentjam/_relay/artifacts.py +96 -0
  34. agentjam/_relay/base.py +387 -0
  35. agentjam/_relay/commits.py +77 -0
  36. agentjam/_relay/copies.py +66 -0
  37. agentjam/_relay/credentials.py +127 -0
  38. agentjam/_relay/endpoints.py +39 -0
  39. agentjam/_relay/follow_ups.py +548 -0
  40. agentjam/_relay/frames.py +443 -0
  41. agentjam/_relay/guest_store.py +114 -0
  42. agentjam/_relay/guests.py +55 -0
  43. agentjam/_relay/inputs.py +119 -0
  44. agentjam/_relay/lineage.py +294 -0
  45. agentjam/_relay/memory.py +1045 -0
  46. agentjam/_relay/payments.py +204 -0
  47. agentjam/_relay/profiles.py +95 -0
  48. agentjam/_relay/remote.py +826 -0
  49. agentjam/_relay/resumptions.py +65 -0
  50. agentjam/_relay/revisions.py +43 -0
  51. agentjam/_relay/schedule_follow_ups.py +274 -0
  52. agentjam/_relay/schedules.py +547 -0
  53. agentjam/_relay/secrets.py +275 -0
  54. agentjam/_relay/sessions.py +640 -0
  55. agentjam/_relay/uploads.py +71 -0
  56. agentjam/_requests.py +178 -0
  57. agentjam/_screening.py +368 -0
  58. agentjam/_secrets.py +153 -0
  59. agentjam/_sentry.py +233 -0
  60. agentjam/_signals.py +98 -0
  61. agentjam/_slack.py +468 -0
  62. agentjam/_stripe.py +93 -0
  63. agentjam/_tasks/__init__.py +0 -0
  64. agentjam/_tasks/access.py +142 -0
  65. agentjam/_tasks/incoming.py +952 -0
  66. agentjam/_tasks/outgoing.py +472 -0
  67. agentjam/_tasks/scheduled.py +206 -0
  68. agentjam/_tasks/serial.py +40 -0
  69. agentjam/_tasks/triggers.py +258 -0
  70. agentjam/_tasks/watches.py +77 -0
  71. agentjam/_tools.py +1035 -0
  72. agentjam/_types.py +965 -0
  73. agentjam/_utils.py +75 -0
  74. agentjam/_verdicts.py +21 -0
  75. agentjam/_watermarks.py +59 -0
  76. agentjam/anthropic.py +442 -0
  77. agentjam/mpp.py +233 -0
  78. agentjam/openai.py +141 -0
  79. agentjam/openai_agents.py +253 -0
  80. agentjam/py.typed +0 -0
  81. agentjam/pydantic_ai.py +301 -0
  82. agentjam/skills.py +69 -0
  83. agentjam-0.1.0.dist-info/METADATA +210 -0
  84. agentjam-0.1.0.dist-info/RECORD +86 -0
  85. agentjam-0.1.0.dist-info/WHEEL +4 -0
  86. agentjam-0.1.0.dist-info/licenses/LICENSE +21 -0
agentjam/_artifacts.py ADDED
@@ -0,0 +1,565 @@
1
+ import asyncio
2
+ import base64
3
+ import math
4
+ from bisect import bisect_right
5
+ from collections.abc import (
6
+ AsyncGenerator,
7
+ AsyncIterable,
8
+ Callable,
9
+ Iterable,
10
+ Iterator,
11
+ )
12
+ from contextlib import aclosing, suppress
13
+ from dataclasses import dataclass
14
+ from typing import Literal, TypeAlias, assert_never, overload
15
+ from urllib.parse import unquote_to_bytes
16
+
17
+ import httpx
18
+
19
+ from agentjam._content import Content, ContentSource, LabeledContent, unlabel
20
+ from agentjam._errors import AgentJamError, describe_error
21
+ from agentjam._files import File
22
+ from agentjam._protocol import ArtifactEnvelope
23
+ from agentjam._types import (
24
+ Artifact,
25
+ ArtifactEvent,
26
+ DeltaEvent,
27
+ FileArtifact,
28
+ TaskEvent,
29
+ TextArtifact,
30
+ )
31
+ from agentjam._utils import create_id, encode_json, spawn
32
+
33
+ ArtifactSource: TypeAlias = ContentSource
34
+ """Anything a task can deliver or return as an artifact."""
35
+
36
+ ArtifactKind = Literal["text", "file"]
37
+
38
+ Piece: TypeAlias = str | bytes
39
+
40
+ MAX_FRAME_BYTES = 1024 * 1024
41
+
42
+ # WARNING: base64 grows bytes by a third and text is measured once escaped, so half a frame leaves room for the envelope.
43
+ CHUNK_BYTES = MAX_FRAME_BYTES // 2
44
+
45
+ STREAM_FLUSH = 0.1
46
+
47
+ MAX_ARTIFACT_NAME_BYTES = 1024
48
+
49
+ MAX_ARTIFACT_KEY_LENGTH = 256
50
+
51
+
52
+ @dataclass(frozen=True, kw_only=True)
53
+ class ArtifactChunk:
54
+ """A piece of an artifact as a `task.artifact` envelope carries it, leaving out the envelope's routing."""
55
+
56
+ artifact_id: str
57
+ kind: ArtifactKind
58
+ name: str | None = None
59
+ mime_type: str | None = None
60
+ key: str | None = None
61
+ chunk: str
62
+ last: bool
63
+ upload_id: str | None = None
64
+
65
+
66
+ @dataclass(frozen=True, kw_only=True)
67
+ class Labels:
68
+ name: str | None = None
69
+ mime_type: str | None = None
70
+ key: str | None = None
71
+
72
+ def construct_chunk(
73
+ self,
74
+ artifact_id: str,
75
+ kind: ArtifactKind,
76
+ piece: Piece,
77
+ *,
78
+ last: bool,
79
+ upload_id: str | None = None,
80
+ ) -> ArtifactChunk:
81
+ return ArtifactChunk(
82
+ artifact_id=artifact_id,
83
+ kind=kind,
84
+ name=self.name,
85
+ mime_type=self.mime_type,
86
+ key=self.key,
87
+ chunk=encode_piece(piece),
88
+ last=last,
89
+ upload_id=upload_id,
90
+ )
91
+
92
+
93
+ @dataclass(frozen=True, slots=True)
94
+ class Batch:
95
+ pieces: list[Piece]
96
+ final: bool
97
+
98
+
99
+ def artifact(
100
+ content: Content,
101
+ *,
102
+ name: str | None = None,
103
+ mime_type: str | None = None,
104
+ key: str | None = None,
105
+ ) -> LabeledContent:
106
+ """Attaches a name, MIME type and optional stable key to artifact content, such as `artifact(stream, name="a.md")`.
107
+
108
+ A later delivery under the same `key` replaces the artifact for requesters.
109
+
110
+ Args:
111
+ content: A string, bytes, `File`, or async iterable to send.
112
+ name: The artifact's name, which takes precedence over a `File`'s.
113
+ mime_type: The artifact's MIME type, which takes precedence over a `File`'s.
114
+ key: A stable key of 1 to 256 characters.
115
+
116
+ Returns:
117
+ The labeled artifact, ready to return or deliver from a task.
118
+ """
119
+ return LabeledContent(content, name=name, mime_type=mime_type, key=key)
120
+
121
+
122
+ def assert_artifact_key(key: object) -> None:
123
+ """Checks that an artifact's key, if it has one, is a string of 1 to 256 characters."""
124
+ if key is None or (
125
+ isinstance(key, str) and 0 < len(key) <= MAX_ARTIFACT_KEY_LENGTH
126
+ ):
127
+ return
128
+
129
+ given = (
130
+ f"a string of {len(key)} characters"
131
+ if isinstance(key, str)
132
+ else f"a {type(key).__name__}"
133
+ )
134
+
135
+ raise AgentJamError(
136
+ f"An artifact's key must be a non-empty string of at most {MAX_ARTIFACT_KEY_LENGTH} characters, not {given}"
137
+ )
138
+
139
+
140
+ def truncate_name(name: str) -> str:
141
+ return name.encode()[:MAX_ARTIFACT_NAME_BYTES].decode(errors="ignore")
142
+
143
+
144
+ def construct_labels(
145
+ name: str | None, mime_type: str | None, key: str | None = None
146
+ ) -> Labels:
147
+ return Labels(
148
+ name=truncate_name(name) if name else None,
149
+ mime_type=mime_type or None,
150
+ key=key,
151
+ )
152
+
153
+
154
+ def construct_file_labels(labeled: LabeledContent, file: File) -> Labels:
155
+ return construct_labels(
156
+ labeled.name if labeled.name is not None else file.name,
157
+ labeled.mime_type if labeled.mime_type is not None else file.mime_type,
158
+ labeled.key,
159
+ )
160
+
161
+
162
+ def encode_piece(piece: Piece) -> str:
163
+ return piece if isinstance(piece, str) else base64.b64encode(piece).decode()
164
+
165
+
166
+ def decode_data_url(url: str) -> bytes:
167
+ header, _, payload = url.removeprefix("data:").partition(",")
168
+
169
+ return (
170
+ base64.b64decode(payload)
171
+ if header.endswith(";base64")
172
+ else unquote_to_bytes(payload)
173
+ )
174
+
175
+
176
+ async def fetch_url(url: str) -> httpx.Response:
177
+ if url.startswith("data:"):
178
+ return httpx.Response(200, content=decode_data_url(url))
179
+
180
+ async with httpx.AsyncClient() as client:
181
+ return await client.get(url)
182
+
183
+
184
+ @overload
185
+ async def download(url: str, kind: Literal["text"], subject: str) -> str: ...
186
+
187
+
188
+ @overload
189
+ async def download(url: str, kind: Literal["file"], subject: str) -> bytes: ...
190
+
191
+
192
+ @overload
193
+ async def download(url: str, kind: ArtifactKind, subject: str) -> Piece: ...
194
+
195
+
196
+ async def download(url: str, kind: ArtifactKind, subject: str) -> Piece:
197
+ """Downloads content from a link the relay signed, or a `data:` URL, as text or bytes."""
198
+ try:
199
+ response = await fetch_url(url)
200
+ except (httpx.HTTPError, ValueError) as error:
201
+ raise AgentJamError(
202
+ f"Couldn't download {subject}: {describe_error(error)}"
203
+ ) from error
204
+
205
+ if not response.is_success:
206
+ raise AgentJamError(
207
+ f"Couldn't download {subject}: {response.status_code} {response.reason_phrase}"
208
+ )
209
+
210
+ return (
211
+ response.content.decode(errors="replace")
212
+ if kind == "text"
213
+ else response.content
214
+ )
215
+
216
+
217
+ def join_pieces(pieces: list[Piece], kind: ArtifactKind) -> Piece:
218
+ texts = [piece for piece in pieces if isinstance(piece, str)]
219
+ blobs = [piece for piece in pieces if isinstance(piece, bytes)]
220
+ if kind == "text" and not blobs:
221
+ return "".join(texts)
222
+
223
+ if kind == "file" and not texts:
224
+ return b"".join(blobs)
225
+
226
+ raise AgentJamError("An artifact stream can't mix text and bytes")
227
+
228
+
229
+ def assemble(envelope: ArtifactEnvelope, pieces: list[Piece]) -> Artifact:
230
+ content = join_pieces(pieces, envelope.kind)
231
+ name = envelope.name
232
+ if isinstance(content, str):
233
+ labels = construct_labels(name, envelope.mime_type)
234
+
235
+ return TextArtifact(
236
+ id=envelope.artifact_id,
237
+ text=content,
238
+ name=labels.name,
239
+ mime_type=labels.mime_type,
240
+ key=envelope.key,
241
+ revision=envelope.revision,
242
+ )
243
+
244
+ return FileArtifact(
245
+ id=envelope.artifact_id,
246
+ file=File(
247
+ content,
248
+ name if name is not None else envelope.artifact_id,
249
+ envelope.mime_type or "",
250
+ ),
251
+ key=envelope.key,
252
+ revision=envelope.revision,
253
+ )
254
+
255
+
256
+ def measure_escaped(text: str) -> int:
257
+ return len(encode_json(text).encode()) - 2
258
+
259
+
260
+ def find_slice_end(text: str, start: int) -> int:
261
+ """Returns where the longest slice of `text` from `start` that fits in a chunk ends."""
262
+ ends = range(start + 1, min(len(text), start + CHUNK_BYTES) + 1)
263
+ fitting = bisect_right(
264
+ ends, CHUNK_BYTES, key=lambda end: measure_escaped(text[start:end])
265
+ )
266
+
267
+ return ends[fitting - 1]
268
+
269
+
270
+ def split_text(text: str) -> Iterator[str]:
271
+ start = 0
272
+ while start < len(text):
273
+ end = find_slice_end(text, start)
274
+ yield text[start:end]
275
+ start = end
276
+
277
+
278
+ def split_bytes(data: bytes) -> Iterator[bytes]:
279
+ for start in range(0, len(data), CHUNK_BYTES):
280
+ yield data[start : start + CHUNK_BYTES]
281
+
282
+
283
+ def split(piece: Piece) -> Iterable[Piece]:
284
+ if isinstance(piece, bytes):
285
+ return split_bytes(piece)
286
+
287
+ if measure_escaped(piece) <= CHUNK_BYTES:
288
+ return [piece] if piece else []
289
+
290
+ return split_text(piece)
291
+
292
+
293
+ def encode_text(artifact_id: str, text: str, labels: Labels) -> Iterator[ArtifactChunk]:
294
+ slices = list(split(text)) if text else [""]
295
+
296
+ for index, piece in enumerate(slices):
297
+ yield labels.construct_chunk(
298
+ artifact_id, "text", piece, last=index == len(slices) - 1
299
+ )
300
+
301
+
302
+ def encode_bytes(
303
+ artifact_id: str, data: bytes, labels: Labels
304
+ ) -> Iterator[ArtifactChunk]:
305
+ count = max(1, math.ceil(len(data) / CHUNK_BYTES))
306
+
307
+ for index in range(count):
308
+ start = index * CHUNK_BYTES
309
+ yield labels.construct_chunk(
310
+ artifact_id,
311
+ "file",
312
+ data[start : start + CHUNK_BYTES],
313
+ last=index == count - 1,
314
+ )
315
+
316
+
317
+ def get_kind(piece: Piece) -> ArtifactKind:
318
+ return "text" if isinstance(piece, str) else "file"
319
+
320
+
321
+ class Backlog:
322
+ """Counts the pieces a stream read from its source and sent on, so callers can wait for what it read to be sent."""
323
+
324
+ def __init__(self) -> None:
325
+ self._read = 0
326
+ self._sent = 0
327
+ self._waiters: list[tuple[int, asyncio.Future[None]]] = []
328
+
329
+ def record_read(self) -> None:
330
+ self._read += 1
331
+
332
+ def record_sent(self, count: int) -> None:
333
+ self._sent += count
334
+ self._release(lambda target: target <= self._sent)
335
+
336
+ def wait_for_sent(self) -> asyncio.Future[None]:
337
+ """Resolves once every piece read before this call has been sent, or the stream has closed."""
338
+ future = asyncio.get_running_loop().create_future()
339
+ if self._sent >= self._read:
340
+ future.set_result(None)
341
+ else:
342
+ self._waiters.append((self._read, future))
343
+
344
+ return future
345
+
346
+ def close(self) -> None:
347
+ self._release(lambda _: True)
348
+
349
+ def _release(self, is_sent: Callable[[int], bool]) -> None:
350
+ released = [future for target, future in self._waiters if is_sent(target)]
351
+ self._waiters = [
352
+ (target, future) for target, future in self._waiters if not is_sent(target)
353
+ ]
354
+
355
+ for future in released:
356
+ if not future.done():
357
+ future.set_result(None)
358
+
359
+
360
+ class ReadAhead:
361
+ """Reads a stream ahead of its consumer, batching what arrives within a flush window or while `limit` bytes wait.
362
+
363
+ A batch is final when the stream had ended without failing by the time it was yielded.
364
+ """
365
+
366
+ def __init__(
367
+ self, stream: AsyncIterable[Piece], limit: int, backlog: Backlog
368
+ ) -> None:
369
+ self._stream = stream
370
+ self._limit = limit
371
+ self._backlog = backlog
372
+ self._buffered: list[Piece] = []
373
+ self._size = 0
374
+ self._ended = False
375
+ self._failure: Exception | None = None
376
+ self._arrived = asyncio.Event()
377
+ self._drained = asyncio.Event()
378
+ self._flush_at = 0.0
379
+
380
+ async def batches(self) -> AsyncGenerator[Batch, None]:
381
+ loop = asyncio.get_running_loop()
382
+ pump = spawn(self._pump())
383
+
384
+ try:
385
+ while True:
386
+ while self._is_held(loop.time()):
387
+ await self._wait_for_arrival(self._flush_at - loop.time())
388
+
389
+ if self._buffered:
390
+ pieces, self._buffered, self._size = self._buffered, [], 0
391
+ self._drained.set()
392
+ self._drained = asyncio.Event()
393
+ self._flush_at = loop.time() + STREAM_FLUSH
394
+ yield Batch(pieces, final=self._ended and self._failure is None)
395
+ # WARNING: the consumer only resumes this generator once it has sent every chunk of these pieces.
396
+ self._backlog.record_sent(len(pieces))
397
+ continue
398
+
399
+ if self._failure is not None:
400
+ raise self._failure
401
+
402
+ if self._ended:
403
+ return
404
+
405
+ await self._wait_for_arrival(None)
406
+ finally:
407
+ # WARNING: a pending read holds the source open, so stopping must not wait for that read to settle.
408
+ if not self._ended:
409
+ pump.cancel()
410
+
411
+ def _is_held(self, now: float) -> bool:
412
+ return (
413
+ len(self._buffered) > 0
414
+ and not self._ended
415
+ and self._size < self._limit
416
+ and now < self._flush_at
417
+ )
418
+
419
+ async def _wait_for_arrival(self, delay: float | None) -> None:
420
+ with suppress(TimeoutError):
421
+ async with asyncio.timeout(delay):
422
+ await self._arrived.wait()
423
+
424
+ self._arrived.clear()
425
+
426
+ async def _pump(self) -> None:
427
+ iterator = aiter(self._stream)
428
+
429
+ try:
430
+ async for piece in iterator:
431
+ self._buffered.append(piece)
432
+ self._size += len(piece)
433
+ self._backlog.record_read()
434
+ self._arrived.set()
435
+ # WARNING: a source whose pieces are all ready never suspends, so yielding here lets its first piece go out alone.
436
+ await asyncio.sleep(0)
437
+ if self._size >= self._limit:
438
+ await self._drained.wait()
439
+ except Exception as error:
440
+ self._failure = error
441
+ finally:
442
+ self._ended = True
443
+ self._arrived.set()
444
+ if isinstance(iterator, AsyncGenerator):
445
+ with suppress(Exception):
446
+ await iterator.aclose()
447
+
448
+
449
+ async def encode_stream(
450
+ artifact_id: str,
451
+ stream: AsyncIterable[Piece],
452
+ labels: Labels,
453
+ backlog: Backlog,
454
+ ) -> AsyncGenerator[ArtifactChunk, None]:
455
+ kind: ArtifactKind | None = None
456
+ finished = False
457
+
458
+ async with aclosing(ReadAhead(stream, CHUNK_BYTES, backlog).batches()) as batches:
459
+ async for batch in batches:
460
+ kind = kind or get_kind(batch.pieces[0])
461
+ slices = list(split(join_pieces(batch.pieces, kind)))
462
+ finished = batch.final and len(slices) > 0
463
+
464
+ for index, piece in enumerate(slices):
465
+ yield labels.construct_chunk(
466
+ artifact_id,
467
+ kind,
468
+ piece,
469
+ last=finished and index == len(slices) - 1,
470
+ )
471
+
472
+ if finished:
473
+ return
474
+
475
+ yield labels.construct_chunk(artifact_id, kind or "text", "", last=True)
476
+
477
+
478
+ async def encode(
479
+ source: ArtifactSource, backlog: Backlog | None = None
480
+ ) -> AsyncGenerator[ArtifactChunk, None]:
481
+ """Splits an artifact source into wire chunks that each fit in a transport frame.
482
+
483
+ A string, bytes or `File` is sliced into chunks, the last of them final. A stream sends what arrives
484
+ within a flush window or while its previous chunk is sent as one, and its last chunk is final when the
485
+ stream ended before it was sent, else an empty final chunk follows. Text never splits inside a character.
486
+ """
487
+ labeled = unlabel(source)
488
+ artifact_id = create_id()
489
+
490
+ match labeled.content:
491
+ case str() as text:
492
+ labels = construct_labels(labeled.name, labeled.mime_type, labeled.key)
493
+ for chunk in encode_text(artifact_id, text, labels):
494
+ yield chunk
495
+
496
+ case File() as file:
497
+ for chunk in encode_bytes(
498
+ artifact_id, file.data, construct_file_labels(labeled, file)
499
+ ):
500
+ yield chunk
501
+
502
+ case bytes() as data:
503
+ labels = construct_labels(labeled.name, labeled.mime_type, labeled.key)
504
+ for chunk in encode_bytes(artifact_id, data, labels):
505
+ yield chunk
506
+
507
+ case AsyncIterable() as stream:
508
+ labels = construct_labels(labeled.name, labeled.mime_type, labeled.key)
509
+ streamed = encode_stream(artifact_id, stream, labels, backlog or Backlog())
510
+ async with aclosing(streamed) as chunks:
511
+ async for chunk in chunks:
512
+ yield chunk
513
+
514
+ case _:
515
+ assert_never(labeled.content)
516
+
517
+
518
+ def encode_upload(file: File, labeled: LabeledContent, upload_id: str) -> ArtifactChunk:
519
+ """Describes a file artifact by the upload holding it, in one empty last chunk the relay links to the file."""
520
+ return construct_file_labels(labeled, file).construct_chunk(
521
+ create_id(), "file", "", last=True, upload_id=upload_id
522
+ )
523
+
524
+
525
+ class ArtifactAssembler:
526
+ """Rebuilds artifacts from their wire chunks, turning each chunk into requester-facing events.
527
+
528
+ An envelope with a `url` replaces any chunks received so far with the downloaded artifact.
529
+ """
530
+
531
+ def __init__(self) -> None:
532
+ self._partials: dict[str, list[Piece]] = {}
533
+
534
+ async def add(self, envelope: ArtifactEnvelope) -> list[TaskEvent]:
535
+ artifact_id = envelope.artifact_id
536
+ if envelope.url:
537
+ self._partials.pop(artifact_id, None)
538
+ downloaded = await download(
539
+ envelope.url, envelope.kind, f"artifact {artifact_id}"
540
+ )
541
+
542
+ return [ArtifactEvent(artifact=assemble(envelope, [downloaded]))]
543
+
544
+ piece: Piece = (
545
+ envelope.chunk
546
+ if envelope.kind == "text"
547
+ else base64.b64decode(envelope.chunk)
548
+ )
549
+ pieces = self._partials.get(artifact_id, [])
550
+ streamed = not envelope.last or len(pieces) > 0
551
+ events: list[TaskEvent] = (
552
+ [DeltaEvent(artifact_id=artifact_id, chunk=piece, key=envelope.key)]
553
+ if streamed and piece
554
+ else []
555
+ )
556
+
557
+ pieces.append(piece)
558
+ if not envelope.last:
559
+ self._partials[artifact_id] = pieces
560
+
561
+ return events
562
+
563
+ self._partials.pop(artifact_id, None)
564
+
565
+ return [*events, ArtifactEvent(artifact=assemble(envelope, pieces))]
@@ -0,0 +1,112 @@
1
+ import asyncio
2
+ from collections.abc import AsyncIterable, Sequence
3
+ from dataclasses import replace
4
+ from typing import TypeAlias, assert_never
5
+
6
+ from agentjam._artifacts import download
7
+ from agentjam._content import Content, ContentSource, LabeledContent, unlabel
8
+ from agentjam._errors import AgentJamError
9
+ from agentjam._files import File
10
+ from agentjam._protocol import AttachmentRef
11
+ from agentjam._types import Attachment
12
+
13
+ AttachmentSource: TypeAlias = ContentSource
14
+ """Anything a requester can attach to a task. Streams are read to the end before they upload."""
15
+
16
+ DEFAULT_MIME_TYPE = "application/octet-stream"
17
+
18
+
19
+ def attachment(
20
+ content: Content, *, name: str | None = None, mime_type: str | None = None
21
+ ) -> LabeledContent:
22
+ """Attaches a name and MIME type to attachment content, such as `attachment(csv, name="q3.csv")`.
23
+
24
+ Args:
25
+ content: A string, bytes, `File`, or async iterable to attach.
26
+ name: The attachment's name, which takes precedence over a `File`'s.
27
+ mime_type: The attachment's MIME type, which takes precedence over a `File`'s.
28
+
29
+ Returns:
30
+ The labeled attachment, ready to pass in `attachments`.
31
+ """
32
+ return LabeledContent(content, name=name, mime_type=mime_type)
33
+
34
+
35
+ async def read_pieces(stream: AsyncIterable[str | bytes]) -> list[str | bytes]:
36
+ return [piece async for piece in stream]
37
+
38
+
39
+ def encode_pieces(pieces: list[str | bytes]) -> bytes:
40
+ return b"".join(
41
+ piece.encode() if isinstance(piece, str) else piece for piece in pieces
42
+ )
43
+
44
+
45
+ async def construct_file(source: AttachmentSource) -> File:
46
+ """Turns an attachment source into the file that uploads, with labels taking precedence over a `File`'s own.
47
+
48
+ Text defaults to `text/plain`, and other content to `application/octet-stream`.
49
+ """
50
+ labeled = unlabel(source)
51
+ content = labeled.content
52
+
53
+ match content:
54
+ case File():
55
+ return relabel_file(labeled, content)
56
+
57
+ case str() | bytes():
58
+ return construct_upload(labeled, [content])
59
+
60
+ case AsyncIterable():
61
+ return construct_upload(labeled, await read_pieces(content))
62
+
63
+ case _:
64
+ assert_never(content)
65
+
66
+
67
+ def relabel_file(labeled: LabeledContent, file: File) -> File:
68
+ if not labeled.name and not labeled.mime_type:
69
+ return file
70
+
71
+ return replace(
72
+ file,
73
+ name=labeled.name if labeled.name is not None else file.name,
74
+ mime_type=labeled.mime_type
75
+ if labeled.mime_type is not None
76
+ else file.mime_type,
77
+ )
78
+
79
+
80
+ def construct_upload(labeled: LabeledContent, pieces: list[str | bytes]) -> File:
81
+ is_text = all(isinstance(piece, str) for piece in pieces)
82
+ name, mime_type = (
83
+ ("attachment.txt", "text/plain")
84
+ if is_text
85
+ else ("attachment", DEFAULT_MIME_TYPE)
86
+ )
87
+
88
+ return File(
89
+ encode_pieces(pieces),
90
+ labeled.name if labeled.name is not None else name,
91
+ labeled.mime_type if labeled.mime_type is not None else mime_type,
92
+ )
93
+
94
+
95
+ async def receive_attachment(ref: AttachmentRef) -> Attachment:
96
+ """Downloads an attachment the relay linked for this agent."""
97
+ if not ref.url:
98
+ raise AgentJamError(
99
+ f"The relay sent attachment {ref.attachment_id} without a link to download it"
100
+ )
101
+
102
+ name = ref.name if ref.name is not None else ref.attachment_id
103
+ data = await download(ref.url, "file", f"attachment {name}")
104
+
105
+ return Attachment(id=ref.attachment_id, file=File(data, name, ref.mime_type or ""))
106
+
107
+
108
+ async def receive_attachments(
109
+ refs: Sequence[AttachmentRef] | None = None,
110
+ ) -> list[Attachment]:
111
+ """Downloads every attachment the relay linked for this agent, in order."""
112
+ return list(await asyncio.gather(*map(receive_attachment, refs or [])))