# Hosting

The public host entry points are `createResponsesApp` and
`runResponsesServer` from `src/host.ts`.

`createResponsesApp` builds an Express app and wires the shared Agent Server
core middleware:

- request IDs and protected platform headers
- JSON body parsing
- observability initialization
- optional request logging
- Responses route registration
- not-found and error middleware

`runResponsesServer` wraps `createResponsesApp`, starts the HTTP server, logs
startup configuration, and handles graceful shutdown.

## Internal Layout

The host is split so protocol behavior is not trapped in one large file:

| Path | Responsibility |
| --- | --- |
| `src/host.ts` | Public Express/server bootstrap |
| `src/hosting/routes.ts` | Route registration and method guards |
| `src/hosting/routes/*.ts` | Endpoint-specific request handlers |
| `src/hosting/execution.ts` | Handler execution loop and response event application |
| `src/hosting/tracing.ts` | Responses request span creation and response lifecycle binding |
| `src/hosting/http-utils.ts` | Query parsing, active key scoping, JSON parse errors |
| `src/hosting/validation.ts` | Server-boundary semantic validation |
| `src/streaming/` | SSE encoding and streaming response helpers used by route handlers |
| `src/store/` | Response persistence providers used by the host |

## Response Execution

`POST /responses` normalizes the create request, resolves IDs and isolation,
creates a `ResponseContext`, starts a request span, and invokes the configured
`ResponsesHandler`.

The handler returns an iterable or async iterable of `ResponseStreamEvent`
objects. The execution loop applies each event to the in-flight
`ResponseObject`, persists the response and stream events when `store` is
enabled, and emits terminal events for completed, failed, or cancelled
responses.

For non-streaming requests, the HTTP response is sent after execution finishes.
For streaming requests, the host starts Server-Sent Events immediately and
writes each normalized response event as it arrives. For background requests,
the initial queued response can return before the handler finishes.

## Handler Input

The host accepts any of these handler shapes:

```ts
new MyResponsesHandler()
```

```ts
() => new MyResponsesHandler()
```

```ts
async function* handler(request, context, signal) {
  yield /* ResponseStreamEvent */;
}
```

The factory form is useful when each request needs an isolated handler
instance. A single handler instance is useful when it owns shared resources and
implements `close()`.
