# The inbox on eve

> Hand inbox conversations in bot mode to eve, run their tools as a service user, send replies as bot messages or ai drafts, and accept channel events without Chat SDK.

Source: https://bettersupabase.com/docs/eve/inbox

`routeInbox` connects the [inbox](/docs/blocks/inbox) to eve's Chat SDK
channel. Build the channel over [`inboxAdapter`](/docs/chat-sdk/inbox-adapter)
and the Postgres state, then hand it to `routeInbox`:

```ts title="agent/channels/inbox.ts"
import { chatSdkChannel } from "eve/channels/chat-sdk";
import { createSupabaseState, inboxAdapter } from "better-supabase/chat-sdk";
import { routeInbox } from "better-supabase/eve";

import { inbox, transport } from "../lib/blocks";

const bridge = chatSdkChannel({
  userName: "Acme agent",
  adapters: {
    inbox: inboxAdapter({
      inbox,
      userName: "Acme agent",
      verify: (request) =>
        request.headers.get("authorization") ===
        `Bearer ${process.env.INBOX_BOT_SECRET}`,
    }),
  },
  state: createSupabaseState({ transport }),
});

routeInbox(bridge, { inbox });

export default bridge.channel;
```

A contact's message in a conversation in bot mode queues an `inbox_bot`
job. Drain the queue with a route that posts each job to the adapter's
webhook, which eve mounts at `/eve/v1/inbox`:

```ts title="app/api/jobs/drain/route.ts"
import "server-only";

import { jobs } from "@/lib/jobs";

export const GET = jobs.drainRoute({
  secret: process.env.CRON_SECRET,
  handlers: {
    inbox_bot: async (payload) => {
      const response = await fetch(`${process.env.APP_URL}/eve/v1/inbox`, {
        method: "POST",
        headers: {
          authorization: `Bearer ${process.env.INBOX_BOT_SECRET}`,
          "content-type": "application/json",
        },
        body: JSON.stringify(payload),
      });
      if (!response.ok) throw new Error(`eve answered ${response.status}`);
    },
  },
});
```

The agent's replies post back into the conversation as the bot. A message
reaches eve only while the conversation's `bot_mode` is `bot`, so a staff
handoff pauses the agent. The turn's principal is the contact
(`principalType: "contact"`, with `tenantId` and `conversationId`), never a
user, so `owner: "user"` connections and per-user memory stay closed to
contacts.

## Inbox connections without Chat SDK [#inbox-connections-without-chat-sdk]

A channel connection that has no Chat SDK adapter reaches eve through three
pieces. `inboxConnectionWebhook` is one route for all connections: it reads
the connection id from the last path segment (`/api/inbox/webhooks/<id>`),
looks the connection up with your `connection` function, and checks the
request with that connection's own credential (`credentials` and `ref`, or
`verify`). An unknown id answers 404, a connection with nothing to verify
with answers 500, and a request that fails the check answers 401. Only a
verified request is stored, in the inbox's `inbound_events`.

```ts title="agent/lib/inbox-webhook.ts"
export const receive = inboxConnectionWebhook({
  inbox,
  connection: (id) => connections.get(id),
});
```

`inboxHandoff` reads the stored events. A parser per adapter name turns an
event into `{ threadId, contact, text, externalId }`, or returns `undefined`
to ignore a status callback. The handoff stores the message with
`inbound.record`, so a replayed event stores one message. While the
conversation's `bot_mode` is `bot`, it sends the text to your eve channel,
keyed by the message id so a retry starts no second turn. The target defaults
to `{ conversationId }`; pass `target` for a channel that names its session
differently.

```ts title="agent/schedules/inbox-handoff.ts"
const handoff = inboxHandoff({ inbox, channel: eve, parsers });

export default defineSchedule({
  cron: "* * * * *",
  run: (args) => args.waitUntil(handoff(args)),
});
```

The session's principal is the contact in that conversation
(`inboxPrincipal`): the principal id is the conversation id, with `tenantId`,
`conversationId` and `contactId` as attributes. Unlike `routeInbox`, which uses the contact id, the id is the conversation's, because a contact can have several conversations and the reply handler only sees the principal's id. A contact is not a user, so
give the tools a service user with `runAs: inboxRunAs({ userId })`; the tool
then runs in the conversation's tenant under that user's row-level security,
and any other principal still needs its own Supabase user.

Replies come from the session sync. Pass `reply: inboxReplies({ inbox })` to
`createSessionSync`. Each finished reply (never an interim one) goes to the
conversation its principal names, keyed by the turn, so a replayed pass sends
it once. In `send` mode (the default) the reply is a bot message that the
inbox's deliveries send on the conversation's channel, with provider status
callbacks through `deliveries.setStatus`. In `draft` mode it is an `ai` draft
that staff review and send. The draft is keyed by the reply, so a retried pass returns the draft even after staff sent or discarded it. `mode` also takes a function, so one inbox can
draft while another sends. `resolve` must return the conversation's tenant for
a contact principal, as in the example.