agentjam 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. agentjam/__init__.py +435 -0
  2. agentjam/_adapters/__init__.py +0 -0
  3. agentjam/_adapters/responses.py +73 -0
  4. agentjam/_adapters/shared.py +435 -0
  5. agentjam/_agent.py +1032 -0
  6. agentjam/_agent_access.py +360 -0
  7. agentjam/_agent_delegations.py +376 -0
  8. agentjam/_agent_executions.py +566 -0
  9. agentjam/_agent_judging.py +288 -0
  10. agentjam/_agent_options.py +122 -0
  11. agentjam/_agent_routing.py +214 -0
  12. agentjam/_agent_session.py +195 -0
  13. agentjam/_agent_support.py +415 -0
  14. agentjam/_artifacts.py +565 -0
  15. agentjam/_attachments.py +112 -0
  16. agentjam/_connections.py +1282 -0
  17. agentjam/_content.py +29 -0
  18. agentjam/_cron.py +302 -0
  19. agentjam/_errors.py +238 -0
  20. agentjam/_events.py +113 -0
  21. agentjam/_files.py +55 -0
  22. agentjam/_github.py +742 -0
  23. agentjam/_idempotency.py +68 -0
  24. agentjam/_inputs.py +79 -0
  25. agentjam/_models.py +21 -0
  26. agentjam/_polling.py +139 -0
  27. agentjam/_profile.py +244 -0
  28. agentjam/_protocol.py +480 -0
  29. agentjam/_providers.py +365 -0
  30. agentjam/_recaps.py +67 -0
  31. agentjam/_relay/__init__.py +0 -0
  32. agentjam/_relay/actions.py +234 -0
  33. agentjam/_relay/artifacts.py +96 -0
  34. agentjam/_relay/base.py +387 -0
  35. agentjam/_relay/commits.py +77 -0
  36. agentjam/_relay/copies.py +66 -0
  37. agentjam/_relay/credentials.py +127 -0
  38. agentjam/_relay/endpoints.py +39 -0
  39. agentjam/_relay/follow_ups.py +548 -0
  40. agentjam/_relay/frames.py +443 -0
  41. agentjam/_relay/guest_store.py +114 -0
  42. agentjam/_relay/guests.py +55 -0
  43. agentjam/_relay/inputs.py +119 -0
  44. agentjam/_relay/lineage.py +294 -0
  45. agentjam/_relay/memory.py +1045 -0
  46. agentjam/_relay/payments.py +204 -0
  47. agentjam/_relay/profiles.py +95 -0
  48. agentjam/_relay/remote.py +826 -0
  49. agentjam/_relay/resumptions.py +65 -0
  50. agentjam/_relay/revisions.py +43 -0
  51. agentjam/_relay/schedule_follow_ups.py +274 -0
  52. agentjam/_relay/schedules.py +547 -0
  53. agentjam/_relay/secrets.py +275 -0
  54. agentjam/_relay/sessions.py +640 -0
  55. agentjam/_relay/uploads.py +71 -0
  56. agentjam/_requests.py +178 -0
  57. agentjam/_screening.py +368 -0
  58. agentjam/_secrets.py +153 -0
  59. agentjam/_sentry.py +233 -0
  60. agentjam/_signals.py +98 -0
  61. agentjam/_slack.py +468 -0
  62. agentjam/_stripe.py +93 -0
  63. agentjam/_tasks/__init__.py +0 -0
  64. agentjam/_tasks/access.py +142 -0
  65. agentjam/_tasks/incoming.py +952 -0
  66. agentjam/_tasks/outgoing.py +472 -0
  67. agentjam/_tasks/scheduled.py +206 -0
  68. agentjam/_tasks/serial.py +40 -0
  69. agentjam/_tasks/triggers.py +258 -0
  70. agentjam/_tasks/watches.py +77 -0
  71. agentjam/_tools.py +1035 -0
  72. agentjam/_types.py +965 -0
  73. agentjam/_utils.py +75 -0
  74. agentjam/_verdicts.py +21 -0
  75. agentjam/_watermarks.py +59 -0
  76. agentjam/anthropic.py +442 -0
  77. agentjam/mpp.py +233 -0
  78. agentjam/openai.py +141 -0
  79. agentjam/openai_agents.py +253 -0
  80. agentjam/py.typed +0 -0
  81. agentjam/pydantic_ai.py +301 -0
  82. agentjam/skills.py +69 -0
  83. agentjam-0.1.0.dist-info/METADATA +210 -0
  84. agentjam-0.1.0.dist-info/RECORD +86 -0
  85. agentjam-0.1.0.dist-info/WHEEL +4 -0
  86. agentjam-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,640 @@
