Skip to content
seeARMSPublic

About

A free, open-source virtual AI Key and AI Port for UniFi Protect: plain-English search, event descriptions and third-party camera detections with local models.

Topics

Resources

Stars

267 stars

Watchers

2 watching

Forks

Latest commit

 

History

124 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Keystone

A free, virtual AI Key and AI Port for UniFi Protect.

Website · Dashboard demo · Install · Turn on features · Hardware · FAQ

Latest Keystone release CI status on main Apache 2.0 license Sponsor Keystone

UniFi Protect's best AI features — plain-English search, detailed event descriptions, face and license plate recognition, and smart detections on third-party cameras — normally require Ubiquiti's AI Key ($799) and AI Port ($199 for up to three HD cameras). Keystone is free software that takes their place: run it on a computer you already own, and open models do the same jobs on your own network.

Protect adopts Keystone in UniFi Protect → UniFi Devices as a virtual AI Key (and optionally a virtual AI Port), just like real Ubiquiti hardware. No database hacks, no patched Protect files, and no cloud subscriptions.

Works with both UniFi and third-party cameras. UniFi cameras with smart detections (G4 and newer) get plain-English search and event descriptions, and G4/G5 cameras also get face and license plate recognition. Third-party ONVIF cameras (Reolink, Amcrest, or Nest through Scrypted) and older UniFi cameras without smart detections pair with the optional virtual AI Port to get all of that plus Protect's smart detections.

Unofficial community project; not affiliated with or endorsed by Ubiquiti Inc. No vendor firmware, proprietary binaries, or vendor model weights are included. Tested on UniFi Protect 7.3.74, 7.4.112, and 7.4.114.

UniFi Protect showing Keystone adopted as a virtual AI Key and AI Port

What you get

These defaults describe the sample config.yaml. The guided installers prompt for feature choices, and the Home Assistant OS app has its own defaults.

  • Plain-English & photo search (Find Anything) — on by default Type "red Tesla today" or "person with a backpack last hour" — or upload a reference photo — right in Protect's native search bar. Works locally on CPU with no extra setup.

  • Event descriptions — needs a vision model (Ollama or API) Turn vague "Vehicle detected" alerts into sentences like "White sedan driving past on the driveway" or "UPS driver carrying a cardboard box to the front porch." Checks multiple moments in each clip so passing cars aren't called parked, shares recent context across cameras, and supports one-click summaries on any event.

  • Smart detections on third-party cameras (virtual AI Port) — off by default Pair up to 10 HD ONVIF cameras (Reolink, Amcrest, or Nest via Scrypted) to get native person, vehicle, animal, package, and audio detections, plus custom zones, line crossing, and loitering — all inside Protect.

  • Face recognition & Enhance Face — off by default Recognize people on G4, G5, and paired third-party cameras directly in Protect's Faces, optionally use household names in captions ("Alex walks up to the front door"), and sharpen blurry face crops with Enhance Face. Unknown people stay unnamed.

  • License plate recognition — off by default Read plates locally on G4, G5, and paired third-party cameras and file them under Protect's Known Vehicles. Optionally map plates in config.yaml so captions say "Alice's sedan pulls into the driveway."

  • Speech transcripts & smart audio — off by default Transcribe what was said on audio-capable cameras into Protect's event timeline (speech-to-text, not spoken narration of descriptions). Paired third-party cameras also support all 9 Protect Smart Audio alarms (speech, barking, baby crying, smoke/CO alarms, sirens, burglar/car alarms, car horns, and glass break).

  • Native Protect filters, alarms & Home Assistant Descriptions automatically map to Protect's built-in tags (tesla, ups, dog, backpack, red, …) so Protect filters and automations work out of the box. Optional webhooks and MQTT send descriptions to Home Assistant or ntfy.

Keystone's local status dashboard: overall health, service cards, paired cameras and the activity feed

Quick start

Pick the install method that matches your setup. Every method sets up both Keystone and the local search database Protect 7.3+ uses for Find Anything.

Home Assistant OS

Open Keystone in Home Assistant

  1. Open Keystone with the badge and confirm adding the app repository if prompted. You can also add https://github.com/seeARMS/keystone under Settings → Apps → Install app → ⋮ → Repositories.
  2. Select Keystone and choose Install. In Configuration, enter your Protect console's IPv4 address and optionally configure a vision endpoint for event descriptions. Review the feature switches and model terms, then save and start the app.
  3. In UniFi Protect → UniFi Devices, adopt the AI Key at your Home Assistant host's LAN address and follow the Find Anything setup.

Install updates from Settings → Apps → Keystone. Home Assistant keeps Keystone's settings, adoption state and search database across updates. See the app documentation for hardware sizing, port conflicts and troubleshooting.

If you use Home Assistant Container, run Keystone alongside it with Docker Compose.

Docker Compose

On a Linux host with Docker Compose and Python 3 (no repository clone needed):

mkdir keystone && cd keystone
curl -fsSLO https://raw.githubusercontent.com/seeARMS/keystone/main/docker-compose.yml
curl -fsSLO https://raw.githubusercontent.com/seeARMS/keystone/main/scripts/setup-compose.py
python3 setup-compose.py
docker compose up -d

During setup, enter your UniFi Protect controller's IP address. If you want event descriptions, enter your Ollama or AI server URL; press Enter to skip descriptions for now (Find Anything search still works right away).

Docker Desktop on macOS/Windows and OrbStack on macOS: Prefer native Homebrew on macOS or a Linux VM bridged to Protect's LAN. These Docker runtimes can rewrite inbound LAN source addresses, so adoption and PostgreSQL's pg_hba.conf see a VM gateway (for example, 192.0.2.1) or 127.0.0.1 (OrbStack host mode) in place of Protect's IP. LAN UDP 10001 broadcasts do not reach the VM through published ports.

If NAT is unavoidable, keep the controller setting pointed at Protect. Set KEYSTONE_CONTROLLER_TRUSTED_PEERS to the observed gateway IP or a comma-separated list of source IPs/CIDRs and KEYSTONE_DEVICE_ADVERTISE_IP to the address Protect can reach. Set both in Compose's .env or in the keystone-aio container environment. Every host behind the same gateway can pass the source-IP check, so restrict access to the published ports to Protect before NAT. For initial discovery when LAN UDP 10001 broadcasts cannot reach the container, use one of the cross-VLAN / routed adoption options (UDP 10001 relay or keystone announce --port <PROTECT_UDP_PORT>).

Updating, shared Docker hosts (OMV / TrueNAS / Synology), and why host networking?
  • Updating: Run docker compose pull && docker compose up -d. If a release updates docker-compose.yml or setup options, re-download docker-compose.yml and setup-compose.py and rerun python3 setup-compose.py first — it keeps your existing settings and database password.
  • Changing trusted peers: keystone-aio regenerates PostgreSQL rules on every start. The separate Compose PostgreSQL image applies its rules at first initialization. For existing Compose databases, add or remove the relevant hostssl unifi-protect unifi-protect <cidr> scram-sha-256 lines in pgdata/pg_hba.conf before the final reject rules, then reload PostgreSQL. Use /32 for a single IPv4 address or /128 for a single IPv6 address.
  • Pinning versions or building locally: latest tracks the newest release. Set KEYSTONE_IMAGE_TAG in .env to pin a version (for example KEYSTONE_IMAGE_TAG=0.1.1) or follow main with edge. To build from a cloned checkout instead of pulling from GHCR, run docker compose -f docker-compose.yml -f docker-compose.build.yml up -d --build.
  • Why host networking? Both containers use network_mode: host so Protect can discover Keystone on your LAN and reach the exact ports it expects. By default PostgreSQL restricts its admin account to loopback and Protect's account to your controller's IP over TLS. Keystone runs as a non-root user with only NET_BIND_SERVICE on python3.
  • Shared Docker hosts (OMV, TrueNAS, Synology, Portainer): Host networking can collide with existing services on ports 443, 5432, 8080, or 10001/udp. Run the all-in-one image (ghcr.io/seearms/keystone-aio) on its own LAN IP with Docker macvlan, set KEYSTONE_CONTROLLER_HOST to Protect's IP, and mount persistent storage at /data. See dedicated-IP deployments.
  • TrueNAS SCALE (24.10+ / HexOS):
    • sudo for Docker: truenas_admin does not have direct access to /var/run/docker.sock, so prefix docker compose / docker exec commands with sudo.
    • Port 443 conflict with Virtual AI Port: With network_mode: host, the TrueNAS web GUI already binds TCP 443, and UniFi Protect hardcodes port 443 for AI Port adoption (changing aiport.mgmt_port alone will fail adoption). Either move TrueNAS's Web Interface HTTPS port off 443 (for example to 9443, leaving HTTP-to-HTTPS HSTS redirect disabled if you run HTTP apps like Plex on the same host), or run ghcr.io/seearms/keystone-aio on its own dedicated LAN IP via Docker macvlan on a spare NIC.
    • TrueNAS Ollama catalog app: The official TrueNAS Ollama app exposes port 30068 on the host instead of 11434 — pass http://192.0.2.50:30068 (using your NAS IP) at the Ollama URL prompt.
    • Headless LAN dashboard: Answer y at the setup prompt (or set web.bind_host: 0.0.0.0 / KEYSTONE_WEB_BIND_HOST=0.0.0.0) on a trusted LAN to open http://<NAS-IP>:8088 without an SSH tunnel.

