Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

28.8 KB
Raw Blame
import 'dotenv/config'
import { z } from 'zod'
import { parseDaemonsSwitch } from '../lib/daemonsSwitch.js'

const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),

  // The single web-facing port: control API + data-plane reverse proxy.
  PORT: z.string().default('8085').transform(Number),

  // Dedicated PUBLIC subdomain app-proxy port. Traffic to [sub].<APP_DOMAIN_SUFFIX> hits this
  // listener (Host-header routed), separate from the api-key control/`/proxy` plane on PORT.
  PORT_APP_PROXY: z.string().default('8087').transform(Number),
  // Domain suffix stripped from the Host header to get the subdomain (e.g. ".harness.autonomous.ai").
  APP_DOMAIN_SUFFIX: z.string().default('.harness.autonomous.ai'),

  // Same MongoDB (and database) as the agent-manager — backend owns `users` +
  // `machines`; reads `managers`/`machine_nodes` via raw queries when needed.
  DATABASE_URL: z.string().default('mongodb://localhost:27017/harness?replicaSet=rs0'),
  // The reads that tolerate a few seconds of lag (older history pages, costs, search, usage totals) go to the secondaries
  // through a second client on DATABASE_URL (lib/prisma.ts prismaSecondary, task #2970). 'off' sends them back to the
  // primary at the next start, with no code change.
  DATABASE_SECONDARY_READS: z.enum(['on', 'off']).default('on'),

  // Redis for the cross-instance data bus. Behind a load balancer an agent's web socket and its
  // manager socket may land on different backend instances; Redis pub/sub bridges them
  // (channels up:{machineId} / down:{machineId}) plus an agent→manager presence key. See lib/bus.ts.
  REDIS_URL: z.string().default('redis://localhost:6379'),
  // The longest one Redis command may take on the shared command connection (lib/bus.ts). Redis answers in well under a
  // millisecond; past this it is stuck, and a request should not wait on it (Stability 3.5).
  REDIS_COMMAND_TIMEOUT_MS: z.coerce.number().int().positive().default(1_000),
  // Signed-in requests per route, across every pod (middlewares/routeRateLimit.ts). Far above what a working client
  // sends, so only a loop meets them. 0 turns one off. Revisit with per-route counts from the ingress logs.
  // Per caller and second: the agent or machine the route names (with its person), else the person.
  ROUTE_RATE_LIMIT_PER_CALLER_SECOND: z.coerce.number().int().min(0).default(50),
  // Per person and minute, whatever agents or machines the calls name. The busiest working client is an older CLI's
  // delivery poll, one call a second per running agent. A late poll can land in the next minute, so a minute can see an
  // agent 61 times: 200 agents are 12200. 15000 leaves room above that.
  ROUTE_RATE_LIMIT_PER_PERSON_MINUTE: z.coerce.number().int().min(0).default(15_000),
  // Per person and second, whatever agents or machines the calls name, so made-up ids cannot spend the minute's budget
  // at once. 200 agents polling once a second can land up to 400 in one second when polls arrive late: 500 is above it.
  ROUTE_RATE_LIMIT_PER_PERSON_SECOND: z.coerce.number().int().min(0).default(500),
  // What each process keeps of the Swarms it read, by their stamps in Redis (superTabs/cache.ts). 'off' is the kill switch:
  // every read goes to Mongo again, while writes still bump the stamps, so processes that keep theirs on stay right.
  SWARM_READ_CACHE: z.enum(['on', 'off']).default('on'),
  // The read cache patches what it holds from the parts that changed (superTabs/cache.ts, spec 2026-11-02); off: a bump drops it.
  SWARM_CACHE_DELTA: z.enum(['on', 'off']).default('on'),
  // The share of patches checked against a full load in the background: the drift alarm in the `swarm cache` log.
  SWARM_CACHE_VERIFY_RATE: z.coerce.number().min(0).max(1).default(0.01),
  // A frame an adapter sends for one viewer goes to the process holding that viewer (lib/terminalRoute.ts), found by its
  // record in Redis, instead of to every process with a viewer of the machine. 'off' is the kill switch: such frames go
  // through the machine's channels again; a viewer on the adapter's own process is still served directly.
  TERMINAL_POD_ROUTES: z.enum(['on', 'off']).default('on'),
  // `__clients` tells each daemon it may hold a machine's live events while no app views it (lib/hub.ts). 'off' is the
  // kill switch: the frame stops saying so, and daemons send every event again with no release of their own.
  RELAY_UI_GATE: z.enum(['on', 'off']).default('on'),
  // Its size per process, counted as the JSON size of what it holds.
  SWARM_CACHE_MB: z.string().default('64').transform(Number),
  // The worker's hourly move of finished deliveries older than 14 days into their messages' receipts
  // (superTabs/deliveryCompaction.ts). 'off' is the kill switch: set it before rolling back to a release whose pages do not
  // read compacted receipts.
  SWARM_DELIVERY_COMPACTION: z.enum(['on', 'off']).default('on'),

  // This backend instance's stable id (used to route manager-command replies via Redis in a
  // multi-instance deploy). Defaults to the pm2 instance index or a per-process fallback.
  BACKEND_INSTANCE_ID: z.string().default(''),

  // Instance mesh (Phase 2 of the data-plane short-circuit): each backend instance/worker binds an
  // INTERNAL-only listener and advertises its endpoint in Redis (inst:{id}:mesh). A public app-request
  // that lands on an instance NOT holding the agent's manager socket is forwarded to the instance that
  // does (agent:{machineId}:appinst), so the data path is a direct backpressured socket, not Redis relay.
  // Off by default (single-instance/dev needs nothing — it's always co-located). Enable in multi-instance.
  MESH_ENABLED: z.string().default('false').transform((v) => v === 'true'),
  // Host the mesh endpoint is reachable at from OTHER instances: 127.0.0.1 for a single-host pm2 cluster,
  // the VM's routable IP for multi-VM. Advertised verbatim in Redis.
  MESH_HOST: z.string().default('127.0.0.1'),
  // Base internal port; each worker binds MESH_PORT_BASE + NODE_APP_INSTANCE (distinct per worker).
  MESH_PORT_BASE: z.string().default('8095').transform(Number),

  // On SIGTERM the API answers /api/ready with 503 at once, then keeps serving this long before it closes its
  // listeners, so the load balancer stops sending new connections first. 0 (the default) closes at once, as before;
  // Kubernetes sets it, with probes and grace period, as backend/README.md describes.
  DRAIN_DELAY_MS: z.coerce.number().int().min(0).max(60_000).default(0),

  // Prometheus /metrics on an internal listener of its own (lib/metrics.ts), never the public PORT. Always
  // on; each pm2 worker binds METRICS_PORT_BASE + NODE_APP_INSTANCE. Loopback by default: a pod whose
  // scraper reads the pod IP sets METRICS_HOST=0.0.0.0 and does NOT list the port on its Service.
  METRICS_PORT_BASE: z.coerce.number().int().min(1).max(65535).default(9464),
  METRICS_HOST: z.string().default('127.0.0.1'),

  // Remote-terminal WebRTC is STUN-only: successful ICE bypasses the backend data relay; failed ICE
  // keeps using the existing WebSocket route. Enabled by default; percentage 0 is the kill switch.
  TERMINAL_P2P_ROLLOUT_PERCENT: z.coerce.number().int().min(0).max(100).default(100),
  // Comma-separated, capped at ten (was eight until 2026-09-10 — the CLI's own parsing of this list on
  // the OFFERER side, remoteRelay.ts's p2pPolicy(), was separately capping at 4, so half of whatever
  // shipped here was silently dropped before an offer was ever built; raised there to 10 to match).
  // werift itself has no failover — parseIceServers() collapses the list to a single `stunServer`
  // (first stun: url wins) — so the CLI races these with its own STUN binding requests and hands
  // werift the fastest responder (cli/src/lib/stunSelect.ts). Older CLIs simply use the first entry,
  // exactly as before, so a longer list is safe to ship at any time.
  // Port 53 is here because networks that drop unusual UDP ports usually still pass DNS; the race
  // drops it at runtime if it ever stops answering, so listing it costs nothing.
  // Beyond Cloudflare: two Google mirrors, Twilio, Nextcloud (also firewall-friendly :443), Ekiga and
  // VoIPGate — all live-probed with a real RFC 5389 binding request before being added (2026-09-09);
  // stun.stunprotocol.org and stun.services.mozilla.com were dropped for the same reason (no DNS record
  // any more). Added 2026-09-10, also live-probed: Linphone's official server (Belledonne
  // Communications — has its own documented DNS-SRV failover to sip1.linphone.org, unlike the
  // similarly-themed stun.freeswitch.org and stun.antisip.com candidates considered and rejected —
  // the former has open GitHub issues reporting real instability, the latter has no confirmed owner at
  // all) and Xiaomi's MiWiFi server, which is real production infra for millions of routers and — more
  // to the point — the one entry here actually reachable from behind networks that block the Western
  // majority of this list, filling a gap none of the other eight cover.
  TERMINAL_P2P_STUN_URLS: z.string().default(
    'stun:stun.cloudflare.com:3478,stun:stun.cloudflare.com:53,'
    + 'stun:stun.l.google.com:19302,stun:stun2.l.google.com:19302,'
    + 'stun:global.stun.twilio.com:3478,stun:stun.nextcloud.com:443,'
    + 'stun:stun.ekiga.net:3478,stun:stun.voipgate.com:3478,'
    + 'stun:stun.linphone.org:3478,stun:stun.miwifi.com:3478',
  ),
  // 2500, not 1500: a TURN-relayed data channel was measured opening in 1372ms, and this is the gate
  // (remoteRelay.ts) that decides whether the FIRST terminal takes p2p or falls back to the WS relay.
  // At 1500 the relay path loses that race almost every time and only the second terminal gets p2p.
  TERMINAL_P2P_OPEN_WAIT_MS: z.coerce.number().int().min(0).max(5000).default(2500),

  // Cloudflare Realtime TURN. Optional on purpose: with no key the policy ships STUN-only, which is
  // exactly the pre-TURN behaviour, so clearing TERMINAL_P2P_TURN_KEY_ID is the kill switch. Checked
  // at the consumer (lib/turnCredentials.ts), not here — same as GEMINI_API_KEY/DEEPGRAM_API_KEY.
  TERMINAL_P2P_TURN_KEY_ID: z.string().optional(),
  TERMINAL_P2P_TURN_API_TOKEN: z.string().optional(),
  // Cloudflare caps credential ttl at 172800 (48h); we refresh well before expiry anyway.
  TERMINAL_P2P_TURN_TTL_SECONDS: z.coerce.number().int().min(600).max(172800).default(7200),
  TERMINAL_P2P_TURN_TIMEOUT_MS: z.coerce.number().int().min(1000).max(30000).default(5000),

  // No manager env: each manager publishes its apiKey + capacity into the `managers` collection;
  // the backend authenticates the manager's dial-in socket (/api/manager-ws) against that apiKey and
  // picks a manager on create by capacity (machines.managerId → managers). See lib/managers.ts.

  // The connector gateway (lib/connectorGateway.ts): its OAuth apps (GitHub, Slack, Google…) live in
  // MongoDB (`connector_apps`), edited directly or written by `npm run connectors:import <file>`.
  // The redirect every one of those apps allows: the Autonomous web page, which forwards a `harness_`
  // state here (POST /api/connectors/callback). Staging: https://staging.autonomousdev.xyz/connector/callback.
  CONNECTOR_REDIRECT_URI: z.string().url().default('https://www.autonomous.ai/connector/callback'),

  // Autonomous SSO (OAuth2 Authorization Code + PKCE). The backend exchanges the code, then hands
  // the SSO access token to the web. Control-plane REST + web WS validate that token through the
  // Autonomous profile API instead of minting a second backend-owned session JWT.
  SSO_ISSUER: z.string().default('https://auth.autonomous.ai'),
  SSO_CLIENT_ID: z.string().default('command_57db108dd2391a9a4bedd6d079bdbe3e'),
  SSO_CLIENT_SECRET: z.string().optional(), // public client (PKCE, auth method 'none') → leave unset
  SSO_SCOPE: z.string().default('openid profile email roles'),
  SSO_PROFILE_URL: z.string().default('https://apiv2.autonomous.ai/api/v1/me/profile'),
  // The cheap way to prove a token: the same answer shape as SSO_PROFILE_URL with no customer or cart
  // read behind it. Asked first; SSO_PROFILE_URL is the fallback on a 404 (a BFF that predates the
  // route). '' turns it off — set that, or your own URL, WHENEVER you move SSO_PROFILE_URL, or tokens
  // for your host get proved against this one.
  SSO_IDENTITY_URL: z.string().default('https://apiv2.autonomous.ai/api/v1/me/identity'),
  // Per-user staging override. Production remains the default; these are consulted only after the
  // login transaction/user record explicitly selects `stag`.
  STAGING_SSO_ISSUER: z.string().default('https://auth.staging.autonomousdev.xyz'),
  STAGING_SSO_CLIENT_ID: z.string().optional(),
  STAGING_SSO_CLIENT_SECRET: z.string().optional(),
  STAGING_SSO_PROFILE_URL: z.string().default('https://apiv2.staging.autonomousdev.xyz/api/v1/me/profile'),
  STAGING_SSO_IDENTITY_URL: z.string().default('https://apiv2.staging.autonomousdev.xyz/api/v1/me/identity'),
  SSO_PROFILE_TIMEOUT_MS: z.coerce.number().int().positive().default(5000),
  // How long a token the profile API just accepted is trusted without asking again (0 = ask every
  // time). This is also the longest a token revoked at the SSO keeps working here.
  SSO_PROFILE_CACHE_TTL_MS: z.coerce.number().int().min(0).default(60_000),
  // While the profile service cannot answer (down, slow, circuit open), a token this process validated up to this long
  // past its TTL keeps working, so an SSO outage does not sign out people who are working (lib/ssoProfileCache.ts).
  // Never past the token's own expiry, never for a token the service rejected. The cost: during an outage a token revoked
  // at the SSO keeps working this long. Off (0) until the owner decides; 600000 (10 min) is the value it was built for.
  SSO_PROFILE_STALE_GRACE_MS: z.coerce.number().int().min(0).default(0),
  // Forces the SSO account picker so users can switch accounts (not silently auto-login the last one).
  // Set to '' to disable, or 'login' to force re-entering credentials.
  SSO_PROMPT: z.string().default('select_account'),
  // Backend callback registered with the SSO client. LEAVE EMPTY to auto-derive from the request host
  // (so live→live, local→local); set explicitly only to pin one value. Must be a value registered
  // with the client on the Autonomous side.
  SSO_REDIRECT_URI: z.string().default(''),
  // The primary/fallback SPA origin the browser is sent back to after login (also the first allowed
  // origin). Live sets this to https://harness.autonomous.ai.
  WEB_URL: z.string().default('http://localhost:3000'),
  // Extra allowed SPA origins (comma-separated), e.g. to let one backend serve both live + local.
  // The post-login token is only ever redirected to an origin in this allowlist (never an arbitrary
  // one from the request), so it can't be leaked to a spoofed host.
  WEB_ORIGINS: z.string().default(''),

  // Autonomous campaign billing for NEW managed machines. A cold catalog outage still cannot expose
  // incomplete plans: the seeder retains a complete cache or falls back to Remote only.
  HARNESS_BILLING_ENABLED: z.string().default('true').transform((v) => v === 'true'),
  // Ceiling on billing-free Remote machines auto-created by the device-auth grant
  // (`harness auth device`). That path is free and its computer id is self-declared, so this caps the
  // rows one account can mint; 0 disables the check. Hygiene, not a security control.
  HARNESS_DEVICE_AUTH_MACHINE_LIMIT: z.coerce.number().int().min(0).default(20),
  // Same idea for device rows (`/api/device-ws` resolves-or-creates one per self-declared computer id).
  // A revoked device is hard-deleted, so the ceiling alone is not enough — see the rates below.
  HARNESS_DEVICE_LIMIT: z.coerce.number().int().min(0).default(20),
  // How fast one account may mint NEW machine / device ids (Redis fixed windows, shared by every
  // replica). A reconnect of an existing id never counts. Ceilings above stop a pile-up; these stop a
  // create → delete → create loop, which the ceilings cannot see. 0 disables that window.
  HARNESS_NEW_MACHINE_PER_HOUR: z.coerce.number().int().min(0).default(5),
  HARNESS_NEW_MACHINE_PER_DAY: z.coerce.number().int().min(0).default(20),
  HARNESS_NEW_DEVICE_PER_HOUR: z.coerce.number().int().min(0).default(5),
  HARNESS_NEW_DEVICE_PER_DAY: z.coerce.number().int().min(0).default(20),
  AUTONOMOUS_BFF_URL: z.string().url().default('https://apiv2.autonomous.ai'),
  STAGING_AUTONOMOUS_BFF_URL: z.string().url().default('https://apiv2.staging.autonomousdev.xyz'),
  // Server-to-server subscription snapshots used by the singleton billing worker. These use
  // environment-specific x-api-key credentials, never a user's SSO access token.
  AUTONOMOUS_CAMPAIGN_API_URL: z.string().url().default('https://campaign-api.autonomous.ai'),
  STAGING_AUTONOMOUS_CAMPAIGN_API_URL: z.string().url().default('https://campaign-api.staging.autonomousdev.xyz'),
  AUTONOMOUS_CAMPAIGN_API_KEY: z.string().optional(),
  STAGING_AUTONOMOUS_CAMPAIGN_API_KEY: z.string().optional(),
  // Origins accepted by Autonomous' hosted-checkout endpoint. They belong to the selected
  // Autonomous environment, not to the Machine UI that supplied success_url/failure_url.
  AUTONOMOUS_CHECKOUT_ORIGIN: z.string().url().default('https://autonomous.ai'),
  STAGING_AUTONOMOUS_CHECKOUT_ORIGIN: z.string().url().default('https://staging.autonomousdev.xyz'),
  AUTONOMOUS_BFF_TIMEOUT_MS: z.coerce.number().int().positive().default(10000),
  // NB: the VALUE is an identifier registered on the EXTERNAL campaign API — subscriptions are matched
  // by campaignCode, so this must stay in lockstep with the campaign registered there. Renamed to
  // `ai-harness-device` with the Machine rebrand: the campaign has to be renamed on the campaign side
  // too, otherwise existing subscriptions stop matching and machines read as unpaid.
  HARNESS_CAMPAIGN_CODE: z.string().default('ai-harness-device'),
  HARNESS_DEVICE_TYPE: z.coerce.number().int().positive().default(15),
  HARNESS_DEVICE_TIMEZONE_DEFAULT: z.string().default('Asia/Saigon'),
  // DEV ONLY. A `provider` machine dials a URL its owner typed, so plain http:// and loopback are
  // refused (see lib/providerUrl.ts). This flag lifts the scheme check so a developer can point a
  // machine at a local example-provider (autonomous-ai/openharness). Setting it in production
  // disables an SSRF control — boot
  // logs a FATAL-level warning if it is on there.
  PROVIDER_ALLOW_INSECURE_URLS: z.coerce.boolean().default(false),
  // Callback page on the web app. When empty, WEB_URL/machine-checkout is used.
  HARNESS_CHECKOUT_CALLBACK_URL: z.string().default(''),
  // Shared with agent-manager. 32 raw bytes encoded as base64; required when billing is enabled.
  HARNESS_CREDENTIAL_ENCRYPTION_KEY: z.string().default(''),
  // Keys the pseudonym of a person's 10-day activity marks (lib/productUsage.ts `markActivity`).
  // Empty: no marks are written. Set it only after the apps describing the marks have shipped.
  PRODUCT_USAGE_SUBJECT_KEY: z.string().refine(v => v === '' || v.length >= 32, 'must be at least 32 characters').default(''),

  // Comma-separated emails granted role=admin on first creation.
  ADMIN_EMAILS: z.string().default(''),
  // A Slack incoming webhook told when reports hide a Hub publication or comment (lib/communityReports.ts).
  // Empty: nothing is sent; reviewers find them at /hub/reports.
  COMMUNITY_REPORTS_WEBHOOK_URL: z.string().url().or(z.literal('')).default(''),

  // Server availability, not user opt-in. Accounts must enable the creature in Experimental settings.
  // Explicit false keeps the module dark; the optional allowlist further limits availability.
  HARNESS_DAEMONS: z.string().default('true'),
  HARNESS_DAEMONS_USERS: z.string().default(''),

  // Device voice STT (PCM arrives on /api/device-ws → batch STT). VOICE_PROVIDER selects the backend:
  //   'deepgram' → needs DEEPGRAM_API_KEY
  //   'gemini'   → needs GEMINI_API_KEY (model via GEMINI_STT_MODEL)
  VOICE_PROVIDER: z.enum(['deepgram', 'gemini']).default('deepgram'),
  DEEPGRAM_API_KEY: z.string().optional(),
  GEMINI_API_KEY: z.string().optional(),
  GEMINI_STT_MODEL: z.string().default('gemini-2.0-flash'),

  // Shared secret for POST /api/cursor/stt — the standalone file-upload STT endpoint the Cursor desktop
  // app calls (routes/cursor.ts). That client is neither a device nor a browser session, so it holds
  // no machine api key and no SSO token; this is its only credential, sent as the `api_key` header.
  // Optional here, but the route fails CLOSED when unset: an absent secret must never read as "open" on
  // an endpoint that spends Deepgram credit.
  CURSOR_STT_API_KEY: z.string().optional(),

  // The LLM behind POST /api/cursor/summarize — an OpenAI-compatible endpoint (the Grid relay). The base
  // URL already ends in `/v1` and embeds a network id, and the key is a long-lived JWT, so neither is
  // hardcoded; routes/cursor.ts appends `/chat/completions`. URL and key are optional here but the route
  // fails CLOSED without them, for the same reason CURSOR_STT_API_KEY does: this endpoint spends credit.
  CURSOR_LLM_BASE_URL: z.string().optional(),
  CURSOR_LLM_API_KEY: z.string().optional(),
  CURSOR_LLM_MODEL: z.string().default('DeepSeek-V4-Flash-0731'),

  // Harness's own OpenRouter key, spent on ⌘B's Jev decisions for people with no key of their own
  // (routes/jevRoute.ts). Optional here, but the route fails CLOSED without it. Give it its own key with
  // a credit limit on OpenRouter: that limit is the budget, the route's per-account caps only spread it.
  JEV_OPENROUTER_API_KEY: z.string().optional(),
  // Decisions a day across every account, on top of each account's own cap: at an average ⌘B (~$0.00017),
  // the default is about $34 a day. A decision at the route's size bounds costs several times that, so the
  // key's OpenRouter credit limit stays the hard cap. Past it ⌘B says Harness's Jev budget has run out until the next UTC day.
  JEV_DAILY_DECISIONS: z.coerce.number().int().positive().default(200_000),

  // Super Tab chat attachments (superTabs/attachments.ts). Clients upload through POST /api/super-tabs/:tabId/attachments,
  // which streams each file into this GCS bucket (10 MB at most); everyone reads it through the public CDN. No bucket:
  // uploads answer ATTACHMENTS_UNAVAILABLE and chat stays text only.
  SUPER_TAB_ATTACHMENTS_BUCKET: z.string().default(''),
  // The base64 of the service account JSON key that writes to the bucket. Empty: application default credentials (Workload Identity, or GOOGLE_APPLICATION_CREDENTIALS). A value that
  // is not base64 of such a key stops the backend at startup, with a message that never shows the value.
  SUPER_TAB_ATTACHMENTS_CREDENTIALS: z.string().default(''),
  SUPER_TAB_ATTACHMENTS_PREFIX: z.string().default('super-tabs'),
  // Where clients read the files. https:// in production (superTabs/attachments.ts refuses anything else at startup).
  SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: z.string().url().default('https://cdn.harness.autonomous.ai'),
  // A private bucket (no public read) for Swarm avatars, served only through signed links that expire. Unset: avatars go in
  // the attachments bucket under avatars/ and are linked on its public CDN like chat files, links that never expire
  // (docs/swarms.md). No attachments bucket either: avatar uploads are off.
  SUPER_TAB_AVATARS_BUCKET: z.string().default(''),

  // The Harness GitHub App (github/app.ts, docs/swarm-github-app.md): a Swarm agent doing a task pushes and opens pull
  // requests with a one-hour token for its project's repository alone. Both empty: off, and POST
  // /api/super-tabs/:tabId/github-token answers GITHUB_APP_NOT_CONFIGURED. One without the other, or a key that cannot be
  // read, stops the backend at startup with a message that never shows the key. The ID is the numeric App ID (or the
  // Client ID); the key is the app's PEM private key as downloaded, with its line breaks as \n, or base64 of the file.
  GITHUB_APP_ID: z.string().default(''),
  GITHUB_APP_PRIVATE_KEY: z.string().default(''),
  // The app's name in github.com/apps/NAME, for the install link a refusal gives. Optional.
  GITHUB_APP_SLUG: z.string().default(''),
  // The app's own GitHub sign-in (its Client ID and a client secret), with which a person who can push to a repository
  // approves it for a Swarm (github/approvals.ts). Unset, no repository can be approved and the app gives no token.
  GITHUB_APP_CLIENT_ID: z.string().default(''),
  GITHUB_APP_CLIENT_SECRET: z.string().default(''),

  // Phone push (push/keys.ts, task #2905): a thread reply or a tag reaches a phone whose app is closed. APNs for iPhones: the
  // Production key Apple generated in the developer account (the .p8 file, with its line breaks as \n, or base64 of it), its Key ID and
  // the Team ID; all three or none. FCM for Android: base64 of the Firebase service account's JSON key. Unset: that platform
  // gets no push, and each one skipped is counted and logged. A value that cannot be right stops the backend at startup, with
  // a message that never shows it.
  APNS_KEY_ID: z.string().default(''),
  APNS_TEAM_ID: z.string().default(''),
  APNS_PRIVATE_KEY: z.string().default(''),
  // Apple's keys are per environment: the three above are the Production key, used on Apple's production host alone. The
  // Sandbox key, for an Xcode build's tokens, is used on the sandbox host alone; both or neither, and only beside the
  // production key. Unset: an Xcode build's push is skipped, and logged (Ken, 11-05).
  APNS_SANDBOX_KEY_ID: z.string().default(''),
  APNS_SANDBOX_PRIVATE_KEY: z.string().default(''),
  // The iPhone app's bundle id, which Apple sends to.
  APNS_TOPIC: z.string().default('ai.autonomous.harness.ios'),
  FCM_SERVICE_ACCOUNT: z.string().default(''),

  // TTL for the in-memory subdomain→machineId cache on the public app-proxy hot path
  // (avoids a Mongo lookup per request). Bounds staleness after a cross-instance app teardown.
  // 60 min default (mapping is stable; a same-instance delete evicts immediately).
  AGENT_TARGET_CACHE_TTL_MS: z.string().default('3600000').transform(Number),
  // TTL for NEGATIVE caching of unknown subdomains — so scans/misconfigured DNS hitting nonexistent
  // subdomains don't hit Mongo on every request. Short so a subdomain registered on another instance
  // becomes reachable quickly. 5s default.
  AGENT_TARGET_NEG_CACHE_TTL_MS: z.string().default('5000').transform(Number),

  // Public app-proxy safety limits. 0 disables the byte limit for that direction. These protect the
  // unauthenticated subdomain data-plane from unbounded tunnel/socket buffering.
  APP_PROXY_MAX_REQUEST_BYTES: z.string().default('104857600').transform(Number), // 100 MiB
  APP_PROXY_MAX_RESPONSE_BYTES: z.string().default('536870912').transform(Number), // 512 MiB
  APP_PROXY_MAX_WS_FRAME_BYTES: z.string().default('8388608').transform(Number), // 8 MiB
  APP_PROXY_MAX_STREAMS_PER_SUBDOMAIN: z.string().default('128').transform(Number),
  APP_PROXY_IDLE_TIMEOUT_MS: z.string().default('300000').transform(Number), // 5 min
  // Largest single app-proxy frame relayed CROSS-INSTANCE through Redis pub/sub (co-located streams
  // never touch Redis). Above it the stream is aborted rather than published: Redis disconnects a
  // pub/sub subscriber that exceeds client-output-buffer-limit, so an oversized message is a threat to
  // every stream on that connection, not just its own. Default sits just above the largest legitimate
  // frame (APP_PROXY_MAX_WS_FRAME_BYTES base64'd into JSON).
  APP_PROXY_MAX_RELAY_FRAME_BYTES: z.string().default('16777216').transform(Number), // 16 MiB

  // Voice PCM held in this process across ALL device sockets (each utterance can reach stt.MAX_PCM =
  // 20 MiB). A budget rather than a per-socket cap so N devices rambling at once degrade to a
  // VOICE_BUFFER_FULL error instead of an OOM. Size against the worker heap (ecosystem.config.cjs).
  VOICE_INFLIGHT_MAX_BYTES: z.string().default('536870912').transform(Number), // 512 MiB

})

export type Env = z.infer<typeof envSchema>

function validateEnv(): Env {
  const parsed = envSchema.safeParse(process.env)
  if (!parsed.success) {
    console.error('Invalid environment variables:', parsed.error.flatten().fieldErrors)
    process.exit(1)
  }
  const data = parsed.data
  if (data.HARNESS_BILLING_ENABLED) {
    let key: Buffer
    try { key = Buffer.from(data.HARNESS_CREDENTIAL_ENCRYPTION_KEY, 'base64') } catch { key = Buffer.alloc(0) }
    if (key.length !== 32) {
      console.error('Invalid environment variables: HARNESS_CREDENTIAL_ENCRYPTION_KEY must be 32 bytes encoded as base64 when HARNESS_BILLING_ENABLED=true')
      process.exit(1)
    }
  }
  return data
}

export const env = validateEnv()

/** Lower-cased set of admin emails (empty entries dropped). */
export const ADMIN_EMAILS = new Set(
  env.ADMIN_EMAILS.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean),
)

/** Server availability (lib/daemonsSwitch.ts). The account's Experimental opt-in defaults off. */
export const DAEMONS = parseDaemonsSwitch(env.HARNESS_DAEMONS, env.HARNESS_DAEMONS_USERS)