# Writing a host adapter

For people connecting an engine, a native app or a desktop host to Controller+ rooms. A game made with [createRoom](sdk-relay-host.md) or [ControllerHost](sdk-node-host.md) never needs this page.

## Host extensions

Native host adapters can extend peer input without inspecting SDK link maps, timers or trackers. Both `createRoom` and the `RelayRoom` constructor accept the filters above. Filters run before the SDK changes ownership or input history; they do not filter other listeners attached directly to Session. Consume `relay-input` for validated socket snapshots.

Synchronous hooks and filters may call `room.remove(playerId)`, `room.close()` or `context.link.close()`. The SDK checks the current lifecycle at each input, signal, peer allocation, promotion and output boundary. Removing one seat stops only that seat's work; later players in the same roster still update. Closing the room stops new work for every seat. Reconnect and relay fallback hooks may close an old peer while the roster or socket snapshot continues.

`room.lifecycle` and each `RelayPlayer.lifecycle` are read-only snapshots of these states:


| Room state | Behavior |
| --- | --- |
| `open` | Present seats may receive input, acquire peers and send output. |
| `closing` | Shutdown is running. New work is refused, every seat lifetime is retired, and peer retirement callbacks still run. `room.closed` is already true. |
| `closed` | All shutdown steps have finished. Further `close()` calls do nothing. |



| Seat state | Behavior |
| --- | --- |
| `present` | The seat exists. `connected: false` keeps a disconnected seat reserved; it can retain its view, but cannot admit packets, peers or feedback. |
| `removal-pending` | `remove()` has blocked input, signals, peers, promotion and private output. The remove command retries until accepted; the seat stays blocked until the roster confirms its absence. Reconnect cannot revive it. |
| `removed` | The seat is absent from `players`; its resources are cleared and final `leave`/`removed` notifications are being delivered. |
| `retired` | This lifetime can do no more work. A confirmed removal becomes retired after its notifications. A phone reconnect also retires the old `RelayPlayer` object and installs a new present object. Shutdown retires all remaining objects. |


Retain a player object only as a snapshot of that lifetime; read `room.players.get(id)` again after reconnect. Metadata updates within one lifetime keep the same object. Shutdown keeps the final player snapshots in `players`, with `lifecycle: 'retired'`.


| Callback | Allowed lifecycle actions |
| --- | --- |
| `signalFilter` | Return exactly true to admit the signal. It may remove a seat, close the room or close an existing peer; retired owners cannot receive the signal. Exceptions reject it. |
| `inputFilter` | Normalize `frame.input` and return exactly true to admit it. Removal, reconnect or shutdown during the callback rejects the old packet before history changes. Exceptions reject it. |
| `peer` | Wrap the supported peer callbacks, close the candidate, remove a seat or close the room. A retired candidate never starts negotiation. |
| `active-link` | Move extension ownership, close either peer, remove a seat or close the room. Replacing or retiring the new owner rejects its activating packet. Retirement callbacks also run during shutdown; admission methods then refuse new work. |
| `reconnect` | Reset socket-scoped state, close old peers, remove a seat or close the room. It runs before retiring the old lifetime. |
| `relay-input` | Update extension input state or retire a peer for socket fallback. Removing/reconnecting the seat or closing the room stops later packet listeners and SDK history changes. |
| Other seat events | Remove a seat or close the room. Later callbacks for a retired lifetime stop; unrelated roster rows continue. Final removal notifications describe the old lifetime and cannot revive it. |


Roster updates, peer ownership changes and shutdown collect listener errors while finishing their lifecycle work, then throw an `AggregateError` containing the original errors. Shutdown closes every active, pending and retiring peer, cancels queues and timers, and closes the relay session before throwing. This includes an old peer awaiting closure inside an ownership callback. Reentrant `close()` calls during shutdown do nothing. Filters still fail closed, and malformed packet/report handlers keep their existing exception handling.

Import stateless native adapter helpers from `@controller-plus/sdk/host-tools`: `validSignal`, `validateFeedback`, `KIND`, `decodeInput`, `encodeInput`, `decodePing`, `encodePong`, `frameKind` and `seqNewer`. These are public package exports; adapters do not need private peer or wire modules.


| Event | Callback and ordering |
| --- | --- |
| `peer` | A `RelayPeerExtension`: `{ playerId, linkId, offer, link, extensions, isActive, activateLegacy }`. Fires once after allocating a candidate, before its first signal reaches RTC. `offer` is the initial offer. `extensions` reads a copy of the current accepted SDK capabilities, or null before a description is accepted. |
| `active-link` | `{ playerId, previous, current }`, with old/new peer contexts or null. Fires after ownership changes and before closing the old peer. Every promotion fires once, even if the route string is unchanged. Retirement fires with `current: null`; cancelling a pending peer does not change the active owner. |
| `reconnect` | `{ playerId, previousLink, link }`. Fires before the old peer and input history are retired when a known seat changes socket incarnation or reconnects. Reset socket-scoped extension state here. |
| `relay-input` | `{ playerId, input, seq?, wire?, at?, ...extensionFields }`. JSON or decoded binary socket snapshots after `inputFilter`, before SDK input tracking. Includes duplicate refreshes and socket input received while a peer is open, so native extensions can enforce their own ordering. This is a packet callback; it does not grant socket input ownership over a negotiated peer. |


The public `link` facade supports `open`, `closed`, `signal(data)`, `onInput(bytes, { reliable })`, `onControl(frame)`, `onState(state, link)`, `sendControl(frame)` and `close(notify = true)`. Install wrappers in `peer`, capturing and forwarding the original callback for messages your extension does not consume. `reliable` is false for the unordered input channel and true for binary on the ordered control channel. Native protocols that put JSON bytes on the reliable channel can decode those bytes in this callback without replacing RTC channel handlers. Validate custom control records before applying them.

`context.isActive()` checks current ownership and stays safe after replacement, cancellation, close, reconnect and room shutdown. Check it in input/control wrappers. Keep candidate contracts separate from the active receiver; move the receiver in `active-link`. Closing a retired peer must not undo the new receiver.

`context.activateLegacy()` promotes an open pending peer only when its current accepted description lacks `path-handoff`, no description is in flight, no handoff probe has started, and its connected seat still owns the candidate. It returns false for stale or consumed contexts. A first offer without the extension cannot bypass a later accepted handoff reoffer. Negotiated SDK peers always use the SDK drain exchange. A native adapter can call this function from its `open` state callback; preserve the SDK callback too.

## Peer handoff

Peer handoff support is exchanged in offer/answer `data.extensions`, independently of relay features. The host keeps the working link while a candidate probes, and activates a handoff candidate only after its old stream drains and `path-active` arrives. Candidate input cannot bypass that drain. An older phone can still activate its first peer with input. See [peer handoff](protocol.md#peer-handoff).

A candidate must activate within seven seconds of its channels opening. Either required channel closing also retires it, so cleanup does not depend on a cancellation `bye` arriving. The activation timer clears on promotion, replacement, cancellation, removal and shutdown.

For active fallback, the updated phone primes the relay watchdog with the first queued state, sends `bye` and an `sdk-path-return` player event for the current and any previous peer, then repeats that state before the remaining queue. This retires the previous peer even when socket fallback arrives before candidate activation. The room consumes each return event internally, retiring the matching active link or pending candidate even if `bye` is refused or lost. A retired candidate's timer is cleared, and its late activation and input are ignored. Candidates with other link IDs and other seats remain available. Relay JSON remains ignored while a peer is healthy, and the local stale-input timeout is unchanged. Older phones lack this return sequence; see [compatibility limits](protocol.md#peer-handoff).
