# Proactive events

Hand outside changes such as email and notifications to the proactive engine.

ShiritaiBot doesn't only work when someone talks to it. A new email, an upcoming homework deadline, a new issue in a repository: changes like these can all go to the proactive engine as events. The engine first judges how important an event is, then decides whether to drop it, file it, or handle it and notify the owner.

A plugin can do two things here: submit events as an **event source**, and adjust the engine's judgments with **hooks**.

## Submit an event

Submit an `ExternalEvent` with `self.context.emit()`:

```python main.py
from shiritaibot.api import Actor, ExternalEvent

await self.context.emit(
    ExternalEvent(
        source="weather",
        kind="weather.alert",
        dedup_key=f"alert:{alert['id']}",
        title=f"Heavy rain warning for {city}",
        payload={"city": city, "level": alert["level"], "text": alert["text"]},
        urgency="high",
    )
)
```

| Field         | Description                                                                                                                        |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `source`      | Where the event comes from; usually just the plugin ID                                                                             |
| `kind`        | The event type, such as `email.received` or `weather.alert`                                                                        |
| `dedup_key`   | Deduplication key. Under the same `source`, each `dedup_key` is handled only once. Required                                        |
| `title`       | A one-line title                                                                                                                   |
| `payload`     | The event content: any JSON-serializable dict                                                                                      |
| `urgency`     | How urgent it is: `low`, `normal`, `high` or `critical`; `normal` by default. Only a hint; the engine decides the final importance |
| `occurred_at` | When it happened, with a time zone; the current time by default                                                                    |
| `actors`      | The people involved, such as an email's sender                                                                                     |

`dedup_key` matters. Polling plugins often see the same item more than once; with a stable ID as the key, the same thing never triggers several notifications.

`actors` tells ShiritaiBot who's in the event, such as `Actor(identity="email:someone@example.com", name="Alex", role="sender")`. Plugins don't write memories themselves; once the event is handled, ShiritaiBot decides whether to remember these people.

`emit()` returns a receipt ID. A successful submission doesn't mean the event has been handled; to check the result, call `await self.context.get_event(receipt_id)`. Use `emit_many()` to submit several events at once.

## Write a polling event source

Most event sources check for something new at regular intervals. Start a background task in `initialize()` and cancel it in `terminate()`:

```python main.py
import asyncio

import httpx

from shiritaibot.api import ExternalEvent, Plugin


class WeatherAlert(Plugin):
    async def initialize(self):
        self.task = asyncio.create_task(self.poll())

    async def terminate(self):
        self.task.cancel()
        await asyncio.gather(self.task, return_exceptions=True)

    async def poll(self):
        async with httpx.AsyncClient(timeout=20) as client:
            while True:
                try:
                    await self.check(client)
                except Exception as exc:
                    self.logger.warning(f"Couldn't check for alerts ({type(exc).__name__})")
                await asyncio.sleep(self.config["interval"])

    async def check(self, client: httpx.AsyncClient):
        city = self.config["city"]
        response = await client.get("https://weather.example.com/alerts", params={"city": city})
        for alert in response.json()["alerts"]:
            await self.context.emit(
                ExternalEvent(
                    source="weather",
                    kind="weather.alert",
                    dedup_key=f"alert:{alert['id']}",
                    title=f"{alert['title']} for {city}",
                    payload=alert,
                )
            )
```

Catch exceptions inside the loop, or a single network error makes the background task quietly stop.

## What happens after an event

1. A triage model rates the event's importance from 0 to 4. Events rated 0 are dropped.
2. Events rated 1 or higher start a Proactive Loop, where the model can use tools to check facts and prepare material.
3. When the loop ends, the model decides whether to notify the owner. Events rated 4 always notify.

The model reads the event's content. Email, web pages and the like may contain instructions aimed at the model, so don't put more in `payload` than needed.

## Adjust the engine's judgments

Besides submitting events, plugins can step into how events from other sources are handled:

| Decorator                      | Handler arguments  | When it runs and what it's for                                                                                               |
| ------------------------------ | ------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| `@hook.on_proactive_event()`   | `(event)`          | When an event starts, before triage. Can change `title`, `payload` and `urgency`, or drop it with `event.drop(reason)`       |
| `@hook.on_proactive_judged()`  | `(event, triage)`  | After triage. Can change `triage.importance` (0 drops it), `decision`, `message` and `reason`                                |
| `@hook.on_proactive_done()`    | `(event, outcome)` | After the loop, before notifying. Can rewrite `outcome.message`, or set `outcome.notify` to `False` to skip the notification |
| `@hook.on_notification_sent()` | `(source, text)`   | After a notification reaches the owner, for example to forward it elsewhere                                                  |

For example, a plugin that ignores certain sources:

```python main.py
from shiritaibot.api import ProactiveEvent, Triage, hook

@hook.on_proactive_event()
async def drop_sources(self, event: ProactiveEvent):
    if event.source in self.config["drop_sources"]:
        event.drop(f"Source {event.source} is set to be ignored")

@hook.on_proactive_judged()
async def raise_floor(self, event: ProactiveEvent, triage: Triage):
    if event.kind == "email.received" and 0 < triage.importance < 2:
        triage.importance = 0
```

Use `event.source` and `event.kind` to tell events apart. These hooks may run for at most 30 seconds.

So that plugins can't accidentally bury something important, ShiritaiBot keeps a few safety rules:

* Reminders and scheduled tasks the owner set up, and results of subagents the owner delegated to (`event.protected` is `True`), can't be dropped.
* Events rated 4 and reminders the owner set up (`outcome.forced` is `True`) always notify; plugins can only rewrite the text.
* When a change is invalid (an importance outside 0 to 4, or an empty message, for example), it's ignored and a warning is logged.

## Notify the owner directly

For a simple notification that should skip the proactive engine's judgment and triage, use `await self.context.notify_owner(text)`. It doesn't go through the proactive engine, and it isn't added to the short-term memory the engine builds.
