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,96 @@
1
+ import base64
2
+ from dataclasses import dataclass, field
3
+ from typing import Literal
4
+
5
+ from agentjam._protocol import ArtifactEnvelope, AttachmentRef
6
+ from agentjam._relay.sessions import request_key
7
+ from agentjam._relay.uploads import DEFAULT_MIME_TYPE
8
+
9
+ MAX_ATTACHMENTS = 10
10
+
11
+
12
+ @dataclass
13
+ class ArtifactRecord:
14
+ artifact_id: str
15
+ kind: Literal["text", "file"]
16
+ name: str | None
17
+ mime_type: str | None
18
+ key: str | None
19
+ pieces: list[bytes] = field(default_factory=list)
20
+ url: str | None = None
21
+ finished: bool = False
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class FinishedArtifact:
26
+ """A task's finished artifact, as the follow-up's attachment and the text and file names a judge reads."""
27
+
28
+ attachment: AttachmentRef
29
+ text: str | None = None
30
+
31
+
32
+ def decode_data_url(url: str) -> bytes:
33
+ return base64.b64decode(url[url.index(",") + 1 :])
34
+
35
+
36
+ def finish_record(record: ArtifactRecord) -> FinishedArtifact:
37
+ fallback = "text/plain" if record.kind == "text" else DEFAULT_MIME_TYPE
38
+ mime_type = record.mime_type if record.mime_type is not None else fallback
39
+ data = decode_data_url(record.url) if record.url else b"".join(record.pieces)
40
+ encoded = base64.b64encode(data).decode()
41
+
42
+ return FinishedArtifact(
43
+ AttachmentRef(
44
+ attachment_id=record.artifact_id,
45
+ name=record.name,
46
+ mime_type=mime_type,
47
+ size=len(data),
48
+ url=record.url or f"data:{mime_type};base64,{encoded}",
49
+ ),
50
+ data.decode(errors="replace") if record.kind == "text" else None,
51
+ )
52
+
53
+
54
+ class ArtifactLedger:
55
+ """Keeps the artifacts of the tasks routed through a `MemoryRelay`, so a run's follow-up receives the ones it finished."""
56
+
57
+ def __init__(self) -> None:
58
+ self._tasks: dict[str, dict[str, ArtifactRecord]] = {}
59
+
60
+ def record(self, envelope: ArtifactEnvelope) -> None:
61
+ artifacts = self._tasks.setdefault(
62
+ request_key(envelope.to, envelope.task_id), {}
63
+ )
64
+ record = artifacts.setdefault(
65
+ envelope.artifact_id,
66
+ ArtifactRecord(
67
+ envelope.artifact_id,
68
+ envelope.kind,
69
+ envelope.name,
70
+ envelope.mime_type,
71
+ envelope.key,
72
+ ),
73
+ )
74
+
75
+ is_text = envelope.kind == "text"
76
+ record.pieces.append(
77
+ envelope.chunk.encode() if is_text else base64.b64decode(envelope.chunk)
78
+ )
79
+ record.url = record.url if envelope.url is None else envelope.url
80
+ record.finished = envelope.last
81
+
82
+ def list_finished(self, requester: str, id: str) -> list[FinishedArtifact]:
83
+ """Lists the finished artifacts of the task `id` of `requester`, a keyed one only at its latest revision, the last 10 at most."""
84
+ records = self._tasks.get(request_key(requester, id), {}).values()
85
+ done = [record for record in records if record.finished]
86
+ latest = [
87
+ record
88
+ for index, record in enumerate(done)
89
+ if record.key is None
90
+ or all(later.key != record.key for later in done[index + 1 :])
91
+ ]
92
+
93
+ return [finish_record(record) for record in latest[-MAX_ATTACHMENTS:]]
94
+
95
+ def end(self, requester: str, id: str) -> None:
96
+ self._tasks.pop(request_key(requester, id), None)
@@ -0,0 +1,387 @@
1
+ from collections.abc import Awaitable, Callable
2
+ from dataclasses import dataclass
3
+ from typing import Protocol, runtime_checkable
4
+
5
+ import httpx
6
+
7
+ from agentjam._errors import AgentJamError
8
+ from agentjam._files import File
9
+ from agentjam._protocol import (
10
+ DeliveredEnvelope,
11
+ DispatchDraft,
12
+ DrainDraft,
13
+ RelayDraft,
14
+ TaskRecapRef,
15
+ TaskRef,
16
+ )
17
+ from agentjam._signals import Signal
18
+ from agentjam._types import (
19
+ AgentCard,
20
+ AgentQuery,
21
+ AutoReloadSettings,
22
+ CreditAccount,
23
+ Dispute,
24
+ HistoryPage,
25
+ HistoryQuery,
26
+ ProfileUpdate,
27
+ Review,
28
+ ReviewDraft,
29
+ ReviewPage,
30
+ ReviewQuery,
31
+ StoredAgent,
32
+ TaskPage,
33
+ TaskQuery,
34
+ TriggerSchedule,
35
+ )
36
+
37
+ Receiver = Callable[[DeliveredEnvelope], Awaitable[None]]
38
+ """Handles one delivered envelope, returning once the agent has handled it."""
39
+
40
+ Draft = DeliveredEnvelope | RelayDraft | DispatchDraft | DrainDraft
41
+
42
+
43
+ @dataclass(frozen=True, kw_only=True)
44
+ class SessionEvents:
45
+ """What a relay reports about an agent's session besides its envelopes. Relays that never lose a session can ignore these."""
46
+
47
+ on_session_replaced: Callable[[], None] | None = None
48
+ """Called once a relay that ended the agent's session during an outage has connected it under a new one."""
49
+ on_error: Callable[[AgentJamError], None] | None = None
50
+ """Called when the connection fails for good, such as when another connection takes over the agent's name."""
51
+
52
+
53
+ @dataclass(frozen=True, kw_only=True)
54
+ class SessionOptions:
55
+ """How a connection joins the agent's other sessions."""
56
+
57
+ instance_id: str | None = None
58
+ """Names this process, so only one connection per instance runs at a time."""
59
+
60
+
61
+ @dataclass(frozen=True, kw_only=True)
62
+ class SecretGrant:
63
+ """A task or schedule's use of the credential its skill's secret connection to `provider` holds."""
64
+
65
+ requester: str
66
+ id: str
67
+ provider: str
68
+
69
+
70
+ @runtime_checkable
71
+ class CredentialChannel(Protocol):
72
+ """How a connection reaches the credentials the platform holds for secret connections, whose keys never reach the agent."""
73
+
74
+ async def authorize(self, grant: SecretGrant) -> str | None:
75
+ """Holds the principal's live credential for `grant`, or returns the link to the form where their human enters one.
76
+
77
+ Args:
78
+ grant: The task or schedule using the credential.
79
+ Returns:
80
+ The form's link, or None once the credential is held.
81
+ """
82
+ ...
83
+
84
+ async def release(self, grant: SecretGrant) -> None:
85
+ """Stops `grant` from using the credential once its task or schedule ended.
86
+
87
+ Args:
88
+ grant: The task or schedule that used the credential.
89
+ """
90
+ ...
91
+
92
+ async def config(self, grant: SecretGrant) -> dict[str, str]:
93
+ """Returns the credential's non-secret fields.
94
+
95
+ Args:
96
+ grant: The task or schedule using the credential.
97
+ Returns:
98
+ The fields, by name.
99
+ Raises:
100
+ ConnectionRevokedError: Once the credential is gone.
101
+ """
102
+ ...
103
+
104
+ async def fetch(self, grant: SecretGrant, request: httpx.Request) -> httpx.Response:
105
+ """Sends a request to the credential's provider through the platform, which adds the credential.
106
+
107
+ Args:
108
+ grant: The task or schedule using the credential.
109
+ request: The request, whose URL may be a path under the credential's base URL.
110
+ Returns:
111
+ The provider's response.
112
+ """
113
+ ...
114
+
115
+
116
+ @runtime_checkable
117
+ class Connection(Protocol):
118
+ """One agent's live session with a relay.
119
+
120
+ Optional capabilities, such as reviews, are separate protocols a connection may also implement.
121
+ """
122
+
123
+ @property
124
+ def name(self) -> str:
125
+ """The name the relay connected the agent under."""
126
+ ...
127
+
128
+ @property
129
+ def card(self) -> AgentCard:
130
+ """The agent's profile as the relay stores it, which can change while it's connected."""
131
+ ...
132
+
133
+ @property
134
+ def claim_url(self) -> str | None:
135
+ """The link where the human claims this agent while it's an unclaimed guest."""
136
+ ...
137
+
138
+ @property
139
+ def payouts_url(self) -> str | None:
140
+ """The link where the human sets up payouts while this agent's paid skills wait for them."""
141
+ ...
142
+
143
+ @property
144
+ def credentials(self) -> CredentialChannel | None:
145
+ """Reaches the credentials of secret connections, or None without a credential store."""
146
+ ...
147
+
148
+ async def send(self, envelope: Draft) -> None:
149
+ """Sends an envelope, which the relay stamps with this agent's name.
150
+
151
+ Args:
152
+ envelope: The envelope to send.
153
+ Raises:
154
+ AgentNotFoundError: If the recipient isn't connected.
155
+ """
156
+ ...
157
+
158
+ async def find(self, query: AgentQuery) -> list[AgentCard]:
159
+ """Lists connected agents matching the query.
160
+
161
+ Args:
162
+ query: The filters to match.
163
+ Returns:
164
+ The matching agents' cards.
165
+ """
166
+ ...
167
+
168
+ async def close(self) -> None:
169
+ """Unregisters the agent and stops delivery."""
170
+ ...
171
+
172
+
173
+ @runtime_checkable
174
+ class ReviewingConnection(Protocol):
175
+ """A connection to a relay that keeps reviews."""
176
+
177
+ async def rate(self, review: ReviewDraft) -> Review:
178
+ """Rates the executor of a task this agent requested, once the task completed with an artifact.
179
+
180
+ Args:
181
+ review: The rating and text.
182
+ Returns:
183
+ The stored review.
184
+ Raises:
185
+ AgentJamError: If the task isn't eligible or this agent already reviewed it.
186
+ """
187
+ ...
188
+
189
+ async def reviews(self, name: str, query: ReviewQuery) -> ReviewPage:
190
+ """Lists the reviews of the named agent, newest first.
191
+
192
+ Args:
193
+ name: The reviewed agent.
194
+ query: The page to list.
195
+ Returns:
196
+ A page of reviews.
197
+ """
198
+ ...
199
+
200
+
201
+ @runtime_checkable
202
+ class DisputingConnection(Protocol):
203
+ """A connection to a relay that takes disputes."""
204
+
205
+ async def dispute(self, task_id: str, reason: str) -> Dispute:
206
+ """Disputes a task this agent requested and its human paid for, while the charge is still held.
207
+
208
+ Args:
209
+ task_id: The disputed task.
210
+ reason: Why the human wants a refund.
211
+ Returns:
212
+ The opened dispute.
213
+ Raises:
214
+ AgentJamError: If the task isn't this human's to dispute, its hold ended, or it's already disputed.
215
+ """
216
+ ...
217
+
218
+
219
+ @runtime_checkable
220
+ class PayingConnection(Protocol):
221
+ """A connection that can buy credits."""
222
+
223
+ async def top_up(self, amount_cents: int) -> CreditAccount:
224
+ """Buys `amount_cents` of credits.
225
+
226
+ Args:
227
+ amount_cents: How many credits to buy, in cents.
228
+ Returns:
229
+ The credit account after the purchase.
230
+ """
231
+ ...
232
+
233
+ async def set_auto_reload(self, settings: AutoReloadSettings) -> CreditAccount:
234
+ """Funds auto-reload from a recurring token.
235
+
236
+ Args:
237
+ settings: How auto-reload buys credits.
238
+ Returns:
239
+ The credit account with auto-reload set.
240
+ """
241
+ ...
242
+
243
+
244
+ @runtime_checkable
245
+ class TriggerListingConnection(Protocol):
246
+ """A connection that lists the active trigger schedules its agent executes."""
247
+
248
+ async def triggers(self) -> list[TriggerSchedule]:
249
+ """Lists the active trigger schedules this agent executes.
250
+
251
+ Returns:
252
+ The schedules.
253
+ """
254
+ ...
255
+
256
+
257
+ @runtime_checkable
258
+ class TaskListingConnection(Protocol):
259
+ """A connection to a relay that keeps the tasks its agent delegated."""
260
+
261
+ async def tasks(self, query: TaskQuery) -> TaskPage:
262
+ """Lists the tasks this agent delegated that match the query, newest first.
263
+
264
+ Args:
265
+ query: The filters and page.
266
+ Returns:
267
+ A page of tasks.
268
+ """
269
+ ...
270
+
271
+
272
+ @runtime_checkable
273
+ class TaskRecallingConnection(Protocol):
274
+ """A connection to a relay that keeps the tasks its agent executed."""
275
+
276
+ async def recall(self, task: TaskRef) -> TaskRecapRef:
277
+ """Recaps a task this agent executed.
278
+
279
+ Args:
280
+ task: The task to recap.
281
+ Returns:
282
+ The task's recap.
283
+ Raises:
284
+ AgentJamError: If no such task exists or this agent didn't execute it.
285
+ """
286
+ ...
287
+
288
+ async def history(self, anchor: TaskRef, query: HistoryQuery) -> HistoryPage:
289
+ """Lists the ended tasks this agent ran before `anchor` that it may recall, newest first.
290
+
291
+ Args:
292
+ anchor: The task the history is for.
293
+ query: The page to list.
294
+ Returns:
295
+ A page of past tasks.
296
+ Raises:
297
+ AgentJamError: If this agent didn't execute `anchor`, or `query` is invalid.
298
+ """
299
+ ...
300
+
301
+
302
+ @runtime_checkable
303
+ class UploadingConnection(Protocol):
304
+ """A connection to a relay that stores files."""
305
+
306
+ async def upload(self, file: File, signal: Signal | None = None) -> str:
307
+ """Uploads a file a proposal can attach.
308
+
309
+ Args:
310
+ file: The file to upload.
311
+ signal: Cancels the upload once it aborts.
312
+ Returns:
313
+ The upload's id.
314
+ """
315
+ ...
316
+
317
+
318
+ @runtime_checkable
319
+ class NetworkConnection(
320
+ Connection,
321
+ ReviewingConnection,
322
+ DisputingConnection,
323
+ TaskListingConnection,
324
+ TaskRecallingConnection,
325
+ UploadingConnection,
326
+ Protocol,
327
+ ):
328
+ """A connection to a relay that keeps reviews and tasks and stores files."""
329
+
330
+
331
+ class Relay(Protocol):
332
+ """Routes envelopes between connected agents. Implement this to plug in a custom transport.
333
+
334
+ A relay stamps each envelope with its sender's name, delivers envelopes in per-sender order, and attaches
335
+ the conversation's answered turns to each message as `history`. An agent may hold many sessions at once:
336
+ new work goes to one of them, and every follow-up to the session that took it.
337
+ """
338
+
339
+ async def create(self, name: str, profile: ProfileUpdate) -> StoredAgent:
340
+ """Stores a new agent, filling in the fields `profile` leaves out with an empty profile.
341
+
342
+ Args:
343
+ name: The agent's name.
344
+ profile: The agent's profile.
345
+ Returns:
346
+ The stored agent.
347
+ Raises:
348
+ AgentExistsError: If an agent with that name already exists.
349
+ """
350
+ ...
351
+
352
+ async def update(self, name: str, profile: ProfileUpdate) -> StoredAgent:
353
+ """Changes only the fields of the agent's stored profile that `profile` sets.
354
+
355
+ Args:
356
+ name: The agent's name.
357
+ profile: The fields to change.
358
+ Returns:
359
+ The stored agent.
360
+ Raises:
361
+ AgentJamError: If no agent with that name exists.
362
+ """
363
+ ...
364
+
365
+ async def connect(
366
+ self,
367
+ name: str,
368
+ receive: Receiver,
369
+ events: SessionEvents | None = None,
370
+ options: SessionOptions | None = None,
371
+ ) -> Connection:
372
+ """Connects an agent the relay stores and starts delivering its envelopes to `receive`.
373
+
374
+ `receive` returns once the agent has handled each envelope. An accepted proposal is handled once its
375
+ task ends, so keep delivering other envelopes in the meantime.
376
+
377
+ Args:
378
+ name: The agent's name.
379
+ receive: Handles each delivered envelope.
380
+ events: Hears about sessions lost after connecting.
381
+ options: Names the instance the session runs as.
382
+ Returns:
383
+ The live connection.
384
+ Raises:
385
+ AgentJamError: If no agent with that name exists, or another connection holds the instance.
386
+ """
387
+ ...
@@ -0,0 +1,77 @@
1
+ from agentjam._errors import AgentJamError, TaskCommittedError
2
+ from agentjam._protocol import (
3
+ ArtifactEnvelope,
4
+ CancelEnvelope,
5
+ CommitEnvelope,
6
+ ConnectionRequiredEnvelope,
7
+ ProposeEnvelope,
8
+ )
9
+ from agentjam._relay.sessions import request_key
10
+ from agentjam._types import FlatPrice, SkillCard
11
+
12
+
13
+ class CommitLedger:
14
+ """Tracks which tasks routed through a `MemoryRelay` can commit, and which of those did."""
15
+
16
+ def __init__(self) -> None:
17
+ self._irreversible: set[str] = set()
18
+ self._flat: set[str] = set()
19
+ self._committed: set[str] = set()
20
+
21
+ def propose(self, proposal: ProposeEnvelope, skill: SkillCard | None) -> None:
22
+ if proposal.cron is not None or proposal.trigger is not None:
23
+ return
24
+
25
+ key = request_key(proposal.sender, proposal.id)
26
+ if skill and skill.irreversible:
27
+ self._irreversible.add(key)
28
+
29
+ if skill and isinstance(skill.price, FlatPrice):
30
+ self._flat.add(key)
31
+
32
+ def commit(self, envelope: CommitEnvelope) -> None:
33
+ key = request_key(envelope.to, envelope.task_id)
34
+ if key not in self._irreversible:
35
+ raise AgentJamError(
36
+ f"Task \"{envelope.task_id}\" isn't of an irreversible skill, so it can't be committed"
37
+ )
38
+
39
+ self._committed.add(key)
40
+
41
+ def deliver(self, artifact: ArtifactEnvelope) -> None:
42
+ """Commits a flat-priced task once its executor sends part of its result."""
43
+ key = request_key(artifact.to, artifact.task_id)
44
+ if key in self._flat:
45
+ self._committed.add(key)
46
+
47
+ def cancel(self, cancel: CancelEnvelope) -> None:
48
+ """Refuses to cancel a committed task."""
49
+ if not self.is_committed(cancel.sender, cancel.task_id):
50
+ return
51
+
52
+ raise TaskCommittedError(
53
+ f'{cancel.to} committed to task "{cancel.task_id}" or sent part of its result, so it can\'t be canceled'
54
+ )
55
+
56
+ def require_access(self, required: ConnectionRequiredEnvelope) -> None:
57
+ """Refuses access a committed task requires, since no action can undo its commit."""
58
+ if not self.is_committed(required.to, required.proposal_id):
59
+ return
60
+
61
+ raise TaskCommittedError(
62
+ f'Task "{required.proposal_id}" was committed, so it can\'t require access anymore'
63
+ )
64
+
65
+ def is_committed(self, requester: str, id: str) -> bool:
66
+ return request_key(requester, id) in self._committed
67
+
68
+ def is_committed_irreversibly(self, requester: str, id: str) -> bool:
69
+ key = request_key(requester, id)
70
+
71
+ return key in self._irreversible and key in self._committed
72
+
73
+ def end(self, requester: str, id: str) -> None:
74
+ key = request_key(requester, id)
75
+ self._irreversible.discard(key)
76
+ self._flat.discard(key)
77
+ self._committed.discard(key)
@@ -0,0 +1,66 @@
1
+ from agentjam._protocol import ActionsEnvelope, CopiedAction
2
+ from agentjam._relay.actions import TrackedAction
3
+ from agentjam._relay.sessions import request_key
4
+ from agentjam._types import ActionOrigin
5
+ from agentjam._utils import create_id
6
+
7
+
8
+ def construct_key(origin: ActionOrigin) -> str:
9
+ return request_key(origin.requester, origin.task_id)
10
+
11
+
12
+ class CopyLedger:
13
+ """Keeps a copy of each open task's actions on the tasks above it in its chain, as a relay does.
14
+
15
+ The requester of each task above learns which accounts its human must connect for the work to go on.
16
+ """
17
+
18
+ def __init__(self) -> None:
19
+ self._copies: dict[str, list[CopiedAction]] = {}
20
+
21
+ def mirror(
22
+ self, chain: list[ActionOrigin], actions: list[TrackedAction]
23
+ ) -> list[ActionsEnvelope]:
24
+ """Replaces the copies of the first task's actions on each task above it with `actions`.
25
+
26
+ `chain` lists the task whose actions changed, then each task above it, nearest first, and `actions` are
27
+ the task's actions while it's open, or none once it ended. Returns the `task.actions` notice for the
28
+ requester of each task above it.
29
+ """
30
+ if not chain:
31
+ return []
32
+
33
+ origin, *ancestors = chain
34
+ copied = [
35
+ CopiedAction(
36
+ kind=action.kind,
37
+ provider=action.provider,
38
+ url=action.url,
39
+ status=action.status,
40
+ origin=origin,
41
+ reason=action.reason,
42
+ )
43
+ for action in actions
44
+ ]
45
+
46
+ notices: list[ActionsEnvelope] = []
47
+ for ancestor in ancestors:
48
+ kept = [
49
+ copy
50
+ for copy in self._copies.get(construct_key(ancestor), [])
51
+ if construct_key(copy.origin) != construct_key(origin)
52
+ ]
53
+
54
+ mirrored = [*kept, *copied]
55
+ self._copies[construct_key(ancestor)] = mirrored
56
+ notices.append(
57
+ ActionsEnvelope(
58
+ id=create_id(),
59
+ sender=ancestor.executor,
60
+ to=ancestor.requester,
61
+ task_id=ancestor.task_id,
62
+ actions=mirrored,
63
+ )
64
+ )
65
+
66
+ return notices