1
+ import random
2
+ from collections.abc import Callable
3
+ from dataclasses import dataclass, field
4
+ from typing import Literal, assert_never
5
+
6
+ from agentjam._errors import AgentJamError
7
+ from agentjam._protocol import (
8
+ AcceptEnvelope,
9
+ ActionsEnvelope,
10
+ ArtifactEnvelope,
11
+ BudgetEnvelope,
12
+ CancelEnvelope,
13
+ CommitEnvelope,
14
+ CompleteEnvelope,
15
+ ConnectionReadyEnvelope,
16
+ ConnectionRequiredEnvelope,
17
+ ConnectionRevokedEnvelope,
18
+ ConnectionStoredEnvelope,
19
+ DeliveredEnvelope,
20
+ DisconnectEnvelope,
21
+ ErrorEnvelope,
22
+ FailEnvelope,
23
+ FollowUpEnvelope,
24
+ MessageEnvelope,
25
+ ProposeEnvelope,
26
+ RecurEnvelope,
27
+ RejectEnvelope,
28
+ ReplyEnvelope,
29
+ RequireEnvelope,
30
+ ScheduleEndEnvelope,
31
+ ScheduleHandoverEnvelope,
32
+ ScheduleStartEnvelope,
33
+ TriggerFailedEnvelope,
34
+ UpdateEnvelope,
35
+ )
36
+ from agentjam._relay.base import Receiver
37
+ from agentjam._utils import encode_json
38
+
39
+ Side = Literal["requester", "executor"]
40
+
41
+
42
+ @dataclass(eq=False)
43
+ class Member:
44
+ """One connection of an agent to a `MemoryRelay`, which compares by identity."""
45
+
46
+ name: str
47
+ instance_id: str | None
48
+ receive: Receiver
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class WorkKey:
53
+ """Work a requester started, by the requester's name and the work's id."""
54
+
55
+ requester: str
56
+ id: str
57
+
58
+
59
+ @dataclass
60
+ class Departure:
61
+ """What a session leaves behind.
62
+
63
+ The work each peer session lost, the runs, watched schedules and resumable tasks a sibling took over, and the
64
+ resumable tasks held for the agent's next session since it had no sibling.
65
+ """
66
+
67
+ abandoned: dict[Member, list[str]] = field(default_factory=dict)
68
+ runs: list[WorkKey] = field(default_factory=list)
69
+ watches: list[WorkKey] = field(default_factory=list)
70
+ resumed: list[WorkKey] = field(default_factory=list)
71
+ held: list[WorkKey] = field(default_factory=list)
72
+
73
+
74
+ # Invariant: a binding is open while its message awaits a reply, its proposal a verdict, or its task or run an outcome.
75
+ # Only an open task whose executor's session left with no sibling is held, bound to that session until another adopts it.
76
+ @dataclass(eq=False)
77
+ class Binding:
78
+ id: str
79
+ kind: Literal["message", "task", "schedule", "run"]
80
+ requester: Member
81
+ executor: Member
82
+ open: bool = True
83
+ held: bool = False
84
+ conversation: str | None = None
85
+
86
+ def get_party(self, side: Side) -> Member:
87
+ return self.executor if side == "executor" else self.requester
88
+
89
+ def set_party(self, side: Side, member: Member) -> None:
90
+ if side == "executor":
91
+ self.executor = member
92
+ else:
93
+ self.requester = member
94
+
95
+
96
+ def request_key(requester: str, id: str) -> str:
97
+ return f"{requester}/{id}"
98
+
99
+
100
+ def conversation_key(first: str, second: str, id: str) -> str:
101
+ return encode_json([*sorted([first, second]), id])
102
+
103
+
104
+ def is_task(binding: Binding) -> bool:
105
+ return binding.kind in ("task", "run")
106
+
107
+
108
+ def is_load(binding: Binding) -> bool:
109
+ return binding.open and is_task(binding)
110
+
111
+
112
+ def is_lenient(binding: Binding, side: Side) -> bool:
113
+ return binding.kind == "schedule" or (binding.kind == "run" and side == "requester")
114
+
115
+
116
+ def is_kept(binding: Binding, side: Side) -> bool:
117
+ return binding.kind == "task" and side == "requester"
118
+
119
+
120
+ def is_inherited(binding: Binding, side: Side) -> bool:
121
+ return side == "executor" and (
122
+ binding.kind == "run" or (binding.kind == "schedule" and not binding.open)
123
+ )
124
+
125
+
126
+ def is_party(binding: Binding, bound: Member, sender: Member | None) -> bool:
127
+ """Whether `sender` is the session on `bound`'s side of a task, or any session of that agent once the task ended."""
128
+ if binding.open:
129
+ return bound is sender
130
+
131
+ return sender is not None and bound.name == sender.name
132
+
133
+
134
+ def find_side(binding: Binding, member: Member) -> Side | None:
135
+ if binding.executor is member:
136
+ return "executor"
137
+
138
+ return "requester" if binding.requester is member else None
139
+
140
+
141
+ def flip_side(side: Side) -> Side:
142
+ return "requester" if side == "executor" else "executor"
143
+
144
+
145
+ def construct_work(binding: Binding) -> WorkKey:
146
+ return WorkKey(binding.requester.name, binding.id)
147
+
148
+
149
+ class SessionBook:
150
+ """The live sessions of each agent on a `MemoryRelay`, and the session on each side of every piece of work.
151
+
152
+ New work goes to the session with the fewest open tasks, and each follow-up to the session bound to its work.
153
+ Only runs, schedules and resumable tasks move to another session once theirs is gone, and tasks keep running
154
+ once their requester's session is gone.
155
+ """
156
+
157
+ def __init__(self) -> None:
158
+ self._sessions: dict[str, list[Member]] = {}
159
+ self._draining: set[Member] = set()
160
+ self._bindings: dict[str, Binding] = {}
161
+ self._turns: dict[str, Binding] = {}
162
+
163
+ def join(self, member: Member) -> list[WorkKey]:
164
+ """Adds a session, which adopts the tasks held for its agent, and returns them."""
165
+ live = self._list_sessions(member.name)
166
+ if member.instance_id is not None and any(
167
+ other.instance_id == member.instance_id for other in live
168
+ ):
169
+ raise AgentJamError(
170
+ f'Instance "{member.instance_id}" of "{member.name}" is already connected'
171
+ )
172
+
173
+ self._sessions[member.name] = [*live, member]
174
+ adopted = [
175
+ binding
176
+ for binding in self._bindings.values()
177
+ if binding.held and binding.executor.name == member.name
178
+ ]
179
+
180
+ for binding in adopted:
181
+ binding.held = False
182
+ binding.executor = member
183
+
184
+ return [construct_work(binding) for binding in adopted]
185
+
186
+ def leave(
187
+ self, member: Member, is_resumable: Callable[[WorkKey], bool]
188
+ ) -> Departure:
189
+ """Removes a session, handing its runs, watched schedules and the open tasks `is_resumable` picks to a sibling.
190
+
191
+ Those tasks are held for the agent's next session when it has no sibling.
192
+ """
193
+ remaining = [
194
+ other for other in self._list_sessions(member.name) if other is not member
195
+ ]
196
+
197
+ if remaining:
198
+ self._sessions[member.name] = remaining
199
+ else:
200
+ self._sessions.pop(member.name, None)
201
+
202
+ self._draining.discard(member)
203
+ departure = Departure()
204
+ for binding in self._bindings.values():
205
+ side = find_side(binding, member)
206
+ resumes = (
207
+ side == "executor"
208
+ and binding.kind == "task"
209
+ and binding.open
210
+ and is_resumable(construct_work(binding))
211
+ )
212
+
213
+ if resumes:
214
+ self._resume(binding, departure)
215
+ elif side is not None:
216
+ self._release(binding, side, departure)
217
+
218
+ return departure
219
+
220
+ def drain(self, member: Member) -> list[WorkKey]:
221
+ """Sends a session no new work, handing the schedules it watches to a sibling that isn't draining, and returns them."""
222
+ if not self.is_live(member):
223
+ return []
224
+
225
+ self._draining.add(member)
226
+ watched = [
227
+ binding
228
+ for binding in self._bindings.values()
229
+ if binding.kind == "schedule"
230
+ and binding.executor is member
231
+ and is_inherited(binding, "executor")
232
+ ]
233
+
234
+ handed: list[WorkKey] = []
235
+ for binding in watched:
236
+ heir = self.select_session(member.name)
237
+ if heir is None:
238
+ continue
239
+
240
+ binding.executor = heir
241
+ handed.append(construct_work(binding))
242
+
243
+ return handed
244
+
245
+ def get_executor(self, work: WorkKey) -> Member | None:
246
+ binding = self._bindings.get(request_key(work.requester, work.id))
247
+
248
+ return binding.executor if binding else None
249
+
250
+ def rebind_requester(self, work: WorkKey, heir: Member) -> None:
251
+ """Binds the requester side of a task to `heir`, once the task it was delegated as part of moved there."""
252
+ binding = self._bindings.get(request_key(work.requester, work.id))
253
+ if binding and binding.kind == "task":
254
+ binding.requester = heir
255
+
256
+ def release_held(self, work: WorkKey) -> Member | None:
257
+ """Closes a task held for its agent's next session, returning its requester's session, or None if it isn't held."""
258
+ binding = self._bindings.get(request_key(work.requester, work.id))
259
+ if not binding or not binding.held:
260
+ return None
261
+
262
+ binding.held = False
263
+ binding.open = False
264
+
265
+ return binding.requester
266
+
267
+ def is_connected(self, name: str) -> bool:
268
+ return bool(self._list_sessions(name))
269
+
270
+ def is_live(self, member: Member) -> bool:
271
+ return any(session is member for session in self._list_sessions(member.name))
272
+
273
+ def list_names(self) -> list[str]:
274
+ return list(self._sessions)
275
+
276
+ def select_session(self, name: str) -> Member | None:
277
+ """Picks the session of `name` that isn't draining with the fewest open tasks, breaking ties at random."""
278
+ serving = [
279
+ member
280
+ for member in self._list_sessions(name)
281
+ if member not in self._draining
282
+ ]
283
+
284
+ if not serving:
285
+ return None
286
+
287
+ loads = {member: self._count_load(member) for member in serving}
288
+ least = min(loads.values())
289
+
290
+ return random.choice(
291
+ [member for member, load in loads.items() if load == least]
292
+ )
293
+
294
+ def find_recipient(
295
+ self, envelope: DeliveredEnvelope, name: str, sender: Member | None = None
296
+ ) -> Member | None:
297
+ """Finds the session of `name` that `envelope` goes to: the one bound to its work, or the least busy one for new work.
298
+
299
+ A task's requester stays bound once gone, so what its executor sends is dropped, and None is returned once
300
+ the session bound to any other task side or message is gone.
301
+
302
+ Raises:
303
+ AgentJamError: If a message names an open task its sender's session isn't a party to, or an ended one its sender's agent isn't.
304
+ """
305
+ match envelope:
306
+ case MessageEnvelope():
307
+ return self._find_message_recipient(envelope, name, sender)
308
+
309
+ case ProposeEnvelope():
310
+ return self._follow(
311
+ envelope.sender, envelope.id, "executor", name, fallback=True
312
+ )
313
+
314
+ case (
315
+ ReplyEnvelope()
316
+ | ErrorEnvelope()
317
+ | AcceptEnvelope()
318
+ | RequireEnvelope()
319
+ | RejectEnvelope()
320
+ ):
321
+ return self._follow(envelope.to, envelope.reply_to, "requester", name)
322
+
323
+ case (
324
+ UpdateEnvelope()
325
+ | ArtifactEnvelope()
326
+ | CommitEnvelope()
327
+ | CompleteEnvelope()
328
+ | FailEnvelope()
329
+ | ActionsEnvelope()
330
+ ):
331
+ return self._follow(envelope.to, envelope.task_id, "requester", name)
332
+
333
+ case CancelEnvelope() | BudgetEnvelope():
334
+ return self._follow(envelope.sender, envelope.task_id, "executor", name)
335
+
336
+ case RecurEnvelope():
337
+ side: Side = "executor" if name == envelope.to else "requester"
338
+ is_new = (
339
+ request_key(envelope.sender, envelope.task_id) not in self._bindings
340
+ )
341
+ bound = self._follow(envelope.sender, envelope.task_id, side, name)
342
+ if bound is not None or not is_new:
343
+ return bound
344
+
345
+ return self._find_live_session(name)
346
+
347
+ case (
348
+ ScheduleStartEnvelope()
349
+ | ScheduleHandoverEnvelope()
350
+ | TriggerFailedEnvelope()
351
+ ):
352
+ return self._follow(
353
+ envelope.sender, envelope.schedule_id, "executor", name
354
+ )
355
+
356
+ case FollowUpEnvelope():
357
+ return self._follow(name, envelope.schedule_id, "requester", name)
358
+
359
+ case ScheduleEndEnvelope():
360
+ if request_key(name, envelope.schedule_id) in self._bindings:
361
+ return self._follow(name, envelope.schedule_id, "requester", name)
362
+
363
+ return self._follow(
364
+ envelope.sender, envelope.schedule_id, "executor", name
365
+ )
366
+
367
+ case ConnectionReadyEnvelope() | ConnectionRequiredEnvelope():
368
+ return self._follow(
369
+ envelope.to, envelope.proposal_id, "requester", name
370
+ )
371
+
372
+ case ConnectionStoredEnvelope():
373
+ return self._follow(
374
+ envelope.sender, envelope.proposal_id, "executor", name
375
+ )
376
+
377
+ case DisconnectEnvelope() | ConnectionRevokedEnvelope():
378
+ return self._find_live_session(name)
379
+
380
+ case _:
381
+ assert_never(envelope)
382
+
383
+ def track(
384
+ self,
385
+ envelope: DeliveredEnvelope,
386
+ recipient: Member,
387
+ sender: Member | None = None,
388
+ ) -> None:
389
+ """Binds the work `envelope` starts to the sessions on both sides, and closes the work it ends."""
390
+ match envelope:
391
+ case MessageEnvelope():
392
+ if sender is None:
393
+ return
394
+
395
+ conversation = conversation_key(
396
+ envelope.sender, envelope.to, envelope.conversation_id
397
+ )
398
+ self._bind(
399
+ envelope.sender,
400
+ Binding(
401
+ envelope.id,
402
+ "message",
403
+ sender,
404
+ recipient,
405
+ conversation=conversation,
406
+ ),
407
+ )
408
+
409
+ case ProposeEnvelope():
410
+ if sender is None:
411
+ return
412
+
413
+ is_scheduled = envelope.cron is not None or envelope.trigger is not None
414
+ kind: Literal["schedule", "task"] = (
415
+ "schedule" if is_scheduled else "task"
416
+ )
417
+ self._bind(
418
+ envelope.sender, Binding(envelope.id, kind, sender, recipient)
419
+ )
420
+
421
+ case ReplyEnvelope():
422
+ self._answer(envelope.to, envelope.reply_to)
423
+
424
+ case ErrorEnvelope() | RejectEnvelope():
425
+ self._end(envelope.to, envelope.reply_to)
426
+
427
+ case AcceptEnvelope():
428
+ self._accept(envelope.to, envelope.reply_to)
429
+
430
+ case CompleteEnvelope() | FailEnvelope():
431
+ self._end(envelope.to, envelope.task_id)
432
+
433
+ case CancelEnvelope():
434
+ self._end(envelope.sender, envelope.task_id)
435
+
436
+ case RecurEnvelope():
437
+ if recipient.name == envelope.to:
438
+ self._bind_run(envelope, recipient)
439
+
440
+ case ScheduleEndEnvelope():
441
+ is_requested = (
442
+ request_key(envelope.sender, envelope.schedule_id) in self._bindings
443
+ )
444
+ requester = envelope.sender if is_requested else envelope.to
445
+ self._end(requester, envelope.schedule_id)
446
+
447
+ case (
448
+ RequireEnvelope()
449
+ | UpdateEnvelope()
450
+ | ArtifactEnvelope()
451
+ | CommitEnvelope()
452
+ | BudgetEnvelope()
453
+ | ActionsEnvelope()
454
+ | DisconnectEnvelope()
455
+ | ScheduleStartEnvelope()
456
+ | ScheduleHandoverEnvelope()
457
+ | TriggerFailedEnvelope()
458
+ | FollowUpEnvelope()
459
+ | ConnectionReadyEnvelope()
460
+ | ConnectionRequiredEnvelope()
461
+ | ConnectionStoredEnvelope()
462
+ | ConnectionRevokedEnvelope()
463
+ ):
464
+ return
465
+
466
+ case _:
467
+ assert_never(envelope)
468
+
469
+ def _find_live_session(self, name: str) -> Member | None:
470
+ """Picks a session that isn't draining, or any live one, for work that isn't new to the agent."""
471
+ live = self._list_sessions(name)
472
+
473
+ return self.select_session(name) or (live[0] if live else None)
474
+
475
+ def _list_sessions(self, name: str) -> list[Member]:
476
+ return self._sessions.get(name, [])
477
+
478
+ def _count_load(self, member: Member) -> int:
479
+ return sum(
480
+ binding.executor is member and is_load(binding)
481
+ for binding in self._bindings.values()
482
+ )
483
+
484
+ def _follow(
485
+ self,
486
+ requester: str,
487
+ id: str,
488
+ side: Side,
489
+ name: str,
490
+ *,
491
+ fallback: bool = False,
492
+ ) -> Member | None:
493
+ binding = self._bindings.get(request_key(requester, id))
494
+ if binding is None or binding.get_party(side).name != name:
495
+ if side == "executor":
496
+ return self.select_session(name)
497
+
498
+ return self._find_live_session(name)
499
+
500
+ bound = binding.get_party(side)
501
+ if self.is_live(bound) or is_kept(binding, side):
502
+ return bound
503
+
504
+ if not fallback and not is_lenient(binding, side):
505
+ return None
506
+
507
+ heir = self.select_session(name)
508
+ if heir is not None:
509
+ binding.set_party(side, heir)
510
+
511
+ return heir
512
+
513
+ def _find_message_recipient(
514
+ self, message: MessageEnvelope, name: str, sender: Member | None
515
+ ) -> Member | None:
516
+ if message.task_id is not None:
517
+ return self._find_counterpart(message.sender, message.task_id, name, sender)
518
+
519
+ turn = self._turns.get(
520
+ conversation_key(message.sender, name, message.conversation_id)
521
+ )
522
+ parties = (turn.executor, turn.requester) if turn else ()
523
+ latest = next(
524
+ (
525
+ member
526
+ for member in parties
527
+ if member.name == name and self.is_live(member)
528
+ ),
529
+ None,
530
+ )
531
+
532
+ return latest or self.select_session(name)
533
+
534
+ def _find_counterpart(
535
+ self, sender_name: str, task_id: str, name: str, sender: Member | None
536
+ ) -> Member | None:
537
+ requested = self._bindings.get(request_key(sender_name, task_id))
538
+ if (
539
+ requested
540
+ and is_task(requested)
541
+ and is_party(requested, requested.requester, sender)
542
+ and requested.executor.name == name
543
+ ):
544
+ return self._find_counterpart_session(requested, requested.executor)
545
+
546
+ executed = self._bindings.get(request_key(name, task_id))
547
+ if (
548
+ executed
549
+ and is_task(executed)
550
+ and is_party(executed, executed.executor, sender)
551
+ and executed.requester.name == name
552
+ ):
553
+ return self._find_counterpart_session(executed, executed.requester)
554
+
555
+ raise AgentJamError(
556
+ f'This session of "{sender_name}" isn\'t a party to task "{task_id}" with "{name}"'
557
+ )
558
+
559
+ def _find_live(self, member: Member) -> Member | None:
560
+ return member if self.is_live(member) else None
561
+
562
+ def _find_counterpart_session(
563
+ self, binding: Binding, counterpart: Member
564
+ ) -> Member | None:
565
+ if binding.open:
566
+ return self._find_live(counterpart)
567
+
568
+ return self._find_live(counterpart) or self.select_session(counterpart.name)
569
+
570
+ def _bind(self, requester: str, binding: Binding) -> None:
571
+ self._bindings[request_key(requester, binding.id)] = binding
572
+
573
+ def _bind_run(self, recur: RecurEnvelope, executor: Member) -> None:
574
+ if request_key(recur.sender, recur.task_id) in self._bindings:
575
+ return
576
+
577
+ schedule = self._bindings.get(request_key(recur.sender, recur.schedule_id))
578
+ requester = (
579
+ schedule.requester
580
+ if schedule and self.is_live(schedule.requester)
581
+ else self.select_session(recur.sender)
582
+ )
583
+
584
+ if requester is not None:
585
+ self._bind(recur.sender, Binding(recur.task_id, "run", requester, executor))
586
+
587
+ def _answer(self, asker: str, id: str) -> None:
588
+ exchange = self._bindings.get(request_key(asker, id))
589
+ if exchange is None:
590
+ return
591
+
592
+ exchange.open = False
593
+ if exchange.conversation is not None:
594
+ self._turns[exchange.conversation] = exchange
595
+
596
+ def _accept(self, requester: str, id: str) -> None:
597
+ binding = self._bindings.get(request_key(requester, id))
598
+ if binding and binding.kind == "schedule":
599
+ binding.open = False
600
+
601
+ def _end(self, requester: str, id: str) -> None:
602
+ if binding := self._bindings.get(request_key(requester, id)):
603
+ binding.open = False
604
+
605
+ def _release(self, binding: Binding, side: Side, departure: Departure) -> None:
606
+ if is_inherited(binding, side):
607
+ self._inherit(binding, departure)
608
+ return
609
+
610
+ if not binding.open or binding.kind == "run" or is_kept(binding, side):
611
+ return
612
+
613
+ binding.open = False
614
+ peer = binding.get_party(flip_side(side))
615
+ if peer is binding.get_party(side) or not self.is_live(peer):
616
+ return
617
+
618
+ departure.abandoned[peer] = [*departure.abandoned.get(peer, []), binding.id]
619
+
620
+ def _resume(self, binding: Binding, departure: Departure) -> None:
621
+ heir = self.select_session(binding.executor.name)
622
+ if heir is None:
623
+ binding.held = True
624
+ departure.held.append(construct_work(binding))
625
+ return
626
+
627
+ binding.executor = heir
628
+ departure.resumed.append(construct_work(binding))
629
+
630
+ def _inherit(self, binding: Binding, departure: Departure) -> None:
631
+ heir = self.select_session(binding.executor.name)
632
+ if heir is None:
633
+ return
634
+
635
+ binding.executor = heir
636
+ work = construct_work(binding)
637
+ if binding.kind == "run":
638
+ departure.runs.append(work)
639
+ else:
640
+ departure.watches.append(work)
@@ -0,0 +1,71 @@
1
+ import httpx
2
+
3
+ from agentjam._errors import AgentJamError
4
+ from agentjam._files import File
5
+ from agentjam._models import WireModel
6
+ from agentjam._relay.endpoints import AGENT_NAME_HEADER, encode_component
7
+ from agentjam._relay.profiles import Account, get_message
8
+ from agentjam._signals import Signal, guard
9
+
10
+ DEFAULT_MIME_TYPE = "application/octet-stream"
11
+ """The MIME type an upload falls back to when its file has none."""
12
+
13
+
14
+ class UploadSlot(WireModel):
15
+ upload_id: str
16
+ url: str
17
+ fields: dict[str, str]
18
+
19
+
20
+ async def request_slot(
21
+ client: httpx.AsyncClient, account: Account, agent: str, file: File
22
+ ) -> UploadSlot:
23
+ response = await client.post(
24
+ f"{account.api_url}/uploads",
25
+ headers={
26
+ "authorization": f"Bearer {account.api_key}",
27
+ AGENT_NAME_HEADER: encode_component(agent),
28
+ },
29
+ json={
30
+ "name": file.name or "attachment",
31
+ "mimeType": file.mime_type or DEFAULT_MIME_TYPE,
32
+ "size": file.size,
33
+ },
34
+ )
35
+
36
+ if not response.is_success:
37
+ raise AgentJamError(f'Couldn\'t upload "{file.name}": {get_message(response)}')
38
+
39
+ return UploadSlot.model_validate(response.json()["data"])
40
+
41
+
42
+ async def store_file(account: Account, agent: str, file: File) -> str:
43
+ async with httpx.AsyncClient() as client:
44
+ slot = await request_slot(client, account, agent, file)
45
+ content = (file.name, file.data, file.mime_type or DEFAULT_MIME_TYPE)
46
+ stored = await client.post(slot.url, data=slot.fields, files={"file": content})
47
+
48
+ if not stored.is_success:
49
+ raise AgentJamError(
50
+ f'Couldn\'t upload "{file.name}": storage answered with {stored.status_code}'
51
+ )
52
+
53
+ return slot.upload_id
54
+
55
+
56
+ async def upload_file(
57
+ account: Account, agent: str, file: File, signal: Signal | None = None
58
+ ) -> str:
59
+ """Uploads a file straight to storage through a presigned form the AgentJam API hands out.
60
+
61
+ Args:
62
+ account: The API and key to request the form from.
63
+ agent: The name of the agent uploading the file.
64
+ file: The file to upload, at most 100 MiB.
65
+ signal: Cancels the upload once it aborts.
66
+ Returns:
67
+ The upload's id, which an envelope can attach.
68
+ Raises:
69
+ AgentJamError: If the API refuses the upload or storage rejects the file.
70
+ """
71
+ return await guard(store_file(account, agent, file), signal)