Proxmox LXC, Debian, or Ubuntu

On a Proxmox host (creates a Debian 13 LXC with 2 cores, 4 GB RAM, and a 16 GB disk):

bash -c "$(curl -fsSL https://raw.githubusercontent.com/seeARMS/keystone/main/scripts/proxmox-lxc.sh)"

Inside an existing Debian 13+ or Ubuntu 24.04+ container or VM (run as root):

bash -c "$(curl -fsSL https://raw.githubusercontent.com/seeARMS/keystone/main/scripts/install.sh)"

Enter your Protect controller's IP and an optional vision server URL (leave it blank to start with Find Anything search only). The first start downloads about 1.6 GB of models.

VLANs, static IPs, and updating Proxmox / Linux installs
  • The Proxmox script uses vmbr0 with DHCP by default. Set KEYSTONE_VLAN, or KEYSTONE_IP and KEYSTONE_GATEWAY, before running it for a VLAN or static IP (other options are listed at the top of scripts/proxmox-lxc.sh). Give the container a fixed address (DHCP reservation or static IP) so Protect keeps finding it.
  • Config lives at /etc/keystone/config.yaml. Apply edits with systemctl restart keystone.
  • To update, run the install.sh one-liner again inside the container or VM — it keeps your config, database, and state.

Unraid

