Skip to content

Events and Sessions

Slack delivers each message to the team bot as a webhook, and it redelivers one when the bot is slow to acknowledge it. Alice asks for last week's churn, and Bob replies in the thread before the first answer arrives. A day later Alice comes back to the thread and approves a query she was asked about.

All of that reaches Mash through one endpoint. Every input to a host is an event, posted to a session, and the session decides when it runs.

Posting an event

The bot uses the Slack thread as the session and the message timestamp as the event id:

curl -X POST http://127.0.0.1:8000/api/v1/sessions/slack:C42:1731864100.0001/events \
  -H "Authorization: Bearer $MASH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"event_id": "1731864100.0001", "app_id": "growth", "policy_id": "growth",
       "message": "pull last week'\''s churn"}'
{
  "data": {
    "session_id": "slack:C42:1731864100.0001",
    "event_id": "1731864100.0001",
    "request_id": "7c9e1f0a-…",
    "seq": 1,
    "status": "queued"
  }
}

event_id, app_id, policy_id and message are required. Three optional fields shape the request: context is prompt text the model sees next to the message, metadata is opaque context for code that the model never sees, and structured_output is a JSON schema the answer must match. The response is trimmed above; it also carries open interactions, the response or error once the event ends, and timestamps.

The request_id is a UUID5 of the session and event ids:

# src/mash/sessions/models.py
def event_request_id(session_id: str, event_id: str) -> str:
    """The id of the request an event runs as."""
    return str(uuid.uuid5(EVENTS_NS, f"{session_id}:{event_id}"))

The bot knows the id before the event runs, and the host gets the same id if it submits the request twice after a restart.

Dedup on the event id

A new (session_id, event_id) returns 202 and inserts a row in the events table. One the session already has returns 200 with the existing row and changes nothing, whatever the body says. A Slack redelivery runs once, and the bot needs no dedup table of its own.

Session and event ids are 1 to 255 letters, digits, ., _, : or -. Session ids are global across the deployment, so an app that can't promise unique ids prefixes them, as the slack: above does.

What a session binds

The first event creates the session and binds it to its policy_id. A later event naming another policy gets 409 SESSION_POLICY_MISMATCH. The thread stays on the growth policy for its whole life.

app_id is not bound. Each event carries its own, and the request stores it for memory scoping, which Cortex covers.

The session row also records host_id, the id of the host boot that took its first event. The bot never sends it. Each build of the host takes a new id and stamps it on what it writes, so the events of one thread can show two ids when a deploy landed in the middle of it. Nothing checks a later event against the session's id.

One event at a time

Events in a session run one at a time, in arrival order. The events table enforces it with a partial unique index:

-- src/mash/storage/migrations/023_sessions_and_events.sql
CREATE UNIQUE INDEX IF NOT EXISTS events_one_active
    ON events (session_id) WHERE status = 'started';

Bob's reply arrives while Alice's event runs, so it waits queued with seq 2. When Alice's event ends, the host starts Bob's, and Bob's request reads the board that Alice's request just wrote to. Work that should run in parallel goes to another session: two threads in #growth run at once.

EventService runs the queues inside the host. Dequeue claims the session's oldest queued event when nothing in the session is started, then submits it to the host's companion under the derived request id. A watcher follows the request to its end, copies the outcome onto the row and dequeues the next event. Each step is idempotent, so on start the host watches every started event again and dequeues every session with queued events.

stateDiagram-v2
    [*] --> queued: POST .../events
    queued --> running: front of the session
    queued --> cancelled: cancel
    running --> waiting: interaction opens
    waiting --> running: answer or timeout
    running --> completed
    running --> failed
    running --> cancelled: cancel
    waiting --> cancelled: cancel

The stored status is queued, started, completed, failed or cancelled. The API reports a started event as waiting while its request has an open interaction and running otherwise. When the last request ends, the host copies its response or error onto the event row, so the outcome outlives retention of the request's events.

Following an event

The bot follows an event on its stream:

curl -N "http://127.0.0.1:8000/api/v1/sessions/slack:C42:1731864100.0001/events/1731864100.0001/stream" \
  -H "Authorization: Bearer $MASH_API_KEY"

While the event is queued, the stream sends one event.queued frame and keepalives every 15 seconds. Once it starts, it relays the request's frames: request.accepted, request.started, agent.trace frames for each model and tool step, request.interaction.create and .ack for pauses, and one end frame, request.completed, request.error or request.cancelled.

An event runs as two requests when the companion routes it. The stream carries the companion's frames, leaves out its end frame, and continues with the routed agent's frames, each seq raised by the companion's last:

# src/mash/sessions/service.py: EventService._frames (trimmed)
agent_id, request_id, offset = routed
async for frame in self._pool.get_client(agent_id).stream_response(
    request_id, after=max(0, after - offset)
):
    if frame.get("seq") is not None:
        frame = {**frame, "seq": int(frame["seq"]) + offset}
    yield frame

Every frame's seq is its SSE id:, so a bot that drops the connection reconnects with ?after= set to the last one and gets the rest of the event, across both requests. The frames are read from the event log, so a late reader sees the same frames as one that was connected from the start.

The other routes read state:

Route Returns
GET /sessions/{sid}/events/{eid} the event's status, request_id, open interactions, response or error
GET /sessions/{sid}/events the session's events in seq order, filtered by status, after_seq, limit
GET /events the same across every session

GET /events?status=running,waiting is how a restarted bot finds the events it was following.

Answering and cancelling

The analyst's run_query tool needs approval, so the stream sends a request.interaction.create frame with an interaction_id, and the event reports waiting. Alice's click comes back to the same endpoint, naming the waiting event:

{"event_id": "1731864100.0001", "interaction_id": "itr_a1b2c3d4e5f6", "response": "approve"}

The body holds only those three keys. The host forwards the answer to the request that owns the interaction, the companion's or the routed agent's, and updates no event row. An answer to an interaction the request doesn't have open gets 404 INTERACTION_NOT_FOUND, one that doesn't fit its schema 400 INVALID_INTERACTION_RESPONSE, and one that lost a race with another answer, a timeout or a cancel 409 INTERACTION_CLOSED. Repeating the stored answer returns 200.

A message Alice sends while the event waits is a new event, and it queues behind the one that's waiting. Human-in-the-loop covers how long a wait lasts and what the agent gets back.

POST /sessions/{sid}/events/{eid}/cancel cancels a queued event outright. For a started one it cancels the companion's request and the request it routed to; each stops at its next step boundary. A cancelled or failed event stays ended. Trying again means posting the message as a new event, which runs against the board as it stands.

Requests underneath

An event is the public unit and a request is the internal one. No route submits, resumes or cancels a request directly; requests start only from a session's queue. The agent read routes stay for inspection, such as GET /api/v1/agent/{agent_id}/sessions/{session_id}/requests, which lists a session's requests filtered by started_by (user, or companion for the routed ones).

The first request every event runs is the companion's, and the companion decides which agent the rest of the event belongs to. That's the next post.

Next: Companion.