# Agents - parts of an app that run around the clock, with web sockets

An agent is a part of an app's [server code](/docs/server-code) that stays reachable around the clock, without a request of its own. Use it for:

- a chat or live updates: the pages keep a web socket open, the server code sends to everyone who is there,
- an AI assistant that keeps working: it answers while it works and reports back when it is done,
- a bot or a watcher that wakes every few seconds or at a time it chooses, checks something and acts.

An agent has a name, such as `chat`. An app can have as many as it needs, for example one per team or per conversation. Agents need server code; the app's code still runs in its own walled-off worker, once per event, with the limits of the owner's plan.

An agent here is part of the app and runs on Scava. The AI that builds the app on your computer or in a chat is something else; see [Connect your agent](/docs/agents).

## In the page

```js
const chat = scava.agent('chat');
chat.on('message', (data) => show(data));   // what the server code sends
chat.on('open', () => setOnline(true));
chat.on('close', () => setOnline(false));
chat.send({ text: 'Hello' });                // goes to the server code as JSON
```

- The socket opens to the app's own address, so it needs no entry in `scava.json`.
- Only signed-in people with access can open it, and only from the app's own pages.
- After a break it comes back by itself, waiting 1, 2, 4 and up to 30 seconds. What `send()` gets in the meantime waits, up to 100 messages.
- `chat.close()` ends it.

## In the server code

```js
export default {
  async agent(event, env, ctx) {
    const chat = env.SCAVA.agent(event.agent);
    if (event.type === 'open') await chat.send({ joined: event.from.name || event.from.email });
    if (event.type === 'message') {
      await env.SCAVA.db('messages', { as: 'me' }).add({ text: event.data.text });
      await chat.send({ from: event.from.email, text: event.data.text });
    }
  },
};
```

`agent(event, env, ctx)` gets every event of every agent of the app:

| `event.type` | When | `event.from` |
|---|---|---|
| `open` | A page opened a socket | The person, like `env.SCAVA.me()` |
| `message` | A page sent something; it is in `event.data` | The person who sent it |
| `close` | A socket closed | The person |
| `wake` | The time the agent set has come | `null` |

`event.agent` is the name of the agent, `event.connections` how many sockets are open, `event.at` the time in milliseconds. For `message`, `{ as: 'me' }` gives the code exactly the rights of the person who sent it, as for a request.

What `agent()` returns for a `message` goes back to the socket that sent it, and only to that one:

```js
async agent(event, env) {
  if (event.type === 'message' && event.data.question) {
    const answer = await env.SCAVA.ai({ provider: 'anthropic', model: 'a-model', messages: [{ role: 'user', content: event.data.question }] });
    return { answer: answer.text };
  }
}
```

`env.SCAVA.agent(name)` works everywhere in the server code, also in `fetch`, in a [schedule or a webhook](/docs/schedules-webhooks):

| Call | What it does |
|---|---|
| `send(data)` | Sends `data` as JSON to every open socket of the agent. Returns `{ sent }` |
| `send(data, { to: 'anna@company.com' })` | Only to the sockets of these people (an address or a list) |
| `wake(ms)` | The agent gets a `wake` event in `ms` milliseconds |
| `wake(date)` | ... at this moment (a `Date` or an ISO time) |
| `wake(null)` | Cancels it |
| `who()` | The people with an open socket: `[{ email, name, since }]` |

One time per agent counts: a new `wake()` replaces the one before. The earliest is a second from now.

## Around the clock

An agent keeps working when it sets its next time each time it wakes:

```js
export default {
  async agent(event, env) {
    if (event.agent !== 'watcher' || event.type !== 'wake') return;
    const res = await fetch('https://api.example.com/status', { headers: { authorization: 'Bearer scava:key:EXAMPLE_KEY' } });
    const status = await res.json();
    if (status.changed) await env.SCAVA.agent('dashboard').send(status);
    await env.SCAVA.agent('watcher').wake(30_000); // again in 30 seconds
  },
  async fetch(request, env) {
    // Started once, for example from a button for the owner, or from a schedule that makes sure it runs.
    if (new URL(request.url).pathname === '/api/start-watcher') {
      await env.SCAVA.agent('watcher').wake(1000);
      return Response.json({ started: true });
    }
    return new Response('Not found', { status: 404 });
  },
};
```

A schedule every few minutes that calls `wake()` keeps it going even when a run fails. Between events an agent sleeps and costs nothing; open sockets stay open while it sleeps.

Bots for chat services work through their webhooks: Slack's Events API, Telegram, WhatsApp and Discord's interactions call a [webhook](/docs/schedules-webhooks) of the app, and the server code answers or sends to an agent. A connection that the app itself keeps open to another service, such as Slack's Socket Mode or Discord's gateway, is not possible.

## Who can connect, and when it ends

- A socket needs the same as the app: a signed-in person with access, opened from the app's own pages. Another site cannot open one in the person's name.
- At every message Scava checks again that the person is still signed in and still has access. Whoever was removed, or signed out, is closed at the next message, with code 1008, and the page does not try again.
- When the owner pauses the app, an admin blocks it or its server code stops, every socket of it closes at the next event and nothing opens until it runs again.
- Text messages only, at most 64 KB each, either way. A socket that sends more than 120 messages a minute is closed (1008). An agent takes up to 1,000 sockets.

## Cost and limits

Every event is one call of the server code and counts with its computing time against the plan, as any request does: an agent that wakes every second uses up a monthly limit quickly, one that wakes every minute or only on messages hardly counts. The numbers are in [Limits](/docs/limits). Sockets that are open while nothing happens cost nothing.

Where it runs: the sockets and the wake-up time are held in the EU, also for apps that keep their data in North America. Messages are not stored by Scava; what the code keeps goes into the app's [database](/docs/database).