Add the template from the Unraid terminal (until it's in Community Applications):

wget -O /boot/config/plugins/dockerMan/templates-user/my-Keystone.xml \
  https://raw.githubusercontent.com/seeARMS/keystone/main/unraid/keystone.xml

Then go to Docker → Add Container and choose Keystone. Set Network Type to br0 with a fixed IP, enter your Protect controller's IP (and optionally a vision provider/URL for descriptions), and apply. Everything is stored in /mnt/user/appdata/keystone; template fields override the matching settings in config.yaml.

macOS / Apple Silicon (Homebrew)

Use macOS Sequoia (15) or newer on an Apple Silicon or Intel Mac on the same LAN as UniFi Protect. Keystone runs natively on macOS so Protect can discover it over UDP without a Docker VM (Docker Desktop does not support LAN host networking). Run these commands as the Homebrew owner. If you started the selected PostgreSQL cluster manually with pg_ctl, stop it with the same cluster manager after setup and before install-daemons. The LaunchDaemon then starts the cluster with its updated listen address:

brew tap seearms/keystone
brew install keystone
keystone macos setup
sudo "$(brew --prefix)/bin/keystone" macos install-daemons
keystone doctor

During setup, enter your Protect console's IPv4 address and an optional Ollama URL (leave it blank to start with Find Anything search only). The installer starts Keystone and PostgreSQL as the Homebrew owner and migrates existing Homebrew user services. Open the dashboard at http://127.0.0.1:8088 and adopt AI Key in UniFi Protect → UniFi Devices. On Apple Silicon, see Apple Silicon acceleration & Mac mini sizing to enable CoreML, VideoToolbox decode, and local captions.

If Protect lists an AI Key with a blank host and adoption fails under brew services, check System Settings → Privacy & Security → Local Network for Homebrew Python. A user LaunchAgent can miss multicast and broadcast discovery while a foreground run answers the same probes. To switch an existing setup, run the install-daemons command above (add -c /path/to/config.yaml for a custom config). System LaunchDaemons have automatic Local Network access. Apple’s Local Network privacy technote

Open UniFi Devices and run keystone doctor again. With the dashboard enabled, it reports UDP datagrams received, reply attempts, direct unicast announces, and socket errors since startup. If you rely on inbound discovery and the reply count stays at zero, run sudo tcpdump -ni en0 udp port 10001 during discovery (substitute your LAN interface) to see whether console probes reach the Mac. Use sudo lsof -nP -iUDP:10001 to identify other listeners such as a discovery relay.

Headless Mac mini (LaunchDaemons), AI Port TCP 443, local Ollama, config paths & upgrades
  • Config, state & upgrades: Config lives at $(brew --prefix)/etc/keystone/config.yaml, state and downloaded models at $(brew --prefix)/var/lib/keystone, and logs at $(brew --prefix)/var/log/keystone. Upgrade with brew upgrade keystone, then rerun install-daemons with your original flags. These paths persist across upgrades.

  • Unattended setup & existing PostgreSQL clusters: Run keystone macos setup --non-interactive --controller 192.0.2.10 --ollama disabled with your console's address. Setup selects an initialized Homebrew cluster with pgvector (or a compatible cluster already serving port 5432) and restricts Protect's PostgreSQL login to the controller's IPv4 address. If the controller moves, rerun setup with the new address. keystone doctor checks the binaries, TLS, database extensions, password-rotation permissions, listeners, controller reachability, and any configured Ollama endpoint.

  • Headless Mac mini & AI Port TCP 443 (LaunchDaemons): For startup before login or to bind the virtual AI Port on TCP 443, set aiport.enabled: true in config (if wanted), then run:

    sudo "$(brew --prefix)/bin/keystone" macos install-daemons

    This switches Keystone and PostgreSQL from user-level brew services to system LaunchDaemons running as the non-root Homebrew owner, with launchd handing off TCP 443 when AI Port uses port 443. Rerun with the same flags after changing AI Port port/enablement or upgrading Keystone; remove with sudo "$(brew --prefix)/bin/keystone" macos uninstall-daemons.

  • Power & FileVault: Keystone holds an idle-sleep assertion while running (KEYSTONE_MACOS_PREVENT_SLEEP=false opts out). Pass --configure-power to install-daemons for a dedicated headless Mac (sudo pmset -a sleep 0 autorestart 1 womp 1). If FileVault is enabled on Apple Silicon, confirm how your Mac handles cold-boot unlock before relying on pre-login startup.

  • Interactive AI Port development with macOS PF: Keep aiport.mgmt_port: 8443 and add an active rdr-anchor "keystone" in your PF translation ruleset (substituting interface, Protect IP, and Mac IP):

    rdr pass on en0 inet proto tcp from 192.0.2.10 to 192.0.2.50 port 443 -> 192.0.2.50 port 8443
    

    Load with sudo pfctl -a keystone -f /path/to/keystone.pf (keeps the controller's source IP for peer checks) and run keystone run -c "$(brew --prefix)/etc/keystone/config.yaml".

  • Optional local vision (Ollama or MLX-VLM): Install Ollama with brew install ollama, start it with brew services start ollama (or pass --with-ollama to keystone macos install-daemons for headless startup), pull a model (for example ollama pull qwen3.5:9b, or qwen3.5:4b-q4_K_M on 16 GB Macs), set vision.provider: ollama and vision.base_url: http://127.0.0.1:11434, and restart Keystone. See Mac mini sizing for local captions for MLX-VLM setup, or Event descriptions for remote/cloud backends.

Manual install (Python 3.12+ / systemd without Docker)
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"

keystone init --controller 192.0.2.10 --ollama http://192.0.2.20:11434 --model qwen3.5:9b
keystone trust -c config.yaml --pin
keystone run -c config.yaml

For Find Anything search on Protect 7.3+ without Docker Compose, install PostgreSQL 16+ with pgvector, enable TLS (ssl = on), run docker/init-protect-db.sql, and set device.sync_postgres_password: true in config.yaml.

Status dashboard: Keystone runs a local status page on 127.0.0.1:8088 (no login). On a headless host, tunnel it with ssh -L 8088:127.0.0.1:8088 user@192.0.2.50 and open http://127.0.0.1:8088 — or set web.bind_host: 0.0.0.0 in config.yaml on a trusted LAN.

After adopting in Protect

Open UniFi Protect → UniFi Devices and adopt the discovered AI Key. Initial credentials are ubnt / ubnt and Protect rotates them automatically on adoption.

The Home Assistant OS app starts with Speech-to-Text, License Plate Recognition, Enhance Face, Face Recognition and AI Port enabled. Use its Configuration switches to manage them. The table below shows the defaults for config.yaml. Event descriptions require a vision server (Ollama or an API).

Feature Default Turn on in config.yaml Turn on in UniFi Protect
Find Anything search On Already enabled (embeddings.enabled: true) Settings → Intelligence → Basic Understanding (7.3: Basic Object Recognition), plus Smart Detections on each camera
Event descriptions Needs vision model (off if URL left blank) Set vision.provider, vision.base_url, and vision.model Settings → Intelligence → Basic Understanding (7.3: AI Summary; see Protect 7.4 note below)
Speech-to-Text (event transcripts) Off stt.enabled: true Settings → Intelligence → Basic Understanding (7.3: Speech-to-Text; see Protect 7.4 note below), plus Speech audio detection on cameras with a mic
Face recognition Off faces.enabled: true G4/G5 cameras: Legacy Camera Enhancement → Face Recognition
Paired ONVIF cameras: Face smart detection
License plates Off lpr.enabled: true G4/G5 cameras: Legacy Camera Enhancement → License Plate Recognition
Paired ONVIF cameras: License Plate smart detection
Enhance Face Off enhance.enabled: true Enhance button on face crops in Protect
Third-party cameras (AI Port) Off aiport.enabled: true Adopt AI Port in UniFi Devices, pair ONVIF cameras, enable smart detections
Backfill older events Off embeddings.retroactive_processing: true Starts automatically once enabled

After editing config.yaml, restart Keystone (docker compose restart, systemctl restart keystone, sudo launchctl kickstart -k system/com.seearms.keystone for a macOS system LaunchDaemon, brew services restart keystone for a Homebrew user service, or restart the Unraid container). For system LaunchDaemons, rerun install-daemons with your original flags if AI Port settings changed. Protect picks up newly enabled features automatically — no re-adoption needed.

Protect 7.4+ (Basic Understanding): UniFi Protect 7.4 combined Object Indexing, AI Summary, and Speech to Text into a single Settings → Intelligence → Basic Understanding ("Basic Object Recognition") card — there are no separate AI Summary or Speech-to-Text toggles. On a fresh adoption, Basic Understanding can appear On (All) even though AI Summary and Speech to Text are still off underneath (Protect will not send speechToText jobs until Speech to Text is enabled). To turn all three on for all supported cameras, toggle Basic Understanding Off, then back On, and click Apply Changes — or switch it to Selected Only to reveal and toggle the individual Object Indexing, Speech to Text, and AI Summary icons per camera.

Tip: Not seeing descriptions or transcripts? Open the Keystone dashboard (:8088). Every service card shows whether it's Ready, Off / Disabled (with the config key to turn it on), Off in Protect (when Protect itself has Speech-to-Text turned off), or reporting an error. In Protect's event player, click the NeXT AI Summary sparkle icon in the player toolbar to open saved event descriptions (it starts collapsed until clicked once). Note also that Speech-to-Text transcribes spoken audio from camera microphones into text — Keystone does not generate spoken audio narration of descriptions.

Resetting adoption ("Connected to another console" / "Reassign this device")

If UniFi Protect flags a virtual device as "Connected to another console" or "Reassign this device" with no Forget/Remove button (for example after recreating a container or migrating consoles), stop Keystone and run keystone reset-adoption to wipe only its MAC identity, device certificates, and controller TLS pins while keeping downloaded models, your face gallery, and activity history:

# Docker Compose (prefix with sudo on TrueNAS SCALE)
docker compose stop keystone
docker compose run --rm keystone reset-adoption --yes
docker compose up -d

# Linux / Proxmox LXC (systemd)
systemctl stop keystone
/opt/keystone/venv/bin/keystone reset-adoption -c /etc/keystone/config.yaml --state-dir /var/lib/keystone --yes
systemctl start keystone

# macOS Homebrew with system LaunchDaemons
plist=/Library/LaunchDaemons/com.seearms.keystone.plist
config=$(/usr/bin/plutil -extract ProgramArguments.3 raw "$plist") &&
  sudo launchctl bootout system/com.seearms.keystone &&
  env -u KEYSTONE_STATE_DIR keystone reset-adoption -c "$config"
sudo launchctl bootstrap system "$plist"

Pass --target aikey or --target aiport to reset only one virtual device, or --dry-run to preview which files will be removed. Restarting generates fresh MAC(s) and certificates; if Protect still shows the old cached MAC card, hard-refresh your browser and restart UniFi Protect to clear its stale discovery entry.

Setting up optional features

Event descriptions (Ollama, LM Studio, oMLX, OpenAI, Anthropic)

To turn on event descriptions, point vision in config.yaml at a vision-capable model, then enable Basic Understanding (toggle Off → On and Apply Changes, or enable the AI Summary icon under Selected Only; on Protect 7.3, enable AI Summary) under Protect → Settings → Intelligence. To read saved descriptions in Protect, open an event and click the NeXT AI Summary sparkle button in the player toolbar (Protect remembers it open afterward).

  • Ollama (default provider): keep vision.provider: ollama and set vision.base_url (for example http://192.0.2.20:11434) and vision.model (default qwen3.5:9b, or qwen3.5:4b for smaller GPUs).
  • LM Studio, oMLX, llama.cpp, or vLLM: set provider: openai-compatible, use the server's /v1 base URL, and set model to the exact model ID it serves:
vision:
  provider: openai-compatible
  base_url: http://192.0.2.20:1234/v1
  model: your-vision-model
  # api_key: set-if-required
  • Hosted OpenAI or Anthropic: set provider to openai or anthropic, base_url to https://api.openai.com/v1 or https://api.anthropic.com/v1, plus model and api_key.
  • Skip descriptions: set vision.provider: disabled. Find Anything search and detections still work with no vision server.

With vision enabled, Keystone keeps processing video and image event captions past its 120-second window for replying to Protect. During bursts, excess captions wait in the queue so on-demand summaries can take the next available vision slot. Each job has up to 10 minutes from the time a worker takes it from the queue. Individual model requests still use vision.timeout_seconds. Keystone attempts to send late results to Protect. If Protect rejects one, you can still search its caption in the Keystone dashboard's activity history. Protect must accept the result to index its CLIP embeddings for Find Anything.

To stop spending compute on expired captions, set vision.process_past_deadline: false or KEYSTONE_VISION_PROCESS_PAST_DEADLINE=false. This restores the 120-second limit from admission, including time spent waiting.

Extra vision options (single-image models, camera layout hints)
  • OpenAI-compatible servers must accept image inputs and JSON mode (response_format: {"type": "json_object"}) on /v1/chat/completions.
  • If your model only accepts one image per request (or you want faster descriptions), set vision.frame_layout: strip to combine the 3 frames into one image, or hybrid for a motion strip plus one full-res keyframe. Lowering vision.max_image_side to 640 also speeds up prompt evaluation.
  • You can add optional per-camera layout hints under cameras: in config.example.yaml so descriptions know which way is entering vs. exiting or which road is the public street.

Third-party cameras (virtual AI Port & Nest)

Turn on the virtual AI Port in config.yaml:

aiport:
  enabled: true

Set the camera's main stream to H.264 (AVC) before pairing. The virtual AI Port requires H.264 for live view and recordings. With H.265 (HEVC), detections can still work while Protect receives no video from the relay. Change the encoding on the camera or in the ONVIF bridge that provides the stream.

Restart Keystone, adopt the discovered AI Port in UniFi Protect → UniFi Devices, pair your ONVIF cameras (or older UniFi cameras without smart detections) to it (up to 10 HD cameras), and enable the smart detections you want on each camera. Package detection and all 9 Protect Smart Audio alarms load automatically only when you enable them in Protect.

Nest and other cloud cameras: Protect only adds third-party cameras that speak ONVIF. Use Scrypted (with its Google Device Access and ONVIF plugins) to expose each Nest camera to Protect as an ONVIF camera, then pair it with Keystone's AI Port like any other third-party camera. UniFi and ONVIF cameras don't need Scrypted.

Scaling beyond one AI Port (multiple LAN IPs / avoiding host port 443)

UniFi Protect caps how many cameras can pair with one AI Port based on resolution (up to 10× 1080p, or fewer for 2K/4K streams) and requires TCP 443 per AI Port. To add more virtual AI Ports — or keep the AI Port off a NAS web UI's port 443 — run lightweight AI-Port-only instances (device.enabled: false / KEYSTONE_DEVICE_ENABLED=false) on separate LAN IPs:

  • No extra PostgreSQL, AI Key, or CLIP RAM: Setting KEYSTONE_DEVICE_ENABLED=false disables the virtual AI Key, search database sync, CLIP embeddings, and VLM worker on the extra container so it only runs the virtual AI Port (~0.5 GB RAM plus optional KEYSTONE_FACES_ENABLED / KEYSTONE_LPR_ENABLED). Your primary Keystone AI Key still handles Find Anything search and event descriptions for every camera on the console.
  • Docker macvlan (recommended): Use docker-compose.aiport.yml to give each extra AI Port its own LAN IP on a physical NIC (KEYSTONE_AIPORT_PARENT_IFACE, KEYSTONE_AIPORT_SUBNET, KEYSTONE_AIPORT_GATEWAY, KEYSTONE_AIPORT_IP). Each container gets its own :443 and automatic UDP 10001 LAN discovery. (Linux macvlan containers cannot talk directly to the Docker host IP without a macvlan shim, which is fine for AI-Port-only containers because they only connect to Protect and your cameras.)
  • Dedicated IP on an existing host (IP alias / spare NIC): On a host with a secondary LAN IP (for example 192.0.2.51), set aiport.bind_host: 192.0.2.51 and aiport.advertise_ip: 192.0.2.51 (or KEYSTONE_AIPORT_BIND_HOST / KEYSTONE_AIPORT_ADVERTISE_IP) to bind :443 only on that address. Any other service or primary AI Port using port 443 on the same host must also bind its own specific IP rather than 0.0.0.0:443. When running multiple Keystone processes in the same host network namespace, give each extra instance its own state_dir (KEYSTONE_STATE_DIR) and aiport.hostname, disable its dashboard (web.enabled: false) or assign a distinct web.port, and set device.discovery_enabled: false (adopting the extra AI Port by IP in Protect so only one process owns UDP 10001).

The standalone Compose file uses the project name keystone-aiport-2 so you can keep it beside the primary stack. If you set COMPOSE_PROJECT_NAME in a shared .env, pass -p keystone-aiport-2 on standalone Compose commands to keep the projects separate.

Upgrading an existing standalone container. To move it from the old shared project, run the commands below from the existing Compose directory. Substitute your container name in the first command if you customized it. The first Compose command removes the old AI Port container and its macvlan network. Keep ./state-aiport-2 mounted at /state to preserve its adoption identity, and omit --remove-orphans so the primary stack keeps running.

old_project=$(docker inspect -f '{{ index .Config.Labels "com.docker.compose.project" }}' keystone-aiport-2)
COMPOSE_REMOVE_ORPHANS=false docker compose -p "$old_project" -f docker-compose.aiport.yml down
docker compose -p keystone-aiport-2 -f docker-compose.aiport.yml up -d

Each AI Port dashboard lists only cameras paired to that instance. To view a standalone port's cameras, set KEYSTONE_AIPORT_WEB_ENABLED=true and open http://<AI-Port-IP>:8088/#cameras from your trusted LAN.

To show Protect names alongside MAC addresses, open Integrations in your console's Protect app and create an API key with read access to the paired cameras. For the standalone Compose template, set KEYSTONE_CONTROLLER_API_KEY in its .env and recreate the container. Deployments that load a config.yaml can also set controller.api_key there. Keystone refreshes the local Protect camera list every five minutes over HTTPS on TCP 443. It pins the console's certificate on first use by default. To verify the certificate on the first connection too, set KEYSTONE_CONTROLLER_API_FINGERPRINT to its independently verified SHA-256 fingerprint. If your deployment loads a config.yaml, an explicit name in its cameras: section takes precedence. Cameras without a known name display their MAC address.

Speech-to-Text (event transcripts)

Off by default. Turn it on in config.yaml:

stt:
  enabled: true
  backend: onnx           # local Whisper on CPU (or "openai" for a remote Whisper server)
  model: whisper-base     # whisper-tiny | whisper-base | whisper-small

Restart Keystone, then enable Speech-to-Text under Protect → Settings → Intelligence (on Protect 7.4+, toggle Basic Understanding Off → On and click Apply Changes, or switch to Selected Only and toggle the Speech to Text icon per camera; on Protect 7.3, enable Speech-to-Text) plus Speech audio detection on audio-capable cameras. Runs locally on CPU with no extra packages; cameras without a microphone return an empty transcript instead of stalling.

License plate recognition

Off by default. Turn it on in config.yaml:

lpr:
  enabled: true

# Optional: name known vehicles in event descriptions
# vehicles:
#   ABC1234: "Alice's white sedan"

Restart Keystone, then enable Legacy Camera Enhancement → License Plate Recognition on G4/G5 cameras (or License Plate smart detection on cameras paired to the AI Port). Plates appear under Known Vehicles in Protect.

Face recognition & Enhance Face

Both are off by default. Turn on whichever you want in config.yaml:

faces:
  enabled: true           # feeds Protect's Faces (no photo folder required)

enhance:
  enabled: true           # answers Protect's "Enhance" button on face crops
  backend: gfpgan         # or "pillow" for a zero-download, low-RAM fallback

Restart Keystone, then enable Legacy Camera Enhancement → Face Recognition on G4/G5 cameras (or Face smart detection on AI Port cameras). You can name people directly inside Protect's Faces tab without creating a photo folder. If you also want household names used inside written event descriptions, add a local photo gallery (see below).

Model license notice: Face recognition downloads pretrained InsightFace weights at runtime (verified by SHA-256). InsightFace licenses these weights for non-commercial research only. For other uses, including routine household monitoring, obtain appropriate rights before enabling faces.enabled: true. See InsightFace's licensing terms. Keystone does not bundle or redistribute them.

Biometric & privacy notice: When faces.enabled: true, Keystone computes a temporary face embedding for every clear face detected in person events (not only people in your gallery). You are responsible for complying with applicable local biometric and privacy laws — such as Illinois BIPA or GDPR — especially where cameras cover public or shared spaces.

Local face gallery (names in captions), CLI tools, and G6 merge tip

To use household names inside event descriptions ("Alex walks up to the front door"), put 5–10 clear, varied photos of each person in <state_dir>/faces/<Person Name>/ (one clear face per photo; lock down with chmod 700). Keystone syncs the folder automatically when files change.

Useful commands:

keystone faces list -c config.yaml                    # people, photo counts, look-alike check
keystone faces sync -c config.yaml --force            # re-embed the whole gallery
keystone faces test -c config.yaml frame.jpg clip.mp4 # test matches and scores
  • Conservative by default: Blurry, distant (min_face_px: 40), or side-profile faces are skipped, and a person is only named when their match clears min_similarity (0.45) and beats the runner-up by min_margin (0.10). The vision model is never allowed to guess a name.
  • Cross-camera carryover: When a person is clearly recognized on one camera, Keystone can carry their name to nearby cameras within 90 seconds if the appearance or companion object (car, dog, package) matches with high confidence and no conflicting face is visible.
  • G6 cameras: Keystone's face clusters start separate from G6 cameras' built-in clusters in Protect. Merge the same person's groups once in Protect → Faces and later sightings follow automatically.
  • Enhance Face (enhance.enabled: true): Uses GFPGAN v1.4 (Apache-2.0, ~340 MB download, ~1 s per face on 2 CPU threads) and automatically unloads from RAM after 5 idle minutes (idle_unload_seconds: 300). Falls back to pillow if the model can't load.
Backfilling older events (retroactive Find Anything search)

Off by default so existing installs don't kick off a multi-hour backfill unexpectedly. On Protect 7.3.74+, set embeddings.retroactive_processing: true (or KEYSTONE_EMBEDDINGS_RETROACTIVE=true) and restart Keystone.

  • Protect sends historical events in batches and marks each done as Keystone indexes it.
  • Backfill uses a separate queue. Live jobs are dispatched first. On macOS, historical thumbnails are encoded in smaller batches so live jobs and camera analyzers have more frequent opportunities to run.
  • Low-power hosts: Set embeddings.retroactive_batch_delay_ms: 200 (or 500) on a Raspberry Pi or N100 mini PC to leave CPU headroom during long backfills.
  • Track progress on the dashboard's Find Anything card or in /api/status. During startup, search.semanticIndex.ready can be false with zero tags while the index loads. AI Port per-camera framesAnalyzed and eventsEmitted counters reset on restart.

Hardware & sizing

What computer do I need?

  • RAM & CPU:
    • 2–3 GB RAM (Raspberry Pi, N100 mini PC, small LXC): works for Find Anything search and a few cameras with low-RAM settings (embeddings.quantization: int8).
    • 4 GB RAM, 2–4 CPU cores (typical): comfortable for Find Anything search and up to ~7 HD third-party cameras on CPU.
    • 8 GB RAM: recommended if you turn on faces, license plates, speech transcripts, and Enhance Face all at once.
  • Do I need a GPU?
    • Not for search, third-party detections, faces, plates, or transcripts — those all run well on CPU (and supported models can use Intel OpenVINO, NVIDIA CUDA, AMD MIGraphX, or Apple Silicon CoreML).
    • Helpful for local event descriptions: A discrete GPU with 6–12 GB VRAM (e.g. RTX 3060/4060, Intel Arc, or an Apple Silicon Mac with unified memory — see Mac mini sizing) writes descriptions in 2–5 seconds using qwen3.5:9b (or qwen3.5:4b on 6–8 GB cards). An integrated GPU works too, at about 20–25 seconds per description. Without a GPU, you can use a hosted OpenAI or Anthropic API or disable descriptions.
  • Google Coral: Not supported. Keystone uses ONNX models that don't fit in Coral's ~8 MB memory, and regular CPUs handle motion-gated detection easily (~6% CPU for seven 1080p cameras on an Intel Core Ultra 5).

Memory & speed at a glance

Feature Memory Typical speed Notes
Base (Find Anything + AI Port detections) ~3.5–4.5 GB RAM (~2 GB with int8) Instant search; ~6% CPU for 7× 1080p cameras Runs on CPU
Event descriptions (vision model) 6–12 GB VRAM on your Ollama host (or cloud API) 2–5 s (discrete GPU) / ~24 s (iGPU) Optional; runs on separate box or cloud
Face recognition (optional) +0.3–0.5 GB RAM ~0.1–0.3 s per frame CPU
Speech transcripts (optional) +0.3 GB RAM (whisper-base) < 1 s for a 30 s clip CPU (whisper-small uses ~1 GB)
License plates (optional) +0.15 GB RAM ~50 ms per frame CPU; shared across AI Key & AI Port
Package detection (AI Port) ~11 MB model (loads only if used) ~60–100 ms per scan CPU; loads when enabled in Protect
Tuning for 2–4 GB hosts (Raspberry Pi, N100, small LXCs) & faster descriptions
Profile Settings CLIP RAM (measured)¹ Est. Keystone total²
Full (default) quantization: fp32, lazy_text_model: true, analyze_max_width: 960 ~1.6 GB idle, ~2.3 GB after first text search ~3.5–4.5 GB
Balanced quantization: int8 ~0.42 GB idle, ~0.55–0.8 GB after first text search ~2–3 GB
Lite int8, text_model_idle_unload_seconds: 300, analyze_max_width: 640, detector_variant: yolox_tiny, embeddings.threads: 2 ~0.42–0.8 GB ~1.5–2 GB
  • embeddings.quantization: int8 (KEYSTONE_EMBEDDINGS_QUANTIZATION) is the biggest RAM saver (~65–74% less RAM than fp32). On ARM CPUs, search quality matches fp32 closely (cosine ≥ 0.986); on x86 AVX2 CPUs there is a slight drop in ranking precision, so keep fp32 if you have ≥ 4–6 GB RAM. Avoid fp16 on CPU (slower and uses more RAM; GPU only) and q4 (about 4× slower on CPU).
  • embeddings.lazy_text_model: true (default) only loads the search text encoder on your first Find Anything query. Set embeddings.text_model_idle_unload_seconds: 300 to free it again when idle.
  • aiport.analyze_max_width: 640 (default 960, min 320) lowers decode CPU on paired ONVIF cameras without affecting detection zone accuracy.
  • Faster descriptions: Set vision.frame_layout: hybrid or strip to cut vision latency roughly in half, or lower vision.max_image_side to 640.

¹ onnxruntime CPU provider, 4 threads, per-process RSS. ² Whole-process estimate; actual usage depends on camera count and enabled features.

Optional Intel GPU / NPU acceleration (OpenVINO & VA-API)

Keystone defaults to CPU and software video decode on Linux so it works everywhere with no drivers. On Intel Core Ultra, Arc, or N100 hosts, you can offload ONNX models to OpenVINO and AI Port video decode to VA-API:

pip install -e ".[openvino]"
acceleration:
  provider: auto                  # auto | cpu | openvino | coreml | cuda | migraphx
  openvino_device: "AUTO:GPU,CPU" # GPU | NPU | CPU | AUTO:GPU,CPU | AUTO:NPU,GPU,CPU
  ffmpeg_hwaccel: auto            # none | auto | vaapi | videotoolbox (AI Port decode only)

If OpenVINO or VA-API fails to initialize, Keystone logs a warning and falls back to CPU automatically. Active providers show up on the status dashboard and in /api/status.

Troubleshooting Intel GPU resets (Linux xe driver) & OpenVINO cache
  • Compiled OpenVINO blobs are cached in <state_dir>/ov_cache across restarts (acceleration.openvino_cache_dir). Precision defaults to openvino_precision: FP16 (GPU/NPU only) and VA-API defaults to ffmpeg_device: /dev/dri/renderD128.
  • GPU resets on Intel Linux xe drivers (Xe2/Xe3): OpenVINO's GPU plugin can hit a CCS page fault / Engine memory CAT error when Intel compute-runtime (NEO) packs pooled OpenCL USM buffers against an unmapped 16 MiB boundary. Keystone sets GPU_ENABLE_LARGE_ALLOCATIONS=YES by default on GPU sessions (acceleration.openvino_gpu_large_allocations: true) to bypass that pool. With onnxruntime-openvino 1.24 / OpenVINO 2025.4, set openvino_device: GPU directly so OpenVINO's AUTO plugin doesn't strip the property.
  • Automatic recovery: If a GPU reset still drops the OpenCL context (CL_OUT_OF_RESOURCES), after 3 device-lost errors within 2 minutes Keystone logs the cause and exits with code 75 so systemd or Docker restarts it with a fresh context. If that happens 3 times within 30 minutes, Keystone starts on CPU instead to prevent a restart loop, and the dashboard flags the GPU as suspended. A manual restart (systemctl restart keystone / docker compose restart) clears that history and retries the GPU. Tune or disable with acceleration.restart_on_gpu_loss, gpu_loss_max_restarts, and gpu_loss_window_minutes (set restart_on_gpu_loss: false if running without a process supervisor).

NVIDIA CUDA with Docker Compose

The CUDA build can run the CLIP image and text encoders, face detector and recognizer, plate detector and OCR, and GFPGAN face enhancer on an NVIDIA GPU. It was tested on a DGX Spark (Linux ARM64) with the default FP32 CLIP models. The host needs a CUDA 13.0-compatible NVIDIA driver, Docker Compose 2.30 or newer, and the NVIDIA Container Toolkit configured for Docker.

From a Keystone repository checkout, prepare your configuration and start the stack:

python3 scripts/setup-compose.py
docker compose -f docker-compose.yml -f docker-compose.cuda.yml up -d --build

The override builds a local image, exposes the GPU and sets KEYSTONE_ACCEL_PROVIDER=cuda. Native installations with a compatible ONNX Runtime GPU wheel and libraries can select acceleration.provider: cuda in config.yaml. Keystone retries on CPU if CUDA initialization or inference fails, including non-finite outputs. The dashboard shows the active provider for each loaded model. The text encoder can show Unloaded until its first search.

AMD GPUs (MIGraphX)

With an ONNX Runtime build that includes the MIGraphX execution provider (ROCm), acceleration.provider: migraphx runs the AI Port detector, the CLIP image encoder, the face detector and recognizer, the plate detector, and the GFPGAN face enhancer on an AMD GPU. MIGraphX compiles a separate program for each input shape, so the CLIP text encoder and plate OCR, whose inputs vary in size, stay on the CPU, and CLIP embeds one image at a time. Check that python -c "import onnxruntime; print(onnxruntime.get_available_providers())" lists MIGraphXExecutionProvider, and give Keystone access to /dev/kfd and /dev/dri/renderD*. On an integrated GPU, also set ffmpeg_hwaccel: vaapi to decode AI Port streams on the GPU.

acceleration:
  provider: migraphx
  migraphx_precision: FP32        # FP32 | FP16

Tested with ONNX Runtime 1.27 on a Radeon 780M (gfx1103, integrated in a Ryzen 9 PRO 8945HS), per inference:

Model CPU (2 threads) MIGraphX FP32 MIGraphX FP16
AI Port detector (YOLOX-M) 275 ms 35 ms 14 ms
CLIP ViT-L/14 image encoder 851 ms 117 ms 33 ms
Face detector (SCRFD 2.5G) 38 ms 5 ms 2 ms
Face recognizer (w600k_r50) 58 ms 12 ms 4 ms

FP32 matches the CPU output. FP16 is 2–3.5× faster again, and its outputs had a cosine similarity of at least 0.99997 to the CPU's.

MIGraphX compiles each model for the GPU when it first loads it, which can take a few minutes per model. Compiled programs are kept in <state_dir>/migraphx_cache (acceleration.migraphx_cache_dir), so later starts take seconds. Overlapping runs on one MIGraphX session return wrong results, so Keystone runs one inference at a time per model. Keystone retries on CPU if MIGraphX initialization or inference fails, including non-finite outputs, and acceleration.cpu_models keeps individual models on the CPU. The related environment variables are KEYSTONE_ACCEL_PROVIDER, KEYSTONE_ACCEL_MIGRAPHX_PRECISION and KEYSTONE_ACCEL_MIGRAPHX_CACHE_DIR.

Hardware acceleration (Apple Silicon)

Run Keystone and FFmpeg natively on macOS. The macOS arm64 onnxruntime wheel includes the CoreML execution provider. With a VideoToolbox-enabled FFmpeg build, enable Media Engine decode for the AI Port analyzer:

acceleration:
  provider: auto
  coreml_compute_units: CPUAndNeuralEngine
  coreml_model_format: MLProgram
  ffmpeg_hwaccel: auto

With these settings, auto selects CoreML for SCRFD at 640 px and ArcFace w600k_r50. In local Apple Silicon tests with an already compiled cache, SCRFD 2.5G went from about 36 ms to 11 ms per image and ArcFace R50 from 28 ms to 16 ms, with about 180 MiB more resident memory for ArcFace. CoreML can schedule those models on CPU and the Neural Engine, leaving the GPU available for captions. Set coreml_compute_units: ALL to also allow CoreML on the tested AI Port YOLOX variants, plate detectors and GFPGAN v1.4. These models benefited most when CoreML could use the GPU, so evaluate ALL alongside your VLM workload. CLIP text, plate OCR, Whisper, D-FINE and audio models use CPU on macOS.

provider: coreml explicitly requests CoreML for eligible models, and provider: cpu opts out of ONNX acceleration. Keystone retries a CoreML initialization or inference failure on CPU, including non-finite inference results. The MLProgram format is the benchmarked default. CoreML keeps compiled .mlmodelc artifacts in <state_dir>/coreml_cache across restarts. The related environment variables are KEYSTONE_ACCEL_PROVIDER, KEYSTONE_ACCEL_COREML_COMPUTE_UNITS, KEYSTONE_ACCEL_COREML_MODEL_FORMAT and KEYSTONE_ACCEL_COREML_CACHE_DIR.

To run an individual model on CPU, add its label from the inference section of /api/status to acceleration.cpu_models, for example ["face:w600k_r50"]. The environment equivalent is the comma-separated KEYSTONE_ACCEL_CPU_MODELS.

On macOS, keystone macos setup starts with ffmpeg_hwaccel: none (software decode); set ffmpeg_hwaccel: auto to check for VideoToolbox in the configured FFmpeg. On Linux it probes the VA-API device. VideoToolbox samples frames on hardware surfaces, then downloads the selected frames in NV12 or P010 before scaling and JPEG encoding. A camera with a decoder failure falls back to software decode. The dashboard shows each camera's decode backend and the active inference provider for loaded models. Set ffmpeg_hwaccel: none to use software decode everywhere.

Use the Apple Silicon inference benchmark to compare CLIP, detection and caption latency, CPU use and memory on your Mac.

On Apple Silicon with macOS 27 or newer, the optional Core AI CLIP image encoder can speed up Find Anything indexing, including historical backfill. It uses the same CLIP ViT-L/14 embedding space and keeps the ONNX encoder available for CPU fallback.

Mac mini sizing for local captions

Unified memory is shared by macOS, the VLM and the ONNX models. Use these as starting points for a Mac running both Keystone and its vision server.

Unified memory Caption model Keystone settings
16 GB Start with qwen3.5:4b-q4_K_M on Ollama's Metal backend or a 4B 4-bit MLX model. Start with vision.num_ctx: 4096 and keep CLIP text loading lazy. Use embeddings.quantization: int8 if memory pressure warrants it, then check Find Anything on your own queries.
24–32 GB or more Start with qwen3.5:9b or its 4-bit MLX equivalent. Larger models need headroom for context, frames and concurrent jobs. Keep CLIP at fp32. Budget additional memory for face recognition, plates and Whisper when enabling them together.

For Ollama, start ollama serve, pull the desired tag, and set vision.provider: ollama, vision.base_url: http://127.0.0.1:11434, and vision.model to that tag. Both the MLX-backed qwen3.5:4b and Metal-backed qwen3.5:4b-q4_K_M returned structured captions with Keystone. vision.keep_alive: 10m keeps a model resident between events. Use a shorter interval if you need to reclaim shared memory.

For MLX-VLM, install mlx-vlm in a separate Python environment and run:

mlx_vlm.server --host 127.0.0.1 --port 8000 --model mlx-community/Qwen3.5-4B-MLX-4bit
vision:
  provider: openai-compatible
  base_url: http://127.0.0.1:8000/v1
  model: mlx-community/Qwen3.5-4B-MLX-4bit
  extra_body:
    enable_thinking: false

Keystone sends JPEG images inline and requests a JSON object. This setup returned parsed captions for both one- and two-frame requests on MLX-VLM 0.8.2.

If the endpoint requires a key, set KEYSTONE_VISION_API_KEY in the service environment, or use vision.api_key: "${MY_VISION_KEY}" to reference another variable. For Docker, pass that variable into the Keystone container through Compose environment or env_file. The vision client resolves the reference at startup and reports a missing or empty variable by name. Local endpoints that accept unauthenticated requests can leave the key blank. After an HTTP 401 or 403, the dashboard shows the backend error and /api/status reports vision.ready: false with vision.lastError. A successful backend request clears the error. Readiness reflects observed requests without a startup probe.

Reasoning models share their output budget between thinking and answering. For faster captions on OpenAI-compatible servers that support it, set vision.extra_body: {reasoning_effort: "none"}. The supported reasoning controls depend on the server and model.

To keep reasoning enabled, configure a budget for image prompts. This example gives event captions and on-demand summaries up to 6144 tokens from their first request, including immediately after a restart.

vision:
  reasoning_first: true
  reasoning_max_tokens: 6144

Choose the budget with both time limits in mind. At 57 tokens/s, generating 6144 tokens alone takes about 108 seconds. The default vision.timeout_seconds is 75 seconds per backend request, and Protect on-demand jobs have at most 120 seconds from admission, including queue and frame processing time.

By default Keystone starts with the caption budget. If reasoning exhausts it before a usable answer, Keystone retries once with vision.reasoning_max_tokens (default 2048, 0 disables). Once the backend accepts that budget, subsequent requests for the model start with it. Incomplete JSON raises an error. For OpenAI reasoning models that require max_completion_tokens or the default temperature, Keystone adapts when the endpoint requests those parameters.


Under the hood (Technical details)

Architecture & protocol compatibility

  • AI Key (UP-AI-KEY, 0xa5f0): Advertises via Ubiquiti UDP 10001 discovery, serves /api/info, /api/adopt, and /api/readopt over HTTPS (:8080), authenticates to Protect via mTLS with pinned controller SHA-256 certificates, handles UCP4 control commands (:7442), and syncs rotated passwords to PostgreSQL (unifi-protect role) for Protect 7.3+ isSearchHost vector search. Keystone intentionally stays in Basic Understanding (supportDeepMode: false, supportVlm: false, aiMode: "basic", legacy dispatch without aiSched): Protect 7.4+'s Deep Understanding mode is restricted to internal Ubiquiti accounts and replaces recognizeKeyFrames/CLIP search with a separate session-describe pipeline.
  • Vision pipeline: Samples 3 chronological frames (±1.0s around each event's keyMoment, widened to ±2.0s on clips ≥ 15s, at 960px) for motion-aware VLM captions and maps outputs plus class-filtered attributes onto Protect's 5,375-tag ramTags vocabulary. Optionally injects per-camera spatial hints (cameras: in config.yaml) and multi-view, episode-chained chronological cross-camera sightings (vision.cross_camera_context_seconds, default 90s, strong similarity 0.62, cross-view floor 0.35, up to 3 sightings) so distant, rear, indoor, or IR angles benefit from earlier clearer cameras across vehicles, people, animals, and deliveries. Interactive on-demand summaries (RequestAI → :7968/on_demand_inference) narrow long exports to a 4-second window and run a fast 1-frame 640px pass to stay inside Protect's UI timeout.
  • Find Anything (:7443): Runs local CLIP ViT-L/14 (768-dim ONNX) for object crop indexing, NL_PARSE text queries (with relative time-window parsing), IMAGE_SEARCH, and optional CLIP reverification. Protect 7.4's release notes say detection confidence verification has been removed, so expect reverification jobs only from Protect 7.3.
  • Speech-to-Text (speechToText, featureFlags supportTts & supportStt): Fetches Protect's audio-only MP4 export (skipVideo=true, retrying transient 404s), decodes 16 kHz mono audio with FFmpeg, transcribes with Whisper (log-mel + timestamp-constrained greedy decoding on onnxruntime, with no-speech and leading-silence gating), and POSTs {camera, event, stt: [{startMs, endMs, text}]} to /internal/aiprocessors/speech-to-text. Segment timestamps use Unix epoch milliseconds for synchronized event playback; queued/active jobs are reported to Protect as UI_AUTO_STT.
  • Built-in AI Port (UP AI PORT X, 0xa5f5): Uses Protect's higher-capacity 0xa5f5 profile (3.0 capacity points, vs. 1.0 on a standard UP-AI-Port) so a single Keystone instance can pair up to 10x 1080p ONVIF cameras (in Protect's UI it appears as UP AI PORT X). Relays video to Protect's ms (:7550/:7551) using zero-video-transcode extendedFlv with AVC sequence-header normalization and automatic silent-audio fallback, runs motion-gated Apache-2.0 YOLOX ONNX detection, and evaluates Protect's configured polygon zones and excludeZones, line-crossing tripwires (lines, A2B/B2A/both with per-object counts) and loitering zones (loiterZones, per-object dwell times; tracks dwelling in a loiter zone are exempt from parked-object suppression until they trigger).
  • AI Port package detection (package / packageMaincam): Keystone advertises both package (smartDetectTypes) and packageMaincam (hasPackageZoneSupportForPrimaryLens) in features.smartDetect when aiport.package_enabled: true (default). The Apache-2.0 D-FINE Small Objects365 ONNX model (class 21, Storage box) loads lazily on the first scan for a camera where Protect enabled package, runs throttled every aiport.package_scan_interval_seconds during motion or person/vehicle presence plus +3s and +8s follow-up scans after a person leaves, filters by Protect's configured package zones and excludeZones, optionally checks each 15%-padded candidate crop via zero-shot CLIP cosine margin against parcel vs. porch false-positive prompts (falling back to a stricter D-FINE score floor if CLIP is unavailable), and suppresses already-reported stationary boxes by IoU (1800s TTL, cleared after 3 consecutive absent scans) so each delivered box emits one crisp EventSmartDetect arrival event with crop snapshot.
  • AI Port Smart Audio detection (all 9 alrm* classes): For paired cameras with audio, Keystone advertises all 9 Protect AUDIO_TYPES (alrmSpeak, alrmBark, alrmBabyCry, alrmSmoke, alrmCmonx, alrmSiren, alrmBurglar, alrmCarHorn, alrmGlassBreak) in features.smartDetect (Protect derives smartDetectAudioTypes from it) and reports isAudioEventReady. When Protect enables any enableAlrm* flags via ChangeAudioEventsSettings, Keystone starts one shared audio-only FFmpeg decoder (16 kHz mono PCM) for that camera. Silero VAD (MIT, shared ONNX session, per-camera RNN state) loads lazily only if alrmSpeak is enabled; Google YAMNet (Apache-2.0, shared ONNX session, 0.975 s sliding window / 0.48 s hop) loads lazily only if any of the other 8 audio alarms is enabled. Both feed a per-camera multi-alarm tracker (AudioEventTracker) that handles overlapping alarms cleanly and emits full 9-key EventSmartAudio enter / moving / leave payloads. Nothing runs while Protect has all audio detections off. Cameras that list an audio track but send no audio back off quietly (30s, then 60s), and FLV ingest retries audio on later reconnects after a transient startup timeout (aiport.flv_audio_header_timeout, default 15s). Tune with aiport.audio_vad_* and aiport.audio_alarms_*, or disable either with audio_vad_enabled: false / audio_alarms_enabled: false.
  • Native Face Recognition (supportFaceRecognition / AI Port face): On the AI Key (G4/G5 cameras), each person event's recognize-anything upload carries a face part: one track per distinct face (same-event duplicates collapse at cosine ≥ 0.55, keeping the sharpest frame), a 512-dim ArcFace embedding, a square head-and-shoulders crop, and a link to Protect's person tracker. On the AI Port (paired ONVIF/Nest cameras), Keystone scans head-and-shoulders regions while a person is visible (at most every 1.5 s per camera, stopping once a sharp frontal face is held) and emits objectType: "face" tracks in EventSmartDetect, linked to the person. Cross-camera identity propagation carries recognized names within propagation_seconds when no conflicting local face is visible (unknown_quality_faces == 0) via direct multi-view person CLIP matching (≥ 0.85 fail-safe default) or companion-object/episode continuity with VLM visual corroboration. Webhook/MQTT payloads include identities and people.
  • License plate recognition (supportLicensePlateRecognition / AI Port licensePlate): On the AI Key, recognizeKeyFrames jobs with ramType: "videoWithRecognition" (or vehicleMeta) are scanned on up to lpr.max_frames vehicle frames decoded at up to 2560px. Keystone adds an lpr JSON part (Protect 7.4 lprInferenceSchema) plus one JPEG per plate crop to the same recognize-anything multipart POST as ram. Plate crops use tracker IDs from 920000 up, and lprAttrs carries both the plate tracker (objectType: "licensePlate") and Protect's own vehicle tracker (matchedName, string-only namesTopK, topKCandidate), so Protect's VehicleRecognizer files the car under vehicle_LPR-<PLATE>. On the AI Port, licensePlate is advertised in features.smartDetect. When Protect enables it in ChangeSmartDetectSettings, vehicle tracks are read (at most every 1.5 s per camera while moving, locked at ≥ 0.88) and the leave event carries smartDetectSnapshotName and trackerIDAttrMap[vehicle].matchedName. The YOLOv9 plate detectors from open-image-models are deliberately not used, because they derive from GPL-3.0 YOLOv9 code.
  • Retroactive processing (supportRetroactiveProcessing): When embeddings.retroactive_processing: true, Protect sends batches of recognizeKeyFrames (ramType: multipleImages) with stored detection thumbnails. getTaskQueueInfo shapes UI_TASK_NUM so Protect's batch budget (50 - UI_TASK_NUM) matches free retroactive queue slots (retroactive_max_queued, default 32) and pauses whenever live jobs are queued; UI_AUTO_RAM always reports the true backlog. Missing/corrupt thumbnails (404/410) are skipped individually, valid thumbnails run in one batched CLIP forward pass, and the callback always completes so Protect never loops on pruned events.

Security defaults

  • Dashboard: Binds to 127.0.0.1:8088 by default so captions and metadata are not exposed unauthenticated on the LAN. Set web.bind_host: 0.0.0.0 (or KEYSTONE_WEB_BIND_HOST) only on a trusted management network or behind an authenticating reverse proxy. The page is fully self-contained (no CDN or remote fonts) and is served with a hash-pinned Content-Security-Policy that only allows its own scripts and same-origin API calls.
  • TLS pinning: Controller control/media (:7442/:7444), search (:7443), and encrypted FLV relays enforce exact leaf SHA-256 pins (TOFU by default, or pre-verified via keystone trust --pin --control-fingerprint ...).
  • Enrollment credentials: Setting a custom device.password or aiport.password disables factory ubnt/ui fallbacks. Protect rotates credentials on adoption, after which Keystone rejects factory credentials. Password verification runs off the event loop with per-IP backoff.
  • Adoption sources: Keystone accepts adoption requests from controller.host by default. Opt in to additional source IPs or CIDRs with controller.trusted_peers (YAML list or comma-separated string) or KEYSTONE_CONTROLLER_TRUSTED_PEERS. Wildcard /0 networks are rejected. Adoption still requires the configured controller in the payload. For PostgreSQL outside Docker, place any additional source rules before the relevant rejection rules in pg_hba.conf.

Required network ports (for segmented VLANs)

Direction Port Purpose
Keystone → Protect TCP 443 Optional Protect API lookup for paired camera names
Keystone → Protect TCP 7442 UCP4 control WebSocket (ds) & AI Port avclient WSS
Keystone → Protect TCP 7443 Find Anything NL Search WebSocket
Keystone → Protect TCP 7444 Media export downloads & RAM callbacks
Keystone → Protect TCP 7550 / 7551 AI Port extendedFlv video ingest (ms, when AI Port enabled)
Keystone → Protect TCP 7447 RTSP restream of UniFi cameras paired with the AI Port
Protect → Keystone TCP 8080 AI Key adoption management HTTPS (/api/info, /api/adopt, /api/readopt)
Protect → Keystone TCP 443 AI Port adoption management HTTPS (/api/1.2/login, /api/1.2/manage, when AI Port enabled)
Protect → Keystone TCP 5432 PostgreSQL + pgvector over TLS for Protect 7.3+ Find Anything (isSearchHost)
Protect ↔ Keystone UDP 10001 Ubiquiti v1 LAN discovery (required for initial AI Key adoption; Protect probes from an ephemeral UDP port)
Keystone → Protect UDP <Protect ephemeral port> Optional unicast cross-VLAN discovery (keystone announce / device.discovery_controller_port, initial adoption only)

Adopting across VLANs

UniFi Protect only populates an unadopted AI Key's IP address from UDP 10001 discovery (connections on :7442 before adoption are rejected before Protect stores the IP). On a separate VLAN, nothing will appear in the Protect UI until discovery reaches Protect using one of the two options below. Discovery is only needed once for initial adoption — afterward, Keystone reconnects across VLANs over TCP (:7442/:7443/:7444) permanently.

  1. UDP 10001 broadcast/multicast relay (automatic): Relay UDP 10001 (233.89.188.1 / broadcast) between Protect's VLAN and Keystone's VLAN (for example with udp-broadcast-relay-redux). Keystone replies unicast to Protect's ephemeral source port.
  2. Unicast announce (no relay needed): Find unifi-protect's current ephemeral UDP discovery port on your Protect console (ss -ulpn | grep unifi-protect), allow UDP from Keystone → Protect on that port, and send a discovery packet while Keystone is running:
keystone announce -c config.yaml --port <PROTECT_UDP_PORT>
# or in Docker:
docker exec keystone keystone announce --port <PROTECT_UDP_PORT>

You can also set device.discovery_controller_port (KEYSTONE_DEVICE_DISCOVERY_CONTROLLER_PORT) temporarily while adopting; Keystone stops sending unicast discovery packets automatically once all enabled targets are adopted. When aiport.enabled: true, the same announce covers both the AI Key and the AI Port — verify both in Protect's UniFi Devices list or Keystone's dashboard//api/status.

Kubernetes & dedicated-IP deployments

Networking requirements for Kubernetes, macvlan, and LoadBalancer setups
  1. Use one IP for adoption and search. Protect expects TCP 8080 (AI Key), 5432 (PostgreSQL), and 443 (when AI Port is enabled) on the same IP. Give ghcr.io/seearms/keystone-aio a dedicated LAN IP with Docker macvlan or a Multus network attachment. On Kubernetes, you can also expose one Pod through a LoadBalancer Service, using the all-in-one image or separate Keystone and PostgreSQL containers in that Pod. With MetalLB or Cilium BGP, set externalTrafficPolicy: Local so PostgreSQL sees Protect's real source IP.
  2. Advertise the IP Protect can reach. Without hostNetwork: true, set device.advertise_ip (KEYSTONE_DEVICE_ADVERTISE_IP) to the external IP, such as the LoadBalancer IP or the dedicated LAN IP. This keeps Keystone from advertising an internal pod IP.
  3. Give discovery a path to the LAN. UDP 10001 broadcast discovery needs Layer 2 reachability to Protect. Use hostNetwork, Multus, or Docker macvlan on Protect's LAN for automatic discovery. If you only have routed access, use one of the cross-VLAN adoption options above and allow the required connections in the table above.

If your LoadBalancer or container network rewrites the source IP and preserving it is unavailable, follow the Docker Compose NAT guidance for KEYSTONE_CONTROLLER_TRUSTED_PEERS and KEYSTONE_DEVICE_ADVERTISE_IP.

Development

ruff check src tests
pytest -v
Status dashboard architecture, history storage, and frontend build

The status dashboard (:8088) is a React + shadcn/ui app in web/ (Vite, Tailwind CSS v4, TypeScript). It compiles to a single self-contained HTML file, src/keystone/ui/index.html, which is committed so pip install and Docker builds don't need Node. Keystone embeds a status snapshot in the page and polls for updates while the dashboard is live.

Keystone keeps 30 days of activity in <state_dir>/activity.sqlite3. Only the 20 most recent entries can retain thumbnail images. Keep the state directory across upgrades and restarts (Docker Compose already mounts it). History starts with the first run of a version that supports it. Events discarded by an older version are unavailable.

Use the Activity time selector to browse the last hour, 24 hours, 7 days, or 30 days. Timestamps use your browser's local time and show when Keystone recorded each item. Search and category filters cover the selected period, including older pages. The Cameras table uses the same period for its Events column, which counts AI Port smart detection and audio messages. One detection can produce several messages as it starts, updates, and ends. Frames are counted since startup.

If the database becomes unavailable, the dashboard shows recent activity and camera counts from the current session. Keystone retries buffered writes when storage recovers and marks known gaps in the archive. Restarting while the database is still unwritable loses entries held only in memory.

cd web
npm ci
KEYSTONE_URL=http://<keystone-host>:8088 npm run dev   # hot reload, proxies /api to a running Keystone
npm test                                               # derivation/formatting tests (vitest)
npm run build                                          # rewrites src/keystone/ui/index.html; commit it

CI fails if the committed bundle doesn't match a fresh build. To refresh the README screenshots (docs/images/dashboard.png dark, dashboard-light.png light; full page at 1280px, resized to 1600px wide), render the sanitized demo snapshot and open it in a browser:

python scripts/render_demo_dashboard.py -o /tmp/keystone-demo.html --json web/src/test/fixtures/demo.json

License & Acknowledgments

Licensed under the Apache License 2.0 (see LICENSE and NOTICE).

  • Portions of Keystone's Protect UCP4 AI Key control, adoption/management, TLS pinning, worker/CLIP reverification, and AI Port adoption code are adapted from Olli0103/unifi-protect-local-ai (Apache-2.0) and modified for Keystone; see NOTICE.
  • Find Anything embeddings use MIT-licensed OpenAI CLIP ViT-L/14 ONNX weights via Xenova/clip-vit-large-patch14 (pinned to an immutable commit and SHA-256 verified on download).
  • AI Port Smart Audio uses the MIT-licensed Silero VAD v6.3 ONNX model (alrmSpeak, pinned to commit 63d4a2a) and Apache-2.0 Google YAMNet ONNX via audiomagic/yamnet-onnx (all other 8 Protect audio alarms, pinned to commit f25b741, AudioSet ontology CC-BY-4.0); both are SHA-256 verified on download and load.
  • Optional speech-to-text uses MIT-licensed OpenAI Whisper ONNX exports from onnx-community (pinned to immutable commits and SHA-256 verified on download).
  • Optional face recognition uses InsightFace SCRFD and ArcFace (WebFace600K) ONNX weights, downloaded at runtime and SHA-256 verified; the weights are licensed by InsightFace for non-commercial research purposes only.
  • Optional Face Image Enhancement uses Apache-2.0 GFPGAN v1.4 ONNX weights via neurobytemind/GFPGANv1.4.onnx (pinned to an immutable commit and SHA-256 verified on download).
  • Optional license plate recognition uses an Apache-2.0 YOLOX plate detector, either faisalthaheem/open-lpr-models plate_yolox_tiny_640.onnx (default) or autolane/yolox-s-alpr yolox_plates_s.onnx, plus MIT-licensed fast-plate-ocr cct_*_v2_global OCR. Weights are pinned and SHA-256 verified on download and load; see NOTICE.
  • Optional ONVIF object detection uses Apache-2.0 YOLOX ONNX weights (SHA-256 verified on download).
  • AI Port package detection uses Apache-2.0 D-FINE Small Objects365 ONNX weights via onnx-community/dfine_s_obj365-ONNX (pinned to an immutable commit and SHA-256 verified on download and load; see NOTICE).

Built by Colin Armstrong

About

A free, open-source virtual AI Key and AI Port for UniFi Protect: plain-English search, event descriptions and third-party camera detections with local models.

Topics

Resources

Stars

267 stars

Watchers

2 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages