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,547 @@
1
+ import asyncio
2
+ from collections.abc import Callable
3
+ from dataclasses import dataclass, field
4
+ from datetime import UTC, datetime
5
+ from typing import Literal, TypeAlias, assert_never
6
+
7
+ from agentjam import _cron
8
+ from agentjam._errors import AgentJamError
9
+ from agentjam._protocol import (
10
+ AcceptEnvelope,
11
+ AttachmentRef,
12
+ CancelEnvelope,
13
+ CompleteEnvelope,
14
+ DeliveredEnvelope,
15
+ DispatchDraft,
16
+ ErrorEnvelope,
17
+ FailEnvelope,
18
+ ProposeEnvelope,
19
+ RecurEnvelope,
20
+ RejectEnvelope,
21
+ RequireEnvelope,
22
+ ScheduleEndEnvelope,
23
+ ScheduleStartEnvelope,
24
+ TriggerFireDraft,
25
+ TriggerSubscribeDraft,
26
+ )
27
+ from agentjam._relay.schedule_follow_ups import FollowedRun
28
+ from agentjam._relay.sessions import request_key
29
+ from agentjam._types import (
30
+ Cron,
31
+ JsonObject,
32
+ ScheduleFollowUp,
33
+ SkillCard,
34
+ TriggerCard,
35
+ TriggerChoice,
36
+ TriggerEvent,
37
+ )
38
+
39
+ EndCode = Literal["expired", "connection_revoked"]
40
+
41
+ Cadence: TypeAlias = Cron | TriggerChoice
42
+
43
+ Deliver: TypeAlias = Callable[[str, DeliveredEnvelope], None]
44
+ """Delivers an envelope to an agent of the relay, dropping it if the agent isn't connected."""
45
+
46
+ END_REASONS: dict[EndCode, str] = {
47
+ "expired": "The schedule reached its expiry",
48
+ "connection_revoked": "The executor lost access to an account the schedule needs",
49
+ }
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class ClosedSchedule:
54
+ """A schedule that just ended, and whether a session of its executor was watching its trigger."""
55
+
56
+ requester: str
57
+ executor: str
58
+ id: str
59
+ watched: bool
60
+
61
+
62
+ @dataclass(eq=False)
63
+ class ScheduleRecord:
64
+ id: str
65
+ requester: str
66
+ executor: str
67
+ principal: str | None
68
+ text: str
69
+ skill: str | None
70
+ input: JsonObject | None
71
+ attachments: list[AttachmentRef] | None
72
+ cadence: Cadence
73
+ expires_at: datetime | None
74
+ then: ScheduleFollowUp | None
75
+ status: Literal["proposed", "requires_action", "active", "ended"] = "proposed"
76
+ next_run_at: datetime | None = None
77
+ """When the next run of a cron schedule is due, unless its cron never matches again."""
78
+ runs: int = 0
79
+ events: set[str] = field(default_factory=set)
80
+ """The ids of the trigger events that started runs."""
81
+ event_keys: set[str] = field(default_factory=set)
82
+ """The keys of the dispatched events that start runs, which the executor's trigger subscribed the schedule to."""
83
+ timer: asyncio.TimerHandle | None = None
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class RunRecord:
88
+ schedule_id: str
89
+ requester: str
90
+ executor: str
91
+ task_id: str
92
+ run: int
93
+ event: TriggerEvent | None
94
+
95
+
96
+ def get_now() -> datetime:
97
+ return datetime.now(UTC)
98
+
99
+
100
+ def construct_start(schedule: ScheduleRecord) -> ScheduleStartEnvelope | None:
101
+ cadence = schedule.cadence
102
+ if not isinstance(cadence, TriggerChoice) or schedule.skill is None:
103
+ return None
104
+
105
+ expires_at = schedule.expires_at
106
+
107
+ return ScheduleStartEnvelope(
108
+ id=f"{schedule.id}:start",
109
+ sender=schedule.requester,
110
+ to=schedule.executor,
111
+ schedule_id=schedule.id,
112
+ principal=schedule.principal,
113
+ text=schedule.text,
114
+ skill=schedule.skill,
115
+ trigger=cadence.name,
116
+ config=cadence.config,
117
+ input=schedule.input,
118
+ attachments=schedule.attachments,
119
+ expires_at=None if expires_at is None else expires_at.isoformat(),
120
+ )
121
+
122
+
123
+ def construct_recur(run: RunRecord, schedule: ScheduleRecord) -> RecurEnvelope:
124
+ event = run.event
125
+
126
+ return RecurEnvelope(
127
+ id=f"{run.task_id}:recur",
128
+ sender=run.requester,
129
+ to=run.executor,
130
+ schedule_id=run.schedule_id,
131
+ task_id=run.task_id,
132
+ run=run.run,
133
+ principal=schedule.principal,
134
+ text=schedule.text,
135
+ skill=schedule.skill,
136
+ input=schedule.input,
137
+ attachments=schedule.attachments,
138
+ event_id=None if event is None else event.id,
139
+ summary=None if event is None else event.summary,
140
+ )
141
+
142
+
143
+ def construct_executor_recur(run: RunRecord, schedule: ScheduleRecord) -> RecurEnvelope:
144
+ recur = construct_recur(run, schedule)
145
+ if run.event is None or run.event.data is None:
146
+ return recur
147
+
148
+ return recur.model_copy(update={"event_data": run.event.data})
149
+
150
+
151
+ def find_cadence(proposal: ProposeEnvelope) -> Cadence | None:
152
+ if proposal.cron is not None and proposal.trigger is not None:
153
+ raise AgentJamError("A schedule runs on a cron or a trigger, not both")
154
+
155
+ if proposal.cron is None:
156
+ return proposal.trigger
157
+
158
+ if problem := _cron.cron_problem(proposal.cron):
159
+ raise AgentJamError(problem)
160
+
161
+ return proposal.cron
162
+
163
+
164
+ def find_trigger_problem(
165
+ choice: TriggerChoice, offered: list[TriggerCard]
166
+ ) -> str | None:
167
+ if any(trigger.name == choice.name for trigger in offered):
168
+ return None
169
+
170
+ names = ", ".join(trigger.name for trigger in offered)
171
+ if names:
172
+ return f'The skill offers no trigger "{choice.name}", only: {names}'
173
+
174
+ return f'The skill offers no triggers, so it can\'t run on "{choice.name}"'
175
+
176
+
177
+ def assert_trigger(cadence: Cadence, skill: SkillCard | None) -> None:
178
+ """Checks that a trigger schedule names a trigger its skill offers."""
179
+ if isinstance(cadence, Cron):
180
+ return
181
+
182
+ offered = [] if skill is None or skill.triggers is None else skill.triggers
183
+ if problem := find_trigger_problem(cadence, offered):
184
+ raise AgentJamError(problem)
185
+
186
+
187
+ def parse_expiry(proposal: ProposeEnvelope) -> datetime | None:
188
+ if not proposal.expires_at:
189
+ return None
190
+
191
+ return datetime.fromisoformat(proposal.expires_at).astimezone(UTC)
192
+
193
+
194
+ def construct_failure(run: RunRecord, error: str) -> FailEnvelope:
195
+ return FailEnvelope(
196
+ id=f"{run.task_id}:ended",
197
+ sender=run.executor,
198
+ to=run.requester,
199
+ task_id=run.task_id,
200
+ error=error,
201
+ )
202
+
203
+
204
+ def construct_ending(
205
+ schedule: ScheduleRecord, sender: str, to: str, code: EndCode
206
+ ) -> ScheduleEndEnvelope:
207
+ return ScheduleEndEnvelope(
208
+ id=f"{schedule.id}:end",
209
+ sender=sender,
210
+ to=to,
211
+ schedule_id=schedule.id,
212
+ reason=END_REASONS[code],
213
+ code=code,
214
+ )
215
+
216
+
217
+ class ScheduleBook:
218
+ """Runs the schedules agents propose through a `MemoryRelay`, ending each once either party leaves."""
219
+
220
+ def __init__(
221
+ self, deliver: Deliver, on_close: Callable[[ClosedSchedule], None]
222
+ ) -> None:
223
+ self._deliver = deliver
224
+ self._on_close = on_close
225
+ self._schedules: dict[str, ScheduleRecord] = {}
226
+ # Invariant: only working runs are kept, and a cron schedule has at most one.
227
+ self._runs: dict[str, RunRecord] = {}
228
+
229
+ def propose(self, proposal: ProposeEnvelope, skill: SkillCard | None) -> None:
230
+ """Records a proposal with a cron or trigger as a schedule, on the executor's skill it names."""
231
+ key = request_key(proposal.sender, proposal.id)
232
+ cadence = find_cadence(proposal)
233
+ if cadence is None or key in self._schedules:
234
+ return
235
+
236
+ assert_trigger(cadence, skill)
237
+ expires_at = parse_expiry(proposal)
238
+ if expires_at is not None and expires_at <= get_now():
239
+ raise AgentJamError("A schedule must expire in the future")
240
+
241
+ self._schedules[key] = ScheduleRecord(
242
+ id=proposal.id,
243
+ requester=proposal.sender,
244
+ executor=proposal.to,
245
+ principal=proposal.principal,
246
+ text=proposal.text,
247
+ skill=proposal.skill,
248
+ input=proposal.input,
249
+ attachments=proposal.attachments,
250
+ cadence=cadence,
251
+ expires_at=expires_at,
252
+ then=proposal.then,
253
+ )
254
+
255
+ def is_schedule(self, requester: str, id: str) -> bool:
256
+ return request_key(requester, id) in self._schedules
257
+
258
+ def respond(
259
+ self, verdict: AcceptEnvelope | RequireEnvelope | RejectEnvelope | ErrorEnvelope
260
+ ) -> None:
261
+ """Starts the first run of a schedule its executor accepts, holds one that requires actions, and forgets one it refuses."""
262
+ key = request_key(verdict.to, verdict.reply_to)
263
+ schedule = self._schedules.get(key)
264
+ is_waiting = schedule is not None and schedule.status in (
265
+ "proposed",
266
+ "requires_action",
267
+ )
268
+ if schedule is None or not is_waiting or schedule.executor != verdict.sender:
269
+ return
270
+
271
+ match verdict:
272
+ case AcceptEnvelope():
273
+ if schedule.status == "proposed":
274
+ self._launch(schedule)
275
+
276
+ case RequireEnvelope():
277
+ if schedule.status == "proposed":
278
+ schedule.status = "requires_action"
279
+
280
+ case RejectEnvelope() | ErrorEnvelope():
281
+ del self._schedules[key]
282
+
283
+ case _:
284
+ assert_never(verdict)
285
+
286
+ def activate(self, requester: str, id: str) -> None:
287
+ """Starts a schedule whose requester's human took every action it requires."""
288
+ schedule = self._schedules.get(request_key(requester, id))
289
+ if schedule is not None and schedule.status == "requires_action":
290
+ self._launch(schedule)
291
+
292
+ def revoke(self, requester: str, id: str) -> None:
293
+ """Ends a schedule once its executor lost access to an account it uses."""
294
+ schedule = self._schedules.get(request_key(requester, id))
295
+ if schedule is not None and schedule.status in ("requires_action", "active"):
296
+ self._terminate(schedule, "connection_revoked")
297
+
298
+ def trigger(self, fire: TriggerFireDraft) -> None:
299
+ """Starts a run of a trigger schedule for an event its executor fired, once per event."""
300
+ schedule = self._find_triggered(fire.sender, fire.to, fire.schedule_id)
301
+ event = TriggerEvent(id=fire.event_id, summary=fire.summary, data=fire.data)
302
+ self._fire_event(schedule, event)
303
+
304
+ def subscribe(self, subscription: TriggerSubscribeDraft) -> None:
305
+ """Subscribes a trigger schedule to the keys of the events dispatched to it, replacing its earlier keys."""
306
+ schedule = self._find_triggered(
307
+ subscription.sender, subscription.to, subscription.schedule_id
308
+ )
309
+ schedule.event_keys = set(subscription.event_keys)
310
+
311
+ def dispatch(self, dispatch: DispatchDraft) -> None:
312
+ """Starts a run of each active schedule of the dispatching executor subscribed to one of the event's keys."""
313
+ event = TriggerEvent(
314
+ id=dispatch.event_id, summary=dispatch.summary, data=dispatch.data
315
+ )
316
+ subscribed = [
317
+ schedule
318
+ for schedule in self._schedules.values()
319
+ if schedule.executor == dispatch.sender
320
+ and schedule.status == "active"
321
+ and any(key in schedule.event_keys for key in dispatch.event_keys)
322
+ ]
323
+
324
+ for schedule in subscribed:
325
+ self._fire_event(schedule, event)
326
+
327
+ def end(self, ending: ScheduleEndEnvelope) -> None:
328
+ schedule = self._find_shared(ending.sender, ending.to, ending.schedule_id)
329
+ if schedule is not None and schedule.status != "ended":
330
+ self._close(schedule)
331
+
332
+ def find_followed(self, completion: CompleteEnvelope) -> FollowedRun | None:
333
+ """Finds the working run a completion ends, with its schedule's follow-up, when the schedule has one."""
334
+ run = self._runs.get(request_key(completion.to, completion.task_id))
335
+ if run is None:
336
+ return None
337
+
338
+ schedule = self._schedules.get(request_key(completion.to, run.schedule_id))
339
+ if schedule is None or schedule.then is None:
340
+ return None
341
+
342
+ return FollowedRun(
343
+ schedule_id=schedule.id,
344
+ requester=run.requester,
345
+ executor=run.executor,
346
+ run_id=run.task_id,
347
+ text=schedule.text,
348
+ then=schedule.then,
349
+ )
350
+
351
+ def is_live(self, requester: str, id: str) -> bool:
352
+ schedule = self._schedules.get(request_key(requester, id))
353
+
354
+ return schedule is not None and schedule.status in ("active", "requires_action")
355
+
356
+ def settle(self, outcome: CompleteEnvelope | FailEnvelope) -> None:
357
+ """Forgets a run once its executor reports how it ended."""
358
+ self._runs.pop(request_key(outcome.to, outcome.task_id), None)
359
+
360
+ def cancel(self, cancel: CancelEnvelope) -> None:
361
+ run = self._runs.pop(request_key(cancel.sender, cancel.task_id), None)
362
+ if run is not None:
363
+ self._deliver(run.requester, construct_failure(run, "The run was canceled"))
364
+
365
+ def rerun(self, requester: str, task_id: str) -> None:
366
+ """Sends a working run to its executor again, once the session running it left."""
367
+ run = self._runs.get(request_key(requester, task_id))
368
+ if run is None:
369
+ return
370
+
371
+ if schedule := self._schedules.get(request_key(requester, run.schedule_id)):
372
+ self._deliver(run.executor, construct_executor_recur(run, schedule))
373
+
374
+ def rewatch(self, requester: str, schedule_id: str) -> None:
375
+ """Starts an active trigger schedule's trigger again, once the session watching it left."""
376
+ schedule = self._schedules.get(request_key(requester, schedule_id))
377
+ start = (
378
+ construct_start(schedule)
379
+ if schedule and schedule.status == "active"
380
+ else None
381
+ )
382
+ if start is not None:
383
+ self._deliver(start.to, start)
384
+
385
+ def leave(self, name: str) -> None:
386
+ """Ends every schedule `name` takes part in, telling the other party, and forgets the ones still proposed."""
387
+ for key, schedule in list(self._schedules.items()):
388
+ if (
389
+ name not in (schedule.requester, schedule.executor)
390
+ or schedule.status == "ended"
391
+ ):
392
+ continue
393
+
394
+ if schedule.status == "proposed":
395
+ del self._schedules[key]
396
+ continue
397
+
398
+ other = (
399
+ schedule.executor if schedule.requester == name else schedule.requester
400
+ )
401
+ self._close(schedule)
402
+ self._deliver(
403
+ other,
404
+ ScheduleEndEnvelope(
405
+ id=f"{schedule.id}:end",
406
+ sender=name,
407
+ to=other,
408
+ schedule_id=schedule.id,
409
+ reason=f"{name} disconnected",
410
+ ),
411
+ )
412
+
413
+ def _find_triggered(self, executor: str, requester: str, id: str) -> ScheduleRecord:
414
+ schedule = self._schedules.get(request_key(requester, id))
415
+ if schedule is None or schedule.executor != executor:
416
+ raise AgentJamError(
417
+ f'No schedule "{id}" from "{requester}" is run by "{executor}"'
418
+ )
419
+
420
+ if isinstance(schedule.cadence, Cron):
421
+ raise AgentJamError(f'Schedule "{id}" runs on a cron rather than a trigger')
422
+
423
+ if schedule.status != "active":
424
+ raise AgentJamError(f'Schedule "{id}" isn\'t active')
425
+
426
+ return schedule
427
+
428
+ def _fire_event(self, schedule: ScheduleRecord, event: TriggerEvent) -> None:
429
+ if self._is_expired(schedule):
430
+ self._terminate(schedule, "expired")
431
+ return
432
+
433
+ if event.id in schedule.events:
434
+ return
435
+
436
+ schedule.runs += 1
437
+ schedule.events.add(event.id)
438
+ self._open(schedule, event)
439
+
440
+ def _find_shared(
441
+ self, sender: str, to: str, schedule_id: str
442
+ ) -> ScheduleRecord | None:
443
+ requested = self._schedules.get(request_key(sender, schedule_id))
444
+ if requested is not None and requested.executor == to:
445
+ return requested
446
+
447
+ executing = self._schedules.get(request_key(to, schedule_id))
448
+
449
+ return (
450
+ executing
451
+ if executing is not None and executing.executor == sender
452
+ else None
453
+ )
454
+
455
+ def _launch(self, schedule: ScheduleRecord) -> None:
456
+ schedule.status = "active"
457
+ if isinstance(schedule.cadence, Cron):
458
+ schedule.next_run_at = _cron.compute_next_run(schedule.cadence, get_now())
459
+
460
+ if start := construct_start(schedule):
461
+ self._deliver(schedule.executor, start)
462
+
463
+ self._fire(schedule)
464
+
465
+ def _fire(self, schedule: ScheduleRecord) -> None:
466
+ if schedule.status != "active":
467
+ return
468
+
469
+ if self._is_expired(schedule):
470
+ self._terminate(schedule, "expired")
471
+ return
472
+
473
+ cadence = schedule.cadence
474
+ due_at = schedule.next_run_at
475
+ if isinstance(cadence, Cron) and due_at is not None and due_at <= get_now():
476
+ schedule.runs += 1
477
+ schedule.next_run_at = _cron.compute_next_run(cadence, get_now())
478
+ self._start(schedule)
479
+
480
+ self._wake(schedule)
481
+
482
+ def _wake(self, schedule: ScheduleRecord) -> None:
483
+ due_at = schedule.next_run_at or schedule.expires_at
484
+ if schedule.status != "active" or due_at is None:
485
+ return
486
+
487
+ delay = max((due_at - get_now()).total_seconds(), 0)
488
+ loop = asyncio.get_running_loop()
489
+ schedule.timer = loop.call_later(delay, self._fire, schedule)
490
+
491
+ def _is_expired(self, schedule: ScheduleRecord) -> bool:
492
+ return schedule.expires_at is not None and schedule.expires_at <= get_now()
493
+
494
+ def _list_runs(self, schedule: ScheduleRecord) -> list[RunRecord]:
495
+ return [
496
+ run
497
+ for run in self._runs.values()
498
+ if run.requester == schedule.requester and run.schedule_id == schedule.id
499
+ ]
500
+
501
+ def _start(self, schedule: ScheduleRecord) -> None:
502
+ if not self._list_runs(schedule):
503
+ self._open(schedule)
504
+
505
+ def _open(
506
+ self, schedule: ScheduleRecord, event: TriggerEvent | None = None
507
+ ) -> None:
508
+ run = RunRecord(
509
+ schedule_id=schedule.id,
510
+ requester=schedule.requester,
511
+ executor=schedule.executor,
512
+ task_id=f"{schedule.id}:{schedule.runs}",
513
+ run=schedule.runs,
514
+ event=event,
515
+ )
516
+
517
+ self._runs[request_key(run.requester, run.task_id)] = run
518
+ self._deliver(run.executor, construct_executor_recur(run, schedule))
519
+ self._deliver(run.requester, construct_recur(run, schedule))
520
+
521
+ def _terminate(self, schedule: ScheduleRecord, code: EndCode) -> None:
522
+ self._close(schedule)
523
+ self._deliver(
524
+ schedule.requester,
525
+ construct_ending(schedule, schedule.executor, schedule.requester, code),
526
+ )
527
+ self._deliver(
528
+ schedule.executor,
529
+ construct_ending(schedule, schedule.requester, schedule.executor, code),
530
+ )
531
+
532
+ def _close(self, schedule: ScheduleRecord) -> None:
533
+ is_watched = schedule.status == "active" and isinstance(
534
+ schedule.cadence, TriggerChoice
535
+ )
536
+ schedule.status = "ended"
537
+ if schedule.timer is not None:
538
+ schedule.timer.cancel()
539
+
540
+ for run in self._list_runs(schedule):
541
+ del self._runs[request_key(run.requester, run.task_id)]
542
+
543
+ self._on_close(
544
+ ClosedSchedule(
545
+ schedule.requester, schedule.executor, schedule.id, is_watched
546
+ )
547
+ )