Record a sky camera around the clock, keep the footage on your own disk, and find what flew past.
TypeScript astronomycloudflare-workerscomputer-visionmcpmeteor-detectionobject-trackingrtspself-hostedsky-camerayolo
Run it with an agent
Hunter Deiblerb1a9474df713
diff --git a/README.md b/README.mdindex 29255e1..8af6dd5 100644--- a/README.md+++ b/README.md@@ -12,6 +12,7 @@<p align="center"><a href="https://docs.openskycam.org/">Documentation</a> ·<a href="https://docs.openskycam.org/deploy/">Deploy your own</a> ·+ <a href="https://docs.openskycam.org/agents/">Run it with an agent</a> ·<a href="https://docs.openskycam.org/api/">API</a></p>@@ -30,7 +31,7 @@ openskycam records an IP camera pointed at the sky, 24 hours a day. A relay copi- **Find things in it.** Build a workflow that samples frames from a time window, runs detection models, and routes each frame to a bucket by class, score, count, time or motion. Run it once, or every night as footage arrives.- **Tell planes from stars.** Boxes from the same object are linked across a recording into a track that is moving, stationary or brief. A workflow can keep moving aircraft and set fixed lights aside.- **Build training data.** Review detections, correct boxes, and freeze a dataset version with its images, labels, tracks and splits.-- **Script everything.** Everything the website does is also a `/v1` API call. An MCP server gives AI agents the same tools.+- **Hand it to your agent.** An AI agent can set it up, run it and change its code: every website action is a `/v1` API call, an MCP server gives agents seven tools that cover the website, and the setup runs unattended from `.env`.## A look inside@@ -90,6 +91,33 @@ npm installmake check # every test suite, the docs build and shell lint; needs no Cloudflare account```+## Run it with your agent++openskycam is built for an AI agent to operate:++- **It covers the whole website.** Connected to the MCP server at `/v1/mcp`, an agent can browse and download footage, take a photo from stored video at any second, build and test workflows, schedule them, follow runs live, review detections, freeze datasets, check the processor and assign models to devices.+- **The server teaches it.** On connect, the agent gets instructions plus six guides and five step-by-step skills (`build-a-workflow`, `find-detections`, `take-photos`, `download-footage`, `verify-changes`).+- **It runs the setup.** `npm run setup -- --yes` asks nothing: it reads every answer from `.env`, stops naming the key it needs, and skips finished steps when run again. `npm run setup -- --check` checks all nine steps of a running deployment and exits with 1 when one fails.+- **It can change the code safely.** [`AGENTS.md`](AGENTS.md) gives the conventions, and `make check` runs every test and the architecture checks without a Cloudflare account.+- **The server enforces the guardrails.**+ - No key can create keys.+ - Deletes show a preview and need a confirmation.+ - Edits fail rather than overwrite a newer revision.+ - Every tool call is logged.++You ask in plain words: *"Did the camera record all night?"*, *"Find last night's meteors and show me the clearest three"*, *"Build a workflow that keeps moving planes between 02:00 and 09:30 UTC and run it every night"*, *"Review the waiting images in Planes"*. Three steps need a person:+- the first Cloudflare login;+- creating the tunnel and the sign-in application in the Cloudflare dashboard;+- creating API keys on the website.++[Run it with an agent](https://docs.openskycam.org/agents/) maps each request to the tool that answers it.++Create an **Agent** key under **API access** on your website, then connect, for example with Claude Code:++```sh+claude mcp add --transport http openskycam https://<api-host>/v1/mcp --header "Authorization: Bearer $OPENSKYCAM_KEY"+```+## Use the APICreate a key on the website under **API access**. An Agent key that covers every camera can call everything the website does:@@ -99,11 +127,7 @@ curl -H "Authorization: Bearer $OPENSKYCAM_KEY" https://<api-host>/v1/workshopcurl -H "Authorization: Bearer $OPENSKYCAM_KEY" "https://<api-host>/v1/recordings?camera=sky01&from=2026-10-25T02:00:00Z&to=2026-10-25T03:00:00Z"```-`/openapi.json` describes the API for client generation. AI agents connect to the [MCP server](https://docs.openskycam.org/api/mcp/) at `/v1/mcp`:--```sh-claude mcp add --transport http openskycam https://<api-host>/v1/mcp --header "Authorization: Bearer $OPENSKYCAM_KEY"-```+`/openapi.json` describes the API for client generation.## Modelsdiff --git a/docs/README.md b/docs/README.mdindex 386c4b3..f56829d 100644--- a/docs/README.md+++ b/docs/README.md@@ -25,7 +25,7 @@ website + API Worker ◀── Cloudflare Access (people), API keys (scripts, ag- **Find things in it.** A Workshop workflow samples frames from a time window, runs one to four detection or classification models, and routes each frame to a bucket by class, score, count, time of day, or motion. Workflows can run on a schedule, for example every night.- **Tell planes from stars.** Boxes from the same object are linked across a recording into a track. Each track is moving, stationary, or brief, so a workflow can keep moving planes and set fixed lights aside.- **Build training data.** Review detections, accept or reject them, correct their boxes, and freeze a dataset version. A version records its images, labels, tracks, classes, and splits, and a script can download it.-- **Script all of it.** Everything the website does is also an API call under `/v1`. AI agents can connect to the MCP server, which offers the same actions.+- **Hand it to an agent.** Everything the website does is also an API call under `/v1`, and an MCP server gives AI agents the same actions with guides on how to use them. An agent can run the setup, operate it day to day and change its code ([Run it with an agent](agents.md)).## What it is made of@@ -48,6 +48,8 @@ The store and the processor can be the same machine. Nothing in Cloudflare holdsCameras, hosts, disk sizing, and the Cloudflare account.- [Deploy your own](deploy.md)\Every step from a clone to video arriving.+- [Run it with an agent](agents.md)\+ What an AI agent can do over MCP, and how it runs the setup for you.- [Configuration](configuration.md)\Every setting and its default.- [Workflows](workshop/workflows.md)\diff --git a/docs/agents.md b/docs/agents.mdnew file mode 100644index 0000000..df5d168--- /dev/null+++ b/docs/agents.md@@ -0,0 +1,99 @@+---+title: Run it with an agent+sidebar: Run it with an agent+description: An AI agent can set openskycam up, run it day to day and change its code. Here is what it can do, how to connect it, and the few steps that still need you.+---++openskycam is built so an AI agent can do the work. Every action on the website is also an API call under `/v1`. An [MCP server](api/mcp.md) gives agents seven tools that cover the website, with guides that teach them how to use them. The setup runs unattended from `.env`, and `make check` verifies any change an agent makes to the code.++A person is needed for three things, all by design: creating API keys on the website, creating the tunnel and the sign-in application in the Cloudflare dashboard, and the first Cloudflare login in a browser. [What needs you](#what-needs-you) lists them.++## What you can ask++Connected over MCP, an agent answers questions like these with the tools on the right. Each answer comes from the live deployment, and the agent can look at the images it finds.++| You ask | The agent uses |+|---|---|+| Did the camera record all night? | `footage cameras` (upload health and storage), `footage days`, `footage list` |+| Take a photo of the sky at 03:12:40 UTC. | `footage photo`: the processor decodes that frame from stored video |+| Download every recording from 02:00 to 03:00 UTC. | `footage download`: signed links that last an hour |+| Find last night's meteors and show me the clearest three. | `images search` by bucket, class, confidence and time, then `images view` |+| Build a workflow that keeps moving planes between 02:00 and 09:30 UTC, and run it every night. | `workflows create` and `update`, `workflows check`, `runs test`, `runs watch`, then a schedule step and `runs start` |+| Is the night workflow keeping up? | `runs list`, `runs status`, `runs schedules` |+| Review the waiting images in Planes: accept real planes, reject stars. | `images search` for pending items, `images view`, then `images review` in batches of up to 100 |+| Keep the best meteor images past their expiry. | `images save` |+| Freeze a dataset of the reviewed meteors and give me the manifest. | `buckets create_version`, `buckets export_version` |+| Is the processor online, and which version is it running? | `runs runtimes` |+| Put the night detector on the gpu-box device. | `models list`, `models devices`, `models deploy` |++An Agent key that covers every camera can also call any website route through `/v1`, so an agent writing a script has the same reach as the website, except managing keys ([API overview](api.md#the-website-under-v1)).++## Connect your agent++On the website, open **API access** and create a key with Purpose **Agent: MCP and full API**. The dialog shows the command for Claude Code with the key filled in:++```sh+claude mcp add --transport http openskycam https://<api-host>/v1/mcp \+ --header "Authorization: Bearer svk_…" --scope user+```++Any MCP client that speaks Streamable HTTP connects to the same URL with the same header. [MCP server](api/mcp.md) lists every tool and action.++## What the agent learns from the server++The agent does not need to read this documentation. On connect, the server sends instructions that point it to the `guide` tool, which serves:++- **Six guides**: `overview`, `footage`, `workflows`, `runs`, `images` and `models`.+- **Five step-by-step skills**: `build-a-workflow`, `find-detections`, `take-photos`, `download-footage` and `verify-changes`. In Claude Code they are also commands, such as `/mcp__openskycam__build-a-workflow`.+- **The rules.** Times are UTC. Test a workflow before a full run, and follow the run until it finishes. After any change, read it back and report what it observed, not what it attempted.++The guides are Markdown files in [`package/dashboard/ui/public/agent/`](https://github.com/Deibler/openskycam/tree/main/package/dashboard/ui/public/agent). Edit them to change what every connected agent is told.++## Guardrails++These are enforced by the server, not left to the agent:++- **No key can make keys.** Keys are created, rotated and revoked only on the website, by someone signed in through Cloudflare Access.+- **Deletes show what would be lost first.** Nothing is deleted until the agent calls again with `confirm: true` and the revision the preview gave it.+- **Edits cannot overwrite each other.** A Workshop edit carries the revision the agent read and fails on a newer one.+- **Cameras.** An Agent key reaches only the footage and images of its cameras.+- **Links expire.** Download links last an hour and stop working when the key is revoked.+- **Every call is logged.** Each tool call writes an `agent_tool` event with the key, tool and action to Workers Logs.++## Set it up with a coding agent++A coding agent with a terminal, such as Claude Code, can run the whole setup. It writes the answers to `.env`, then runs:++```sh+npm install+npm run setup -- --yes+```++With `--yes` the setup asks nothing. It takes every answer from `.env`, uses suggested values where there is one, and stops at the first missing or wrong answer, naming the key to set, with exit code 1. The agent fixes that key and runs it again; finished steps are skipped. Two secrets are read from the environment instead, so they are never written to `.env`:++| Variable | What it is |+|---|---|+| `STORE_TUNNEL_TOKEN` | The footage store's tunnel token, written only to the store host |+| `OPENSKYCAM_WORKSHOP_KEY` | The processor's Run Workshop jobs key, written only to the processor host |++[Configuration](configuration.md#guided-setup) lists every `.env` key the setup reads. With `--yes`, a processor is installed only when `PROCESSOR_HOST` is set.++`npm run setup -- --check` checks all nine steps of a running deployment and changes nothing. It exits with 1 when a required step fails and says why, so an agent can use it to confirm a deployment works, or to find what broke.++### What needs you++| Step | Why an agent cannot do it |+|---|---|+| Sign in to Cloudflare once (`wrangler login`) | It opens a browser login |+| Create the tunnel and the Access application in the Cloudflare dashboard, and the Browser Integrity Check rule for the API host | Wrangler's login cannot create them. The setup explains each click; the agent passes on the tunnel token, team domain and audience tag |+| Create API keys on the website: Agent, and Run Workshop jobs for a processor | Only a person signed in through Access can create keys |+| Allow SSH key login to each host, and `sudo` on Linux hosts | The setup uses `sudo -n` with `--yes`, so it fails at once instead of waiting for a password |++## Change the code with an agent++The repository is laid out for coding agents:++- [`AGENTS.md`](https://github.com/Deibler/openskycam/blob/main/AGENTS.md) gives the conventions: where code goes, the layer rules and file names, and what to verify.+- `make check` runs every test suite, the architecture checks, the docs build with its link check, and shell lint. It needs no Cloudflare account, so an agent can run it anywhere.+- The architecture checks enforce the layer rules mechanically: SQL outside `db/`, HTTP objects in services, and a misplaced type all fail ([Architecture](develop/architecture.md#what-the-checks-enforce)).+- Every deploy step is a command: `npm run release` and `npm run deploy` for the Workers, `external/store/deploy.sh`, `make deploy HOST=<relay-host>` for the relay, and `install-workshop.sh` for a processor. A change to processor code needs a new runtime, which an agent registers with `runs register_runtime` ([Processor](processor.md#runtimes)).diff --git a/docs/api/mcp.md b/docs/api/mcp.mdindex 33768b1..fafb3bd 100644--- a/docs/api/mcp.md+++ b/docs/api/mcp.md@@ -3,7 +3,7 @@ title: MCP serverdescription: Connect an AI agent to openskycam through its remote Model Context Protocol server.----`https://<api-host>/v1/mcp` is a remote [Model Context Protocol](https://modelcontextprotocol.io) server. An agent connected to it can browse footage, take photos from stored video, build and run workflows, review detections, freeze datasets and deploy models: everything the website does except managing API keys. It needs an **Agent** key.+`https://<api-host>/v1/mcp` is a remote [Model Context Protocol](https://modelcontextprotocol.io) server. An agent connected to it can browse footage, take photos from stored video, build and run workflows, review detections, freeze datasets and deploy models: everything the website does except managing API keys. It needs an **Agent** key. [Run it with an agent](../agents.md) shows what to ask and which tools answer.## Connectdiff --git a/docs/configuration.md b/docs/configuration.mdindex 5ffd0e7..ad106db 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -66,6 +66,8 @@ Variables already set in the environment win over `.env`. In Workers Builds, set| `PROCESSOR_DEVICE` | The processor's registered device name || `OPENSKYCAM_AGENT_KEY` | An Agent key for every camera. The setup registers the processor with it; your scripts can use it too |+With `npm run setup -- --yes`, two secrets come from the environment instead of `.env`: `STORE_TUNNEL_TOKEN`, written only to the store host, and `OPENSKYCAM_WORKSHOP_KEY`, written only to the processor host.+## How `npm run config` fills `wrangler.jsonc`The `wrangler.jsonc` files leave every deployment value out. [`package/shared/deploy-config.mjs`](https://github.com/Deibler/openskycam/blob/main/package/shared/deploy-config.mjs) fills them in. Every Wrangler script in `package/dashboard/` and `package/worker/` runs it first, and it writes the result to `wrangler.deploy.json`:diff --git a/docs/deploy.md b/docs/deploy.mdindex 92a28a0..f3a3937 100644--- a/docs/deploy.md+++ b/docs/deploy.md@@ -27,6 +27,7 @@ The setup does each step a command can do: it signs in to Cloudflare, creates th| `npm run setup` | Sets up everything that is not working yet. Steps that pass their check are skipped. || `npm run setup -- relay` | Runs one step again, for example after changing the camera: `cloudflare`, `hosts`, `storage`, `store`, `access`, `website`, `ingest`, `relay` or `processor`. || `npm run setup -- --check` | Checks every step of a running deployment and changes nothing. It exits with 1 if a required step fails. |+| `npm run setup -- --yes` | Asks nothing: takes every answer from `.env` and stops, naming the key, at the first missing one. For coding agents and scripts ([Run it with an agent](agents.md#set-it-up-with-a-coding-agent)). |The setup needs key-based SSH login to each host (`ssh-copy-id <host>`). On Linux hosts it offers to run `loginctl enable-linger` and to install missing packages with `sudo`, which ask for your password there.diff --git a/package/docs/src/nav.ts b/package/docs/src/nav.tsindex c9e226d..8f3ea98 100644--- a/package/docs/src/nav.ts+++ b/package/docs/src/nav.ts@@ -15,6 +15,7 @@ export const tabs: { label: string; icon: string; sections: { title: string; ico'how-it-works': 'Route',requirements: 'ListChecks',deploy: 'CloudUpload',+ agents: 'Sparkles',configuration: 'SlidersHorizontal',},},diff --git a/setup/setup.mjs b/setup/setup.mjsindex 566f6e9..4f4e8ac 100644--- a/setup/setup.mjs+++ b/setup/setup.mjs@@ -7,6 +7,9 @@* npm run setup -- relay run one step again (cloudflare, hosts, storage, store, access, website,* ingest, relay, processor)* npm run setup -- --check check every step and change nothing+ * npm run setup -- --yes ask nothing: take every answer from .env (secrets that never go in .env+ * from the environment) and stop, naming the key, when one is missing.+ * For agents and scripts.*/import { spawn, spawnSync } from 'node:child_process';import crypto from 'node:crypto';@@ -21,6 +24,7 @@ const envFile = path.join(root, '.env');const wranglerBin = path.join(root, 'package/dashboard/node_modules/.bin/wrangler');const args = process.argv.slice(2);const checkOnly = args.includes('--check');+const assumeYes = args.includes('--yes');const only = args.find(a => !a.startsWith('--'));let env = fs.existsSync(envFile) ? lib.parseEnv(fs.readFileSync(envFile, 'utf8')) : {};@@ -60,8 +64,17 @@ process.on('SIGINT', () => {process.exit(130);});-/** Asks until the answer passes `problem`. Enter keeps the current value. Secrets are not echoed. */-async function ask(label, { initial = '', secret = false, problem } = {}) {+/**+ * Asks until the answer passes `problem`. Enter keeps the current value. Secrets are not echoed. With --yes,+ * the current value is the answer, and `key` names where to put one when there is none.+ */+async function ask(label, { initial = '', secret = false, problem, key } = {}) {+ if (assumeYes) {+ const issue = initial ? problem?.(initial) : `none is set; put it in ${key}`;+ if (issue) throw new Error(`${label}: ${issue}.`);+ say(`${label}: ${secret ? dim('(from ' + key + ')') : initial}`);+ return initial;+ }for (;;) {const current = initial ? dim(secret ? ' [Enter keeps the saved one]' : ` [${initial}]`) : '';process.stdout.write(` ${label}${current}: `);@@ -75,11 +88,16 @@ async function ask(label, { initial = '', secret = false, problem } = {}) {}}async function confirm(label, yes = true) {+ if (assumeYes) {+ say(`${label} ${dim(yes ? 'yes' : 'no')}`);+ return yes;+ }process.stdout.write(` ${label} ${dim(yes ? '[Y/n]' : '[y/N]')} `);const answer = (await nextLine()).trim().toLowerCase();return answer ? answer.startsWith('y') : yes;}async function pause(text = 'Press Enter when that is done.') {+ if (assumeYes) throw new Error(`This step needs a person: ${text}`);process.stdout.write(` ${dim(text)} `);await nextLine();}@@ -165,16 +183,21 @@ function save(values) {fs.writeFileSync(envFile, lib.setEnv(text, values), { mode: 0o600 });}+/** Shows a problem and lets the person try again; with --yes there is nobody to ask, so it stops. */+function tryAgain(message) {+ if (assumeYes) throw new Error(message);+ say(red(message));+}+/** Asks for an SSH host until key-based login works. */async function sshHost(label, key) {for (;;) {- const host = await ask(label, { initial: env[key], problem: lib.problems.ssh });+ const host = await ask(label, { initial: env[key], problem: lib.problems.ssh, key });if (ssh(host, 'true').ok) {save({ [key]: host });return host;}- say(red(`Cannot log in to ${host} with an SSH key.`));- say(`Set up key login first, for example: ${bold(`ssh-copy-id ${host}`)}, then try again.`);+ tryAgain(`Cannot log in to ${host} with an SSH key. Set up key login first, for example: ssh-copy-id ${host}`);}}@@ -184,7 +207,7 @@ async function linger(host) {if (ssh(host, 'loginctl show-user "$USER" --property=Linger').out.includes('Linger=yes')) return;say(`${host} must keep its services running when nobody is logged in (loginctl enable-linger).`);if (await confirm('Turn that on now? It may ask for your password on that host.'))- sshTerminal(host, 'sudo loginctl enable-linger "$USER"');+ sshTerminal(host, `sudo ${assumeYes ? '-n ' : ''}loginctl enable-linger "$USER"`);}const storeToken = () => {@@ -220,7 +243,7 @@ const steps = [if (!who?.loggedIn) throw new Error('Wrangler is still not signed in.');if (who.accounts?.length > 1) {who.accounts.forEach((a, i) => say(`${i + 1}. ${a.name} (${a.id})`));- const pick = await ask('Which account', { problem: v => (who.accounts[+v - 1] ? undefined : 'Enter a number.') });+ const pick = await ask('Which account', { key: 'CLOUDFLARE_ACCOUNT_ID', problem: v => (who.accounts[+v - 1] ? undefined : 'Enter a number.') });save({ CLOUDFLARE_ACCOUNT_ID: who.accounts[+pick - 1].id });}},@@ -236,9 +259,9 @@ const steps = [},async run() {say('The website and API are two hostnames on a domain in your Cloudflare account.');- const site = await ask('Website hostname, for example sky.example.com', { initial: env.SITE_HOST, problem: lib.problems.host });- const apiHost = await ask('API hostname', { initial: env.API_HOST || `api.${site}`, problem: lib.problems.host });- const cam = await ask('A short ID for the camera', { initial: env.CAM_ID || 'sky01', problem: lib.problems.camera });+ const site = await ask('Website hostname, for example sky.example.com', { initial: env.SITE_HOST, problem: lib.problems.host, key: 'SITE_HOST' });+ const apiHost = await ask('API hostname', { initial: env.API_HOST || `api.${site}`, problem: lib.problems.host, key: 'API_HOST' });+ const cam = await ask('A short ID for the camera', { initial: env.CAM_ID || 'sky01', problem: lib.problems.camera, key: 'CAM_ID' });const cameras = [...new Set([...(env.CAMERAS ?? '').split(',').filter(Boolean), cam])].join(',');save({ SITE_HOST: site, API_HOST: apiHost, CAM_ID: cam, CAMERAS: cameras });},@@ -295,18 +318,18 @@ const steps = [sshTerminal(host, `PATH=/opt/homebrew/bin:/usr/local/bin:$PATH brew install ${missing.join(' ')}`);} else {say('Install cloudflared: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/');- await pause('Press Enter once they are installed.');+ await pause(`Install ${missing.join(', ')} on ${host}, then press Enter.`);}}- const folder = await ask('Folder for the footage, for example /mnt/footage', { initial: env.STORE_ROOT, problem: lib.problems.folder });+ const folder = await ask('Folder for the footage, for example /mnt/footage', { initial: env.STORE_ROOT, problem: lib.problems.folder, key: 'STORE_ROOT' });ssh(host, `mkdir -p '${folder}'`);let systemDisk = env.STORE_SYSTEM_DISK === 'yes';if (ssh(host, `python3 -c 'import os,sys; sys.exit(0 if os.path.ismount(sys.argv[1]) else 1)' '${folder}'`).ok) systemDisk = false;else {say(`${folder} is not a separate disk. The store refuses to write to a folder whose disk is missing,`);say('so a drive that fails to mount never fills the system disk.');- systemDisk = await confirm('Keep footage in this folder on the system disk anyway?', false);- if (!systemDisk) throw new Error(`Mount the footage disk at ${folder}, then run setup again.`);+ systemDisk = env.STORE_SYSTEM_DISK === 'yes' || (await confirm('Keep footage in this folder on the system disk anyway?', false));+ if (!systemDisk) throw new Error(`Mount the footage disk at ${folder} (or set STORE_SYSTEM_DISK=yes), then run setup again.`);}save({ STORE_ROOT: folder, STORE_SYSTEM_DISK: systemDisk ? 'yes' : 'no' });@@ -318,14 +341,14 @@ const steps = [say('It needs no public hostname. On the install page, copy the command: the long token after --token is what you need.');openUrl('https://one.dash.cloudflare.com/');for (;;) {- const token = await ask('Tunnel token', { secret: true });+ const token = await ask('Tunnel token', { secret: true, initial: process.env.STORE_TUNNEL_TOKEN, key: 'the environment variable STORE_TUNNEL_TOKEN' });try {tunnelId = lib.parseTunnelToken(token).tunnelId;const wrote = ssh(host, 'mkdir -p ~/.config/skyvision-store && umask 077 && cat > ~/.config/skyvision-store/tunnel.token', token.trim());if (!wrote.ok) throw new Error(wrote.all);break;} catch (error) {- say(red(error.message));+ tryAgain(error.message);}}save({ STORE_TUNNEL_ID: tunnelId });@@ -364,21 +387,24 @@ const steps = [say('4. Save, then copy the Application Audience (AUD) tag from the application\'s Basic information.');openUrl('https://one.dash.cloudflare.com/');for (;;) {- const team = lib.teamDomain(await ask('Team domain, shown under Settings → Custom pages or in the sign-in URL', { initial: env.ACCESS_TEAM_DOMAIN, problem: lib.problems.team }));+ const team = lib.teamDomain(await ask('Team domain, shown under Settings → Custom pages or in the sign-in URL', { initial: env.ACCESS_TEAM_DOMAIN, problem: lib.problems.team, key: 'ACCESS_TEAM_DOMAIN' }));const certs = await http(`${team}/cdn-cgi/access/certs`);if (certs.status === 200 && json(certs.text)?.keys) {save({ ACCESS_TEAM_DOMAIN: team });break;}- say(red(`${team} does not answer as an Access team domain.`));+ tryAgain(`${team} does not answer as an Access team domain.`);}- save({ ACCESS_AUD: await ask('Application Audience (AUD) tag', { initial: env.ACCESS_AUD, problem: lib.problems.aud }) });+ save({ ACCESS_AUD: await ask('Application Audience (AUD) tag', { initial: env.ACCESS_AUD, problem: lib.problems.aud, key: 'ACCESS_AUD' }) });say('');say('Scripts call the API with keys, but Cloudflare\'s Browser Integrity Check blocks many of them first.');say(`Turn it off for ${env.API_HOST} only: your domain → Rules → Configuration Rules → Create rule,`);say(`when Hostname equals ${env.API_HOST}, set Browser Integrity Check to Off.`);- openUrl('https://dash.cloudflare.com/');- await pause();+ if (assumeYes) say(dim('The website step checks that this rule is in place.'));+ else {+ openUrl('https://dash.cloudflare.com/');+ await pause();+ }},},{@@ -419,7 +445,7 @@ const steps = [say(yellow('The deploy did not print a workers.dev address. Your account may need a workers.dev subdomain:'));say('Workers & Pages → Overview → workers.dev subdomain.');openUrl('https://dash.cloudflare.com/?to=/:account/workers-and-pages');- url = await ask('The ingest Worker address, https://skyvision-ingest.<subdomain>.workers.dev', { initial: env.INGEST_URL, problem: v => (/^https:\/\//.test(v) ? undefined : 'Start with https://.') });+ url = await ask('The ingest Worker address, https://skyvision-ingest.<subdomain>.workers.dev', { initial: env.INGEST_URL, key: 'INGEST_URL', problem: v => (/^https:\/\//.test(v) ? undefined : 'Start with https://.') });}save({ INGEST_URL: url });putSecret('worker', 'INGEST_TOKEN', env.INGEST_TOKEN);@@ -445,18 +471,18 @@ const steps = [const missing = ssh(host, 'for t in ffmpeg ffprobe curl; do command -v $t >/dev/null || echo $t; done').out.split('\n').filter(Boolean);if (missing.length) {say(yellow(`${host} is missing: ${missing.join(', ')}.`));- if (await confirm('Install ffmpeg and curl with apt now? It asks for your password on that host.')) sshTerminal(host, 'sudo apt-get update && sudo apt-get install -y ffmpeg curl');+ if (await confirm('Install ffmpeg and curl with apt now? It asks for your password on that host.')) sshTerminal(host, `sudo ${assumeYes ? '-n ' : ''}sh -c 'apt-get update && apt-get install -y ffmpeg curl'`);}await linger(host);for (;;) {say('');say('The camera must stream H.264 or H.265 over RTSP (see docs/requirements.md).');- const ip = await ask('Camera address', { initial: env.CAMERA_IP_ADDRESS, problem: lib.problems.address });- const user = await ask('Camera user name', { initial: env.CAMERA_USERNAME || 'admin' });- const password = await ask('Camera password', { initial: env.CAMERA_PASSWORD, secret: true });- const port = await ask('RTSP port', { initial: env.CAMERA_RTSP_PORT || '554', problem: lib.problems.port });+ const ip = await ask('Camera address', { initial: env.CAMERA_IP_ADDRESS, problem: lib.problems.address, key: 'CAMERA_IP_ADDRESS' });+ const user = await ask('Camera user name', { initial: env.CAMERA_USERNAME || 'admin', key: 'CAMERA_USERNAME' });+ const password = await ask('Camera password', { initial: env.CAMERA_PASSWORD, secret: true, key: 'CAMERA_PASSWORD' });+ const port = await ask('RTSP port', { initial: env.CAMERA_RTSP_PORT || '554', problem: lib.problems.port, key: 'CAMERA_RTSP_PORT' });say(dim('Stream paths: Dahua /cam/realmonitor?channel=1&subtype=0 · Hikvision /Streaming/Channels/101 · Tapo /stream1'));- const streamPath = await ask('RTSP path', { initial: env.CAMERA_RTSP_PATH || '/cam/realmonitor?channel=1&subtype=0', problem: lib.problems.path });+ const streamPath = await ask('RTSP path', { initial: env.CAMERA_RTSP_PATH || '/cam/realmonitor?channel=1&subtype=0', problem: lib.problems.path, key: 'CAMERA_RTSP_PATH' });save({ CAMERA_IP_ADDRESS: ip, CAMERA_USERNAME: user, CAMERA_PASSWORD: password, CAMERA_RTSP_PORT: port, CAMERA_RTSP_PATH: streamPath });say(`Checking the stream from ${host}…`);const url = `rtsp://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${ip}:${port}${streamPath}`;@@ -466,7 +492,7 @@ const steps = [say(green(`The camera streams ${codec === 'hevc' ? 'H.265' : 'H.264'} at ${width}×${height}.`));break;}- say(red(probe.ok ? `The camera streams ${codec}; the relay records H.264 or H.265 only.` : `The relay cannot read the stream: ${probe.all.trim().split('\n').pop()}`));+ tryAgain(probe.ok ? `The camera streams ${codec}; the relay records H.264 or H.265 only.` : `The relay cannot read the stream: ${probe.all.trim().split('\n').pop()}`);}say('Installing the recorder and uploader…');if (!run(path.join(root, 'external/relay/deploy.sh'), [host]).ok) throw new Error('The relay install failed; see the output above.');@@ -490,7 +516,8 @@ const steps = [async run() {say('The processor runs detection models over your footage for Workshop workflows. It needs a');say('macOS or Linux machine with Python 3.11 or later; an Apple or NVIDIA GPU makes it much faster.');- if (!(await confirm('Set up a processor now?', false))) return 'skipped';+ // With --yes, a processor is set up when PROCESSOR_HOST says where.+ if (!(assumeYes ? env.PROCESSOR_HOST : await confirm('Set up a processor now?', false))) return 'skipped';const site = `https://${env.SITE_HOST}/?view=api`;for (;;) {if (env.OPENSKYCAM_AGENT_KEY && json((await api('/v1/me', env.OPENSKYCAM_AGENT_KEY)).text)?.scope === 'agent') break;@@ -498,13 +525,14 @@ const steps = [say(`On the website, open ${bold('API access')} and create a key: Purpose ${bold('Agent')}, every camera.`);say('Setup uses it to register the processor; it is saved in .env for your own scripts too.');openUrl(site);+ if (assumeYes) throw new Error('OPENSKYCAM_AGENT_KEY is missing or refused: create an Agent key for every camera on the website and put it in .env.');save({ OPENSKYCAM_AGENT_KEY: await ask('Agent key', { secret: true }) });}const host = await sshHost('SSH host of the processor machine', 'PROCESSOR_HOST');const python = ssh(host, 'PATH=/opt/homebrew/bin:/usr/local/bin:$PATH; command -v python3 && python3 -c "import sys; sys.exit(sys.version_info < (3, 11))"');if (!python.ok) throw new Error(`${host} needs Python 3.11 or later.`);const suggested = ssh(host, 'hostname -s').out.trim().toLowerCase().replace(/[^a-z0-9._-]/g, '-');- const device = await ask('Device name for this machine', { initial: env.PROCESSOR_DEVICE || suggested, problem: lib.problems.device });+ const device = await ask('Device name for this machine', { initial: env.PROCESSOR_DEVICE || suggested, problem: lib.problems.device, key: 'PROCESSOR_DEVICE' });const created = await api('/v1/models/devices', env.OPENSKYCAM_AGENT_KEY, { method: 'POST', body: JSON.stringify({ id: device }) });if (![200, 201].includes(created.status)) throw new Error(`Registering ${device} failed: ${created.status} ${created.text}`);save({ PROCESSOR_DEVICE: device });@@ -512,13 +540,13 @@ const steps = [say('');say(`Create a second key: Purpose ${bold('Run Workshop jobs')}, device ${bold(device)}, every camera.`);openUrl(site);- const key = await ask('Run Workshop jobs key', { secret: true });+ const key = await ask('Run Workshop jobs key', { secret: true, initial: process.env.OPENSKYCAM_WORKSHOP_KEY, key: 'the environment variable OPENSKYCAM_WORKSHOP_KEY' });const me = json((await api('/v1/me', key)).text);if (me?.scope === 'workshop:run') {ssh(host, 'mkdir -p ~/.config/openskycam && umask 077 && cat > ~/.config/openskycam/workshop.key', key);break;}- say(red(me ? `That key's purpose is ${me.scope}.` : 'That key was refused.'));+ tryAgain(me ? `That key's purpose is ${me.scope}, not Run Workshop jobs.` : 'That Run Workshop jobs key was refused.');}const commit = run('git', ['rev-parse', '--short', 'HEAD'], { quiet: true }).out.trim();const folder = `openskycam-processor/${commit}`;