Repository navigation
Expand file tree
/
Copy path.env.example
More file actions
4594 lines (4035 loc) · 263 KB
/
Copy path.env.example
File metadata and controls
4594 lines (4035 loc) · 263 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ┌─────────────────────────────────────────────────────────────────────────────┐
# │ OmniRoute — .env Contract │
# │ This file documents EVERY environment variable read by the runtime. │
# │ Copy to .env and adjust values. Lines starting with # are commented out │
# │ (optional / off-by-default). Uncomment only what you need. │
# │ Reference: docs/ENVIRONMENT.md for full details and usage scenarios. │
# └─────────────────────────────────────────────────────────────────────────────┘
# ═══════════════════════════════════════════════════════════════════════════════
# 1. REQUIRED SECRETS — Must be set before first run!
# ═══════════════════════════════════════════════════════════════════════════════
# These secrets are critical for security. Generate strong, unique values.
# JWT signing key for dashboard session tokens.
# Used by: src/lib/auth — signs/verifies all authenticated session cookies.
# Generate: openssl rand -base64 48
JWT_SECRET=
# Encryption key for API keys stored in the database.
# Used by: src/lib/db/apiKeys.ts — encrypts API key values at rest in SQLite.
# Generate: openssl rand -hex 32
API_KEY_SECRET=
# Initial admin login password — CHANGE THIS before first use!
# Used by: src/lib/auth/managementPassword.ts — sets the dashboard password at startup
# while none is saved yet; ignored once a password is saved.
# After first login you can change it from Dashboard → Settings → Security.
# CHANGEME (this template's value) is publicly known. npm and source installs copy this
# file to .env, so replace CHANGEME there before first boot, or set INITIAL_PASSWORD=
# (empty) there to create the password in the dashboard's onboarding wizard instead.
INITIAL_PASSWORD=CHANGEME
# ═══════════════════════════════════════════════════════════════════════════════
# 2. STORAGE & DATABASE
# ═══════════════════════════════════════════════════════════════════════════════
# OmniRoute uses SQLite for all persistence. These variables control where
# data lives, encryption, and cleanup policies.
# Base directory for all persistent data (SQLite DB, logs, backups).
# Used by: src/lib/db/core.ts — resolves the SQLite database file path.
# Default: ~/.omniroute/ | Override for Docker or custom installations.
# Hint: When running in Docker, consider mounting a host directory here for data persistence across container restarts
# also if you want to share the same database as "npm run dev" use "./data"
# DATA_DIR=/var/lib/omniroute
# Fallback alias for DATA_DIR, checked only when DATA_DIR is unset.
# Used by: open-sse/executors/promptql/threadSticky.ts — locates the PromptQL
# executor's on-disk thread-sticky session cache. Leave unset to rely on DATA_DIR.
# OMNIROUTE_DATA_DIR=/var/lib/omniroute
# Directory the runtime plugin scanner reads, overriding the home-derived default (#11827).
# Used by: src/lib/plugins/scanner.ts — getDefaultPluginDir(); it is also the root the
# plugin manager installs into. Set it in Docker/K8s to point straight at the bind-mounted
# plugin tree, instead of moving HOME (which changes every other HOME-relative behaviour)
# just to relocate the scan path. Unset = <HOME>/.omniroute/plugins, and
# /tmp/.omniroute/plugins when the process exports no home at all.
# Distinct from the CLI-only variable in section 9 that points the omniroute-cmd-* command
# loader (bin/cli/plugins.mjs) at a package tree — this one drives the server-side scanner.
# OMNIROUTE_PLUGINS_DIR=/opt/omniroute/plugins
# Escape hatch for the test/eval DATA_DIR guard (#10428). A test or node eval/print
# probe (-e/--eval/-p/--print, including --eval=/--print=) that never chose a DATA_DIR
# is redirected to a throwaway temp dir so it cannot open the operator's real database.
# Set to 1 only for a deliberate run against the real DATA_DIR — never for CI.
# Used by: src/lib/dataPaths.ts
# OMNIROUTE_ALLOW_DEFAULT_DATA_DIR=1
# Build provenance (#10427). OMNIROUTE_BUILD_SHA lets a container inject the artifact's git
# SHA when the dist/BUILD_SHA sentinel is absent; it is also what `npm run build:release`
# stamps. OMNIROUTE_RELEASE_REF is the ref the pack gate checks ancestry against, and
# OMNIROUTE_ALLOW_CANARY_BUILD=1
# API key the canary-deploy smoke uses when the target gateway requires auth (#10429).
# Used by: scripts/ops/deploy-canary.mjs — sent as `Authorization: Bearer` on the
# /v1/chat/completions probe. Never needed by the server itself.
# OMNIROUTE_SMOKE_API_KEY=sk-... records a deliberate off-release-line build instead of
# failing it. Used by: scripts/build/buildProvenance.ts, src/lib/monitoring/buildSha.ts
# OMNIROUTE_BUILD_SHA=abc1234
# OMNIROUTE_RELEASE_REF=origin/main
# OMNIROUTE_ALLOW_CANARY_BUILD=1
# Build-phase signal (#10060). Set to 1 by scripts/build/build-next-isolated.mjs and
# inherited by every spawned build worker so the DB layer returns a no-op stub instead
# of loading the native better-sqlite3 addon (which aborts the worker on exit).
# Never set this for the running server. Used by: src/lib/buildPhase.ts, src/lib/db/core.ts
# OMNIROUTE_BUILDING=1
# Skip the optional native-dependency prebuild check for exotic vendored trees.
# This does not make a missing dependency buildable. Used by: scripts/check/check-native-deps.mjs
# Default: 0 | Set to 1 only when native dependencies are supplied out of band.
# OMNIROUTE_SKIP_NATIVE_DEP_CHECK=0
# Encryption key for SQLite database encryption at rest.
# Used by: src/lib/db/encryption.ts — encrypts the entire SQLite database.
# Generate: openssl rand -hex 32 | Leave empty to disable DB encryption.
STORAGE_ENCRYPTION_KEY=
# Version tag for the encryption key — allows future key rotation.
# Used by: scripts/bootstrap-env.mjs, electron/main.js — persists key version.
# Default: v1 | Increment when rotating STORAGE_ENCRYPTION_KEY.
STORAGE_ENCRYPTION_KEY_VERSION=v1
# Routine/pre-write SQLite backups.
# Used by: src/lib/db/backup.ts. Set true only when those backups are managed externally.
# This never disables the migration runner's mandatory, content-addressed safety snapshot
# or its mass-migration guard for an existing persistent database.
# Default: false (routine backups enabled).
DISABLE_SQLITE_AUTO_BACKUP=false
# Opt-in synchronous SQLite adapter timing. Unset means off.
# Used by: src/lib/db/adapters/slowDiagnostics.ts
# OMNIROUTE_SQLITE_SLOW_MS=200
# Background SQLite planner statistics maintenance, independent of retention cleanup.
# Used by: src/lib/db/sqlitePlannerStats.ts via the cleanup scheduler.
# First pass: 30s after startup, after migrations; then every 6 hours.
# Default: true. Set false or 0 to disable all planner-statistics maintenance.
OMNIROUTE_SQLITE_OPTIMIZE_ENABLED=true
# Analysis row sampling limit: default 400; 0 = unlimited, exact analysis.
# Unlimited mode also disables SQLite's periodic optimize sampling cap.
# Decimal integers clamped to [0, 100000]; invalid values fall back to 400.
OMNIROUTE_SQLITE_ANALYSIS_LIMIT=400
# ── Redis (Rate Limiting) ──
# Redis connection URL for the rate limiter backend. OPT-IN: leave this
# commented out to use the built-in in-memory rate limiter. Setting it to a
# non-running localhost (#4878) makes ioredis flood "[REDIS] Error:" logs.
# Used by: src/shared/utils/rateLimiter.ts
# Example: redis://localhost:6379 (or redis://redis:6379 in Docker)
# REDIS_URL=redis://localhost:6379
# Namespace prefix for ALL OmniRoute Redis keys (rate limiter + auth cache +
# quota store + warmup circuit breaker). Prevents key collisions when OmniRoute
# shares a Redis instance with other apps (e.g. on 127.0.0.1:6379). Default when
# unset: omniroute:
# REDIS_KEY_PREFIX=omniroute:
# Optional shared session -> account affinity (slice 1a). Default: sqlite.
# redis requires REDIS_URL; uses the same client and REDIS_KEY_PREFIX.
# sessionAffinityTtlMs must remain positive; Redis calls fall back to SQLite after 100 ms.
# The timeout bounds waiting, not a sent EVAL, which may land after fallback.
# Each Redis affinity store caps outstanding operations at 8; full stores use SQLite immediately.
# SQLite routing keeps the legacy four-field JSON; Redis pins include hashed identity.
# Shared writes CAS against the routing observation (SQLite fallback records count as a miss).
# Redis alone is authoritative while it answers; confirmed mutations never write SQLite.
# Confirmed upserts/touches/deletes remove local entries; eviction uses the local identity guard.
# Only Redis errors, timeouts or admission saturation write local outage decisions,
# with the existing bounded TTL.
# Rejected upsert adopts a still-live eligible winner; unavailable winners keep the local candidate.
# On rejection, lease commits keep the claimed account for this request only, leaving shared unchanged.
# Late sent-mutation replies clean their timeout row by exact serialized-value compare-and-delete.
# During outage instances may re-pin independently; stickiness re-converges when Redis recovers.
# Known account identity overrides contradictory local IDs in resolution and guarded eviction.
# Shared liveness uses atomic value/PTTL reads; local snapshots map Redis's remaining TTL.
# JSON expiresAt is informational on Redis; existing keys retain their format and CAS bytes.
# Guarded eviction clears the failed account locally even when Redis is down.
# Successful shared replies can only remove local pins, never resurrect an evicted account.
# Does not share combo stickiness, native turn pins, concurrency or spend limits.
# OMNIROUTE_SESSION_AFFINITY_STORE=sqlite
# Host interface docker-compose publishes the Redis sidecar on.
# Default: 127.0.0.1 (loopback only). The compose Redis runs WITHOUT
# `requirepass`, and app containers reach it over the compose network
# (redis:6379) — the published port is only for host-side tooling. Setting this
# to 0.0.0.0 exposes an unauthenticated Redis to your whole LAN.
# REDIS_BIND_HOST=127.0.0.1
# Host port for the compose Redis sidecar. Default: 6379.
# REDIS_PORT=6379
# Host interface docker-compose publishes the app's own ports (dashboard,
# API, live-WS) on for the base/web/cli/host profiles and docker-compose.prod.yml.
# Default: 127.0.0.1 (loopback only). Combined with REQUIRE_API_KEY=false
# (the default below), an unqualified publish spec would expose the anonymous
# /v1 LLM proxy to your whole LAN/WAN. Only set this to 0.0.0.0 once you've
# confirmed REQUIRE_API_KEY=true, or that a reverse proxy in front of this
# instance already enforces its own authentication. (#12568)
# APP_BIND_HOST=127.0.0.1
# Host interface docker-compose publishes the Qdrant memory sidecar on.
# Default: 127.0.0.1 (loopback only). Same LAN-exposure reasoning as Redis.
# QDRANT_BIND_HOST=127.0.0.1
# Host interface docker-compose publishes the Bifrost router sidecar on.
# Default: 127.0.0.1 (loopback only). Same LAN-exposure reasoning as Redis.
# BIFROST_BIND_HOST=127.0.0.1
# ═══════════════════════════════════════════════════════════════════════════════
# 3. NETWORK & PORTS
# ═══════════════════════════════════════════════════════════════════════════════
# OmniRoute can run on a single port (default) or split Dashboard/API ports.
# Canonical port for both Dashboard UI and API (single-port mode).
# Used by: src/lib/runtime/ports.ts — base port for the Next.js server.
# Default: 20128
PORT=20128
# Base path (URL subpath) when serving OmniRoute behind a reverse proxy under a subpath.
# Used by: next.config.mjs — sets Next.js `basePath`; auth redirects are basePath-aware.
# Also mirrored to NEXT_PUBLIC_OMNIROUTE_BASE_PATH at build time so the dashboard
# endpoint display (useDisplayBaseUrl) shows https://host/omniroute/v1 instead of
# https://host/v1. Rebuild after changing this value (Next basePath is build-time).
# Default: "" (served at the domain root). Example: /omniroute to serve under https://host/omniroute
# Docker: baked at image build time via build-arg; root-path images can also apply this at
# container start (see docs/guides/DOCKER_GUIDE.md).
# OMNIROUTE_BASE_PATH=
# Client fetch/EventSource under this path are rewritten via installBasePathFetch
# (src/shared/utils/basePathFetch.ts) so absolute `/api/*` and `/v1/*` hits work
# without a reverse-proxy rewrite. Rebuild after changing (Next basePath is build-time).
#
# Browser-visible mirror of OMNIROUTE_BASE_PATH, inlined at build time so the
# dashboard endpoint display can read it client-side. Set it to the same value
# as OMNIROUTE_BASE_PATH; when unset the hook falls back to OMNIROUTE_BASE_PATH.
# Used by: src/shared/hooks/useDisplayBaseUrl.ts
# NEXT_PUBLIC_OMNIROUTE_BASE_PATH=
#
# Optional: set the public origin *with* the same path so OAuth and display URLs
# stay consistent without relying on window.location.origin alone:
# NEXT_PUBLIC_BASE_URL=https://host/omniroute
#
# Client-side fallback port for display URLs when no origin is known (SSR/tests):
# read before PORT so a browser bundle built with a different public port still
# renders the right http://localhost:<port> links (src/shared/hooks/useDisplayBaseUrl.ts).
# NEXT_PUBLIC_PORT=20128
#
# Explicit path probed by the container health check. Unset, the probe derives it
# from OMNIROUTE_BASE_PATH; setting it opts back into the deep monitoring endpoint.
# Used by: scripts/dev/healthcheck.mjs
# OMNIROUTE_HEALTHCHECK_PATH=/api/monitoring/health
# Opt-in iframe embedding of the OmniRoute HTML pages (issue #10273). Off by default:
# every route ships `frame-ancestors 'none'` + `X-Frame-Options: DENY`, which is why the
# VS Code Simple Browser (used by the OmniCopilot extension's "Open Dashboard → editor"
# mode) renders a blank tab. Set this to `vscode` to switch the HTML pages — dashboard,
# login, docs, landing — to `frame-ancestors 'self' vscode-webview:` and drop
# X-Frame-Options for them (XFO cannot express a custom scheme). The API surface
# (/api, /v1, /v1beta, /a2a, /healthz and the root-level aliases) keeps the strict
# headers regardless. Only `vscode` is recognised; `1`/`true` do NOT enable it.
# Used by: next.config.mjs via scripts/build/dashboardEmbed.mjs — build-time, rebuild after changing.
# Docker: pass it as a build arg (`docker build --build-arg DASHBOARD_ALLOW_EMBED=vscode`);
# setting it on an already-built server or image does nothing.
# DASHBOARD_ALLOW_EMBED=vscode
# Split-port mode: serve Dashboard and API on separate ports for network isolation.
# Used by: src/lib/runtime/ports.ts — overrides PORT for each service.
# API_PORT=20129
# API_HOST=0.0.0.0
# DASHBOARD_PORT=20128
# Dedicated port for the self-service quota page (/quota/{provider}). Unset means no listener.
# The port relays only that page, its two API routes and its build assets to the main port.
# Every other path answers 404. GET and HEAD are relayed without a body.
# One JSON PATCH of the quota view is also relayed, with a body of at most 4096 bytes.
# A value that is not a port from 1 to 65535 opens nothing and logs a warning.
# So does a value equal to the dashboard port, the API port or the live WebSocket port.
# The port serves plain HTTP. Keep it on 127.0.0.1 and put a TLS reverse proxy in front of it.
# Used by: src/lib/quotaPanelBridge.ts, src/lib/apiBridgeServer.ts
# QUOTA_PANEL_PORT=20133
# QUOTA_PANEL_HOST=127.0.0.1
# Connection backpressure: cap concurrent in-flight chat connections (503 + Retry-After when full).
# Used by: src/sse/utils/backpressure.ts — disabled when unset/0.
# OMNI_MAX_CONCURRENT_CONNECTIONS=0
# Optional OmniRoute-to-OmniRoute peer chaining guard. Give every instance a
# unique ID and allowlist only the other OmniRoute base URLs it may call.
# Requests to allowlisted peers carry X-OmniRoute-Peer-Trace; repeated instances
# and exhausted hop budgets are rejected with HTTP 508 before provider routing.
# OMNIROUTE_INSTANCE_ID=gateway-a
# OMNIROUTE_PEER_URLS=http://gateway-b:20128/v1
# OMNIROUTE_PEER_MAX_HOPS=4
# Port for the real-time WebSocket live monitoring server.
# Used by: src/server/ws/liveServer.ts, src/app/api/v1/ws/route.ts
# Default: 20132
# LIVE_WS_PORT=20132
# Bind address for the live WebSocket server.
# Default: 127.0.0.1 (loopback only). Set to 0.0.0.0 to expose on LAN —
# remember to also configure LIVE_WS_ALLOWED_ORIGINS when doing so.
# LIVE_WS_HOST=127.0.0.1
# Comma-separated extra origins allowed to open a live WebSocket. The
# loopback dashboard origins are already permitted by default; use this
# var when fronting the server with a domain (e.g. https://omni.local).
# Not needed for the default same-origin socket (/live-ws through the main
# port): it is accepted when its Origin matches the Host the browser sent and
# it carries the dashboard session cookie or a `manage` API key.
# ⚠️ When using NEXT_PUBLIC_LIVE_WS_PUBLIC_URL or exposing the WS server
# beyond loopback, this MUST include the public origin(s) — otherwise
# the Origin allow-list check will reject all browser connections.
# Example: LIVE_WS_ALLOWED_ORIGINS=https://omni.local,https://dashboard.example.com,https://ws.my-ai.com
# LIVE_WS_ALLOWED_ORIGINS=https://omni.local,https://dashboard.example.com
# Comma-separated extra hostnames allowed to open a live WebSocket (LAN/Tailscale).
# Unlike LIVE_WS_ALLOWED_ORIGINS (which matches full origin URLs), this matches
# only the host portion — useful for wildcard-ish LAN/Tailscale setups.
# Used by: src/server/ws/liveServerAllowList.ts
# Example: LIVE_WS_ALLOWED_HOSTS=omni.local,tailscale-host,192.168.1.50
# LIVE_WS_ALLOWED_HOSTS=omni.local,tailscale-host,192.168.1.50
# Public URL for the live dashboard WebSocket (client-side, browser only).
# Unset, a page served from a host other than localhost / 127.0.0.1 / ::1
# connects to /live-ws on its own origin (wss://<host>/live-ws on https,
# ws:// on http): the production server relays that upgrade on its main HTTP
# port, so a reverse proxy only has to forward WebSocket upgrades on /live-ws.
# On loopback, and under `npm run dev` / `npm start` (no relay), the browser
# connects to ws://hostname:20132. Set this when the socket lives elsewhere
# (e.g. a separate ws.* host); it wins over that default.
# NEXT_PUBLIC_* is inlined at build time: on a prebuilt image use the runtime
# name LIVE_WS_PUBLIC_URL instead (echoed by /api/v1/ws?handshake=1; it wins
# when both are set).
# The path portion of this URL (e.g. ws://localhost:20132/live-ws -> /live-ws) is also used by the dev proxy
# (scripts/dev/standalone-server-ws.mjs) and the handshake response to route
# WebSocket upgrades. Default path: /live-ws.
# Used by: src/hooks/useLiveDashboard.ts, src/app/api/v1/ws/route.ts,
# scripts/dev/standalone-server-ws.mjs, and scripts/start-ws-server.mjs.
# Example: NEXT_PUBLIC_LIVE_WS_PUBLIC_URL=wss://ws.my-ai.com/live-ws
# NEXT_PUBLIC_LIVE_WS_PUBLIC_URL=ws://localhost:20132/live-ws
# LIVE_WS_PUBLIC_URL=wss://ws.my-ai.com/live-ws
# Enable the real-time dashboard WebSocket server.
# Used by: src/server/ws/liveServer.ts, scripts/start-ws-server.mjs
# Default: ON. Set to 0 or false to disable startup of the live WS server.
# Combine with LIVE_WS_HOST / LIVE_WS_ALLOWED_ORIGINS above when exposing
# beyond loopback.
# OMNIROUTE_ENABLE_LIVE_WS=1
# Per-(token,IP) relay rate limit, requests/minute. In-memory, per instance.
# 0 or negative disables the IP-dimension gate (per-token DB limit still applies).
# Default: 30
# Used by: src/app/api/v1/relay/chat/completions/route.ts
# RELAY_IP_PER_MINUTE=30
# Bundler selection for `npm run dev` and `npm run build`. Set to 0 to fall back to webpack.
# Default is 1 (Turbopack). PR #4092 had forced webpack because earlier
# Turbopack 16.2.x panicked on the OmniRoute module graph with "internal error:
# entered unreachable code: there must be a path to a root"
# (turbopack-core/module_graph/mod.rs:662). That panic no longer reproduces on
# the pinned Next 16.2.9 — verified across a broad cold-compile sweep (36
# dashboard routes + open-sse-heavy API routes incl. /api/v1/chat/completions,
# /api/v1/models, /api/mcp) and repeated HMR rebuilds: zero panics. Turbopack
# also keeps dev memory far lower on the edit→rebuild loop (HMR rebuild RSS stays
# ~flat vs webpack's monotonic growth), which mitigates the dev-server OOM on
# this 60+ route app. The production build (scripts/build/build-next-isolated.mjs)
# reads the same flag: Turbopack by default, 0 builds with webpack (`npm run
# build:contributor` sets it for you).
OMNIROUTE_USE_TURBOPACK=1
# Webpack production builds (OMNIROUTE_USE_TURBOPACK=0) skip webpack's
# persistent filesystem cache by default: writing it adds about 2.5 GB of peak
# build memory at a 6144 MB heap cap. Set to 1 to keep .build/next/cache/webpack
# for faster repeat builds on a machine with RAM to spare (Docker: pass it as
# --build-arg). Read by next.config.mjs.
# OMNIROUTE_WEBPACK_BUILD_CACHE=1
# Disable systemd sd_notify (Type=notify / WatchdogSec=) even when running
# under a systemd unit with NOTIFY_SOCKET set.
# Used by: scripts/dev/systemd-notify.mjs. Set to 1 to disable.
# OMNIROUTE_DISABLE_SD_NOTIFY=1
# Injected by systemd when running under a service unit (sd_notify protocol).
# Read by scripts/dev/systemd-notify.mjs — never set this yourself.
# NOTIFY_SOCKET=/run/systemd/notify
# Skip the SQLite integrity health check on startup (faster boot on large DBs).
# Used by: src/lib/db/core.ts, src/lib/db/healthCheck.ts. Set to 1 to skip.
# OMNIROUTE_SKIP_DB_HEALTHCHECK=1
# Interval (ms) for the background credential health check scheduler.
# Default: 3600000 (60 minutes). Minimum: 10000 (10 seconds).
# Used by: open-sse/config/constants.ts, src/lib/credentialHealth/scheduler.ts
# CREDENTIAL_HEALTH_CHECK_INTERVAL=3600000
# TTL (ms) for cached credential health status.
# Default: 300000 (5 minutes).
# Used by: open-sse/config/constants.ts, src/lib/credentialHealth/cache.ts
# CREDENTIAL_HEALTH_CACHE_TTL=300000
# Set to 1 or true to disable background periodic testing of provider connections.
# Default: false
# Used by: src/lib/credentialHealth/scheduler.ts
# OMNIROUTE_DISABLE_CREDENTIAL_HEALTH_CHECK=false
# DEEP_HEALTH_CHECK_ENABLED: set to 1 to let an authenticated caller append ?deep=1 to
# /api/monitoring/health and sample the completions surface (cached per TTL). Off by default;
# anonymous callers never trigger a probe.
# DEEP_HEALTH_CHECK_ENABLED=0
# Stall threshold (ms) for the boot event-loop recorder: a freeze longer than
# this logs one line at resume and bumps the counter/maximum on
# /api/monitoring/health. Set to 0 to disable; unreadable or negative falls
# back to 5000.
# Used by: src/lib/healthzLag.ts
# OMNIROUTE_EVENT_LOOP_STALL_THRESHOLD_MS=5000
# Set to "true" to emit `[ProxyFetch]` debug logs from the Vercel relay path
# in open-sse/utils/proxyFetch.ts. Off by default to avoid leaking routing
# hints in production logs.
# OMNIROUTE_PROXY_FETCH_DEBUG=true
# Absolute path of the local proxy core binary (a file named `sing-box` for `.json` targets,
# or `mihomo` for `.yaml`/`.yml` targets) used to check a
# generated core configuration before it replaces the adopted file. Unset = write
# `<path>.generated` beside the adopted file only. Host environment only: never stored in the
# database nor accepted through the management API, because the binary is executed.
# A binary that doesn't match the target's core writes beside the adopted file with a warning.
# Used by: src/lib/proxySubscription/coreConfig/sync.ts.
# OMNIROUTE_PROXY_CORE_BINARY_PATH=/usr/bin/sing-box
# OMNIROUTE_PROXY_CORE_BINARY_PATH=/usr/local/bin/mihomo
# How the local proxy core reloads after a verified config replacement.
# Either a JSON argument array run without a shell, e.g.
# ["systemctl-reload-sing-box"] is NOT valid (must be an absolute path array),
# or exactly `external` when an outside observer applies the file.
# Never stored in the database nor exposed via the API.
# Used by: src/lib/proxySubscription/coreConfig/reload.ts.
# OMNIROUTE_PROXY_CORE_RELOAD_COMMAND=["/usr/bin/systemctl","--user","reload","sing-box"]
# Set to "true" or "1" to include client/egress IPs and the account prefix in
# the verbose `[ProxyEgress]` process-log line (src/lib/proxyLogger.ts). Kept
# OFF by default so the process log does not leak IPs or the account prefix.
# PROXY_LOG_INCLUDE_IPS=true
# Set to any non-empty value to emit `[omniroute completion]` diagnostics from
# the CLI shell-completion cache paths (read/refresh/write) in
# bin/cli/commands/completion.mjs. Off by default — these caches fail silently
# so a missing/corrupt cache never breaks tab-completion.
# OMNIROUTE_DEBUG_COMPLETION=1
# Set to 1 to print the full stack trace when a CLI command fails, instead of the
# concise error message. CLI-only diagnostics; HTTP error responses never include stacks.
# Used by: bin/cli/utils/formatCliError.mjs
# OMNIROUTE_DEBUG_STACK=1
# Optional Gemini CLI home used by `omniroute setup-gemini`. `omniroute run
# gemini` always replaces it with a private temporary home for that child.
# Default: the current user's home. Used by: bin/cli/commands/setup-gemini.mjs
# GEMINI_CLI_HOME=/path/to/isolated-gemini-home
# Grace period in milliseconds after forwarding SIGINT/SIGTERM/SIGHUP to a CLI
# child before OmniRoute escalates termination. Default: 5000.
# Used by: bin/cli/commands/run.mjs, launch.mjs, launch-codex.mjs
# OMNIROUTE_CHILD_SIGNAL_TIMEOUT_MS=5000
# Hermetic CLI/test escape hatch. When set to 1, an explicit DATA_DIR does not
# fall through to the user's default ~/.omniroute/.env credential file.
# Default: unset. Used by: bin/omniroute.mjs
# OMNIROUTE_CLI_SKIP_DEFAULT_DATA_ENV=1
# Set to 1 (or true) to let `omniroute fcc-claude` send the API key to a non-loopback
# plain http:// base URL, e.g. a LAN server at http://192.168.x.y:20128. Unset, the
# command refuses because the key would travel in plaintext. Loopback HTTP and HTTPS
# never need it. Set it in the shell or the data-dir .env: a .env in the working
# directory cannot set it. Used by: bin/cli/commands/fcc-claude.mjs
# OMNIROUTE_ALLOW_INSECURE_REMOTE=1
# Set to 1 to print per-request timing diagnostics from the CLI quota commands
# to stderr (`[omniroute] GET <path> completed in Nms`).
# Used by: bin/cli/commands/quota.mjs
# OMNIROUTE_DEBUG=1
# Docker production port mappings (docker-compose.prod.yml only).
# These set the HOST-side published ports. Container ports use PORT/API_PORT.
# PROD_DASHBOARD_PORT=20130
# PROD_API_PORT=20131
# Runtime override used by Electron and wrapped environments.
# OMNIROUTE_PORT takes precedence over PORT when running inside wrappers.
# Used by: src/lib/runtime/ports.ts — preserves canonical port in Electron.
# OMNIROUTE_PORT=20128
# Hostname/bind address for the Next.js server.
# Used by: scripts/dev/run-next.mjs (HOST), Playwright runner (HOSTNAME).
# Default: 0.0.0.0 (HOST) / 127.0.0.1 (HOSTNAME inside tests).
# NOTE: Do NOT use `HOSTNAME` — it is a POSIX shell variable automatically set to
# the machine name by bash/zsh. The .env loader cannot override it (first-wins
# semantics). Use OMNIROUTE_SERVER_HOST instead for `omniroute serve`.
# See: https://github.com/cheaper-inference/OmniRoute/issues/6194
# HOST=0.0.0.0
# HOSTNAME=127.0.0.1
# OMNIROUTE_SERVER_HOST=0.0.0.0
# Environment mode — affects Next.js behavior, logging verbosity, and caching.
# Values: production | development | Default: production
NODE_ENV=production
# Container runtime — controls startup script behavior (permissions, advice).
# Values: docker | podman | Default: docker
# Set to "podman" for any Podman topology. The entrypoint cannot determine
# whether the engine is local or reached through Podman Machine, so it prints
# topology-neutral guidance and links contrib/podman/README.md.
CONTAINER_HOST=docker
# Container runtime override for skill sandboxing.
# Used by: src/lib/skills/sandbox.ts + src/lib/skills/containerProvider.ts
# Values: auto | docker | apple | wsl | orbstack | podman
# - auto: OS-aware auto-detect (apple/orbstack on macOS, wsl on Windows, podman on Linux)
# - apple: Apple Container (native OCI on macOS 26+)
# - wsl: WSL Container CLI (wslc.exe on Windows)
# - orbstack: OrbStack (high-perf Linux VM + docker shim on macOS)
# - podman: Podman (rootless, daemonless)
# - docker: Docker (default fallback)
# (defined under SKILLS & SANDBOXING section below)
# ═══════════════════════════════════════════════════════════════════════════════
# 4. SECURITY & AUTHENTICATION
# ═══════════════════════════════════════════════════════════════════════════════
# Salt for generating unique machine IDs (fingerprint diversification).
# Used by: src/lib/auth — combined with hardware identifiers for machine-id hash.
# Default: endpoint-proxy-salt | Change per-deployment for isolation.
MACHINE_ID_SALT=endpoint-proxy-salt
# Salt for deriving CLI machine-ID auth tokens (HMAC-SHA256).
# Used by: src/lib/machineToken.ts — rotates the local CLI auth token without
# touching code. Set to a new value to invalidate existing CLI tokens.
# Default: omniroute-cli-auth-v1
# OMNIROUTE_CLI_SALT=omniroute-cli-auth-v1
# Set true when running behind HTTPS (reverse proxy with TLS termination).
# Used by: src/lib/auth — sets the Secure flag on session cookies.
# Default: false | MUST be true in any non-localhost deployment.
AUTH_COOKIE_SECURE=false
# Require an API key for all /v1/* proxy endpoints.
# Used by: API middleware — rejects unauthenticated requests to the proxy API.
# Default: false | Set true for multi-user/public deployments.
# On: true, 1 or yes (case and surrounding spaces ignored). Any other value is off.
# Leaving this false is only safe when the app is reachable on loopback only
# (see APP_BIND_HOST above) or sits behind a reverse proxy doing its own auth.
REQUIRE_API_KEY=false
# Allow revealing full API key values in the Dashboard UI.
# Used by: src/shared/constants/featureFlagDefinitions.ts — controls show/hide of key values.
# Also configurable from Dashboard > Settings > Feature Flags.
# Default: false | Security risk if enabled on shared instances.
ALLOW_API_KEY_REVEAL=false
# Shared secret for the internal Codex Responses WebSocket bridge.
# Used by: src/app/api/internal/codex-responses-ws/route.ts — authenticates
# bridge requests between the Electron/browser WS relay and OmniRoute.
# ⚠️ REQUIRED for production — if unset, all WS bridge requests are rejected.
# Generate: openssl rand -base64 32
# OMNIROUTE_WS_BRIDGE_SECRET=
# Per-process secret that proves the trusted peer-IP stamp came from OmniRoute's
# own HTTP server (scripts/dev/peer-stamp.mjs). The custom server stamps the real
# TCP peer IP as `<token>|<ip>`; the authz middleware trusts the locality only
# when the token matches. Used by: src/server/authz/policies/management.ts.
# Auto-generated per boot — leave UNSET in normal use. Only set it to pin a fixed
# value across processes (e.g. a multi-process setup that must share the stamp).
# OMNIROUTE_PEER_STAMP_TOKEN=
# Comma-separated API key IDs that skip request logging (GDPR/compliance).
# Used by: src/lib/compliance/index.ts — suppresses logs for specific keys.
# NO_LOG_API_KEY_IDS=key_abc123,key_def456
# Fallback per-day request budget applied to API keys whose `rate_limits`
# column is null. Default (unset/empty) is unlimited (no implicit caps).
# Malformed values preserve the legacy 1000/day, 5000/week, 20000/month windows.
# Set explicitly to "0" to opt out entirely (unlimited fallback). Any
# positive integer N enables N/day, 5N/week, 20N/month.
# Used by: src/shared/utils/apiKeyPolicy.ts — checkRateLimit() fallback.
# DEFAULT_RATE_LIMIT_PER_DAY=1000
# Maximum request body size in bytes (rejects larger payloads). A saved maxBodySizeMb wins.
# Chat Completions and Responses keep a 50 MB default until a limit is saved.
# Used by: src/shared/middleware/bodySizeGuard.ts — prevents oversized uploads.
# Default: 10485760 (10 MB)
# MAX_BODY_SIZE_BYTES=10485760
# Atomic admission for POST /v1/chat/completions (#7846). Large request bodies
# amplify into multiple transient representations during parsing, compression, and
# provider dispatch. Heavyweight capacity is reserved before parsing; excess work
# receives 503 + Retry-After instead of overlapping until the process OOMs.
# Used by: src/shared/middleware/chatBodyAdmission.ts
# Actual bodies at or above this size take the heavyweight lease (BYTE path,
# including POST /v1/responses) and use the same #10437 healthy-headroom escape
# as structure-heavy. Default 262144 (256 KB).
# OMNIROUTE_CHAT_LARGE_BODY_BYTES=262144
# Actual-byte hard cap enforced during bounded ingestion. Default 52428800 (50 MB).
# A saved maxBodySizeMb replaces the default; when set here, this also caps that saved value.
# OMNIROUTE_CHAT_HARD_MAX_BODY_BYTES=52428800
# Legacy request-COUNT cap (#503-fanout). Now binds only when explicitly set here —
# left unset, heavyweight admission is gated by OMNIROUTE_CHAT_MAX_INFLIGHT_BYTES below
# instead (an auto-derived byte budget), fixing coding-agent fan-out (multiple
# subagents/CLIs) collapsing to an effective concurrency of ~1 and 503ing.
# Two overlapping ~750k-token /v1/responses abort ~12 Gi heaps (#7849) — a
# memory-budget warning, not a hard product max of 2. A healthy heap may admit
# more via HEALTHY_HEADROOM. Tens of long SSE clients (40-50) is heap +
# OMNIROUTE_CHAT_MAX_INFLIGHT_BYTES / #10110. Multiply heaps with N independent
# DATA_DIRs (#11024); never replicas>1 on one SQLite.
# OMNIROUTE_CHAT_MAX_HEAVY_IN_FLIGHT=1
# Override for the auto-derived ingest byte budget (#503-fanout). Default: 25% of the
# process's effective memory ceiling (V8 heap limit, or the tighter cgroup/container
# limit) divided by an 8x transient-amplification factor, clamped between 8 MiB and
# 2 GiB; explicit overrides are clamped to the same safe range. Read
# chatAdmission.maxInflightBytes/budgetSource at /api/monitoring/health before overriding.
# OMNIROUTE_CHAT_MAX_INFLIGHT_BYTES=134217728
# Heap-pressure shed ratio (heapUsed/heap_size_limit) for BYTE and STRUCTURE
# heavyweight admission (#10183, #10268, #10437): a concurrent heavyweight request
# past OMNIROUTE_CHAT_MAX_HEAVY_IN_FLIGHT is only shed with a retryable 503 when the
# heap is ALSO under this much pressure — on a healthy heap it is admitted via
# healthy-headroom instead. Range (0, 1]. Default 0.75.
# OMNIROUTE_CHAT_ADMISSION_HEAP_SHED_RATIO=0.75
# Bounded extra capacity for the healthy-heap fast path above OMNIROUTE_CHAT_MAX_HEAVY_IN_FLIGHT
# (#10437, BYTE + STRUCTURE, including bodies >= OMNIROUTE_CHAT_LARGE_BODY_BYTES):
# once this many concurrent leases are active through the healthy-heap bypass,
# further busy requests fall through to the same bounded-wait/shed path used under real heap
# pressure. 0 disables the bypass entirely. Default 1.
# OMNIROUTE_CHAT_ADMISSION_HEALTHY_HEADROOM=1
# Message count that classifies an otherwise small body as heavyweight. Default 200.
# OMNIROUTE_CHAT_HEAVY_MESSAGE_COUNT=200
# Tool count that classifies an otherwise small body as heavyweight. Default 64.
# OMNIROUTE_CHAT_HEAVY_TOOL_COUNT=64
# Conservative string-size token estimate that classifies a request as heavyweight. Default 32000.
# OMNIROUTE_CHAT_HEAVY_ESTIMATED_TOKENS=32000
# Optional opt-in hard message-count cap; excess receives compact-required 413 before
# compression can run. Unset/0 (the default) means no history cap: heap growth is bounded
# by OMNIROUTE_CHAT_MAX_HEAVY_IN_FLIGHT and the heap-pressure shed instead. Set a positive
# value only on memory-constrained deployments that need a hard ceiling.
# OMNIROUTE_CHAT_HARD_MAX_MESSAGES=0
# Skip OmniRoute's local context-window and max-input-token check for direct
# single-model requests. Default: false (dangerous opt-in).
# The upstream provider still enforces its real limits, so enabling this can
# replace an early OmniRoute 400 with an upstream context-length error.
# Prompt compression and the model's own output-token cap remain active.
# Also configurable from Dashboard > Settings > Feature Flags; no restart is
# required. Used by: src/shared/utils/featureFlags.ts and open-sse/handlers/chatCore.ts.
# DISABLE_CONTEXT_WINDOW_CHECKS=false
# How long a heavy request waits for heavyweight capacity before a retryable 503.
# A short bounded wait serializes agent bursts instead of an instant 503; 0 = instant.
# Defaults to RATE_LIMIT_MAX_WAIT_MS (see that var elsewhere in this file for its
# current value), the same budget the resilience layer gives the upstream turn that
# holds the slot — a shorter wait cannot bridge it.
# OMNIROUTE_CHAT_ADMISSION_QUEUE_MS=20000 # example override; default tracks RATE_LIMIT_MAX_WAIT_MS
# Queued-bytes budget for the admission wait: bounds total buffered body bytes parked
# per lane so the wait cannot amplify the heap (#4380). Over-budget waits 503 immediately.
# Default 4194304 (4 MB).
# OMNIROUTE_CHAT_ADMISSION_MAX_QUEUED_BYTES=4194304
# Per-connection virtual admission lanes (#9654): idle-lane eviction TTL. Default 60000 (60s).
# OMNIROUTE_CHAT_VIRTUAL_TTL_MS=60000
# Per-connection virtual admission lanes (#9654): max concurrent sessions (lanes). Default 64.
# OMNIROUTE_CHAT_VIRTUAL_MAX_SESSIONS=64
# Adaptive runtime virtual admission lanes (#9654): master switch for the per-tenant
# adaptive gate (system 2, open-sse/services/admission). NOTE: the TTL/MAX_SESSIONS
# vars above tune the byte-level per-connection lanes (system 1); this switch enables
# the adaptive runtime lanes. Dashboard feature flag of the same name; env wins over
# the dashboard override; restart required. Default: off.
# OMNIROUTE_CHAT_VIRTUAL_LANES=1
# Hard cap (bytes) for a non-streaming upstream response buffered fully into memory
# (#5152). Past this the upstream reader is cancelled and the request fails fast
# instead of growing an unbounded string until the V8 heap is exhausted.
# Used by: open-sse/handlers/chatCore/nonStreamingResponseBody.ts
# Default: 67108864 (64 MB)
# OMNIROUTE_FORWARDING_HEADER_BUDGET_BYTES=768
# OMNIROUTE_MAX_NONSTREAMING_RESPONSE_BYTES=67108864
# Per-stream cap (bytes) on the text streaming translators keep in memory across
# SSE lines (tool-call arguments, reasoning text, thinking signatures). Past it the
# stream ends with one invalid_sse_payload error frame. 0 disables the cap.
# Used by: open-sse/utils/streamRetainedBudget.ts
# Default: 67108864 (64 MB)
# OMNIROUTE_MAX_STREAM_RETAINED_BYTES=67108864
# Most quota-recovery tickets (pending, running or awaiting confirmation) one
# API key may hold. At the limit, new turns get the original quota error.
# Used by: src/lib/quota/quotaSessionRecovery.ts
# Default: 64
# OMNIROUTE_QUOTA_RECOVERY_MAX_PER_KEY=64
# CORS configuration — controls which cross-origin browser clients can call the API.
# Used by: src/server/cors/origins.ts — sets Access-Control-Allow-Origin.
# Same-origin dashboard requests behind a reverse proxy do not need CORS; they
# use session-bound CSRF protection. No wildcard is sent unless CORS_ALLOW_ALL=true.
# CORS_ALLOWED_ORIGINS=https://your-frontend.example.com
# CORS_ORIGIN=https://your-frontend.example.com # legacy single-origin alias
# CORS_ALLOW_ALL=false
# Turns off the outbound URL guard's host checks, cloud-metadata block included, on the
# provider paths that follow the guard mode: URL validation, model discovery, provider-node
# base URLs (including remote rerank nodes), and the proxy-fallback test, among other
# provider-adjacent outbound paths such as remote image/media fetch. It also allows
# private webhook targets, except cloud-metadata/link-local endpoints, which stay
# blocked even with this flag on. Local providers work with the defaults:
# OMNIROUTE_ALLOW_LOCAL_PROVIDER_URLS below (default true) already allows local and LAN
# URLs. A value saved from the dashboard toggle takes precedence over this variable.
# Details: docs/reference/ENVIRONMENT.md.
# Used by: src/shared/network/outboundUrlGuardPolicy.ts
# Default: false
# OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS=true
# Allow provider URLs on local and private addresses (127.0.0.1, localhost, LAN).
# Default: true (OmniRoute is local-first); the guard then blocks cloud-metadata
# endpoints — all of 169.254.0.0/16 plus the known metadata hostnames. Set false to
# block private and loopback hosts too (public-only mode). The guard checks the
# hostname or IP literal as written first; in public-only mode the safe-fetch
# wrapper (validation, model discovery) also resolves the name and refuses
# private answers.
# Built-in local providers skip these checks for key validation and chat.
# A value saved from the dashboard toggle takes precedence over this variable.
# Used by: src/shared/network/outboundUrlGuardPolicy.ts
# OMNIROUTE_ALLOW_LOCAL_PROVIDER_URLS=false
# Treat 198.18.0.0/15 (the RFC 2544 benchmarking range) as private in the strict public-only
# checks (caller-supplied image/media URLs, public-only DNS and connect-time guards). Off by
# default because fake-IP proxies (Clash, Mihomo, Surge in TUN mode) answer every name with an
# address in that range; turn it on only when no such proxy is in use and the range holds
# internal services.
# Used by: src/shared/network/privateHost.ts
# Default: false
# OMNIROUTE_BLOCK_BENCHMARK_RANGE=true
# Legacy alias; its dashboard toggle (a DB override) is read before this environment value.
# "false", "0", "no", or "off" in either turns the host checks off the way
# OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS=true does, even when that flag's dashboard toggle
# is saved off. Other values leave the guard to the two flags above.
# Used by: src/shared/network/outboundUrlGuardPolicy.ts
# OUTBOUND_SSRF_GUARD_ENABLED=true
# ── Self-hosted unified OpenAI-compatible entry (RIC-738, D4) ────────────────────
# When set, /v1/chat/completions diverts to the self-hosted provider adapters
# (open-sse/services/selfHostedEntry.ts) instead of the cloud pipeline. YAML inline
# (example) — or point OMNIROUTE_SELF_HOSTED_PROVIDERS_FILE at a YAML file. Secrets
# are runtime-only, never logged. While ANY of these is set, the entry is active;
# config present but unparseable returns a 500 (never silently falls through).
# OMNIROUTE_SELF_HOSTED_PROVIDERS='
# providers:
# - id: local
# kind: openai
# baseUrl: http://127.0.0.1:11434/v1
# model: llama3
# - id: claude
# kind: anthropic
# baseUrl: http://127.0.0.1:8080
# model: claude-sonnet
# '
# OMNIROUTE_SELF_HOSTED_PROVIDERS_FILE=/etc/omniroute/providers.yaml
# Optional shared API key for the unified entry (D5 reserved). When set, require
# `Authorization: Bearer <key>`; empty = open loopback/trusted-network route.
# OMNIROUTE_SELF_HOSTED_API_KEY=
# ── Deterministic routing strategies (M2 / RIC-740, D3 可审计路由) ─────────────
# Optional `strategy:` block — either inline in the providers document above, or a
# standalone document via these env vars. One rule per line; every decision is
# explainable via the `x-omniroute-route-decision` response header. No ML/predict.
# Malformed strategy config returns a 500 (never silently becomes a no-op).
# Example (inline, same shape as `strategy:` inside the providers YAML):
# OMNIROUTE_SELF_HOSTED_STRATEGY='
# blacklist: []
# whitelist: [cheap, fast, premium]
# costPriority: true
# latencyAware:
# enabled: true
# cooldown:
# consecutiveFailures: 2
# cooldownMs: 30000
# fallbackChain: [cheap, fast, premium]
# '
# OMNIROUTE_SELF_HOSTED_STRATEGY_FILE=/etc/omniroute/strategy.yaml
# See docs/routing/DETERMINISTIC_ROUTING.md for the full strategy surface.
# ═══════════════════════════════════════════════════════════════════════════════
# 5. INPUT SANITIZATION & PII PROTECTION (FASE-01)
# ═══════════════════════════════════════════════════════════════════════════════
# Multi-layer defense: request-side injection guard + response-side PII sanitizer.
# ── Request-Side: Prompt Injection Guard ──
# Scans incoming messages for prompt injection patterns before routing.
# Used by: src/middleware/promptInjectionGuard.ts
# Default ON when unset. Set to false/0/no/off to disable. Truthy: true/1/yes/on.
# INPUT_SANITIZER_ENABLED=false
# INPUT_SANITIZER_MODE=warn # warn = log only | block = reject request | redact = legacy (does NOT strip injection; use PII_REDACTION_ENABLED for request PII)
# INPUT_SANITIZER_BLOCK_THRESHOLD=high # high (default) | medium | low — severities at/above this are blocked in block mode
# Legacy aliases for INPUT_SANITIZER_MODE / INPUT_SANITIZER_BLOCK_THRESHOLD (same effect).
# INJECTION_GUARD_MODE=warn
# INJECTION_GUARD_BLOCK_THRESHOLD=high
# PII detection in incoming requests (emails, phone numbers, SSNs, etc.).
# Used by: src/middleware/promptInjectionGuard.ts — extends injection guard.
# PII_REDACTION_ENABLED=false
# Reversible PII vault (needs PII_REDACTION_ENABLED=true). Request PII becomes per-request
# surrogate tokens such as <<PII_EMAIL_QWERTYUI_1>> instead of [EMAIL_REDACTED]; the chat
# handler restores the original values in 2xx responses (SSE and JSON). Error bodies keep the
# tokens. A DB override on the dashboard toggle wins over this value.
# Used by: src/lib/pii/requestTokenVaultScope.ts.
# PII_REVERSIBLE_VAULT_ENABLED=false
# Redacts well-known API-key / secret-token patterns (OpenAI, Anthropic, GitHub,
# Slack, etc.) from request/response payloads before they reach providers/clients.
# Opt-in; mirrors PII_REDACTION_ENABLED. Used by: src/lib/guardrails/credentialMasker.ts.
# CREDENTIAL_REDACTION_ENABLED=false
# Minimum streaming window size for PII detection (bytes). Default: 200.
# Used by: src/lib/streamingPiiTransform.ts.
# PII_WINDOW_SIZE=200
# Test bypass: allow setting PII_WINDOW_SIZE below minimum. Default: false.
# Used by: src/lib/streamingPiiTransform.ts.
# PII_TEST_BYPASS_MIN_WINDOW=false
# ── Request-Side: Agent Guard ──
# monitor = log requests to the claude/anthropic providers whose client is not an
# official agent (Claude Code or an official Anthropic SDK). monitor reads the provider
# from the model string: only model ids with the provider prefix (cc/, claude/,
# anthropic/ or a quota-share id) are observed, not bare model ids or combos.
# block = refuse known third-party agents on those providers (HTTP 403), decided on
# the provider the request resolved to. Client headers can be forged: this deters
# unmodified third-party agents, it is not access control.
# AGENT_GUARD_STRICT=true also refuses clients that cannot be identified (block only).
# A DB override on the dashboard toggle wins over these values.
# Used by: src/lib/guardrails/agentGuard/settings.ts
# AGENT_GUARD_MODE=off
# AGENT_GUARD_STRICT=false
# ── Response-Side: PII Sanitizer ──
# Scans LLM responses for leaked PII before returning to the client.
# Used by: src/lib/piiSanitizer.ts
# PII_RESPONSE_SANITIZATION=false
# PII_RESPONSE_SANITIZATION_MODE=redact # redact = mask PII | warn = log only | block = drop response
# ── VS Code Tokenized-Route Context Sanitizer ──
# Strips implicit active-editor context (editorContext/activeEditor/currentFile/
# selection/openTabs…) from requests on the /v1/vscode/[token]/* routes before
# forwarding upstream, and redacts the content of explicitly-attached sensitive
# files (.env, private keys, kubeconfig, credentials/secrets). Explicit
# attachments otherwise pass through. Secure-by-default: ON unless set to 0.
# Used by: src/app/api/v1/vscode/contextSanitizer.ts
# OMNIROUTE_VSCODE_SANITIZE_CONTEXT=1 # set to 0 to disable
# ═══════════════════════════════════════════════════════════════════════════════
# 6. TOOL & ROUTING POLICIES
# ═══════════════════════════════════════════════════════════════════════════════
# Tool policy mode — controls which tools LLMs can invoke via function calling.
# Used by: src/lib/toolPolicy.ts — enforces allowlist/denylist on tool_choice.
# Values: allowlist | denylist | disabled | Default: disabled
# TOOL_POLICY_MODE=disabled
# Payload manipulation rules JSON file.
# Used by: open-sse/services/payloadRules.ts — injects/removes upstream payload fields per model/protocol.
# Default: ./config/payloadRules.json
# OMNIROUTE_PAYLOAD_RULES_PATH=./config/payloadRules.json
# Reload interval for payloadRules.json mtime checks in milliseconds.
# Used by: open-sse/services/payloadRules.ts — keeps file-based rules hot-reloadable without restart.
# Default: 5000 | Minimum: 1000
# OMNIROUTE_PAYLOAD_RULES_RELOAD_MS=5000
# Prefer Claude Code OAuth for unprefixed Claude-family model IDs such as
# claude-sonnet-4-6 or newly released IDs like claude-fable-5.
# Used by: open-sse/services/model.ts. Explicit provider prefixes still win.
# Default: false
# OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS=false
# Set to false to stop OmniRoute adding the redact-thinking-2026-02-12 Anthropic beta
# on its own (thinking text is then returned instead of empty signature-only blocks).
# Requests with thinking.display "summarized" already skip it; client-negotiated or
# CC-compatible requestDefaults.redactThinking opt-ins keep it. Claude OAuth requests keep
# the beta (Claude Code OAuth fingerprint) unless the default-off feature flag
# CLAUDE_OAUTH_SUMMARIZED_THINKING_UNREDACTED is enabled.
# Used by: open-sse/executors/base/redactThinkingBeta.ts
# Default: true
# OMNIROUTE_REDACT_THINKING=true
# Feature flag (also settable from the dashboard Feature Flags page): let Claude OAuth
# requests that ask for thinking.display "summarized" drop the redact-thinking beta.
# Off by default — the beta is part of the Claude Code OAuth wire fingerprint.
# Used by: open-sse/executors/base/redactThinkingBeta.ts
# Default: false
# CLAUDE_OAUTH_SUMMARIZED_THINKING_UNREDACTED=false
# Legacy resolveBareModelToConnectionDefault behaviour (#4825): replace ANY bare
# model name (not only "auto"/empty) with the selected connection's defaultModel.
# Off by default: a concrete bare name such as claude-haiku-4-5 is kept.
# Used by: open-sse/services/model.ts.
# Default: false
# BARE_MODEL_DEFAULT_OVERRIDE_LEGACY=false
# Per-model concurrency cap for round-robin combos (#9100).
# Used by: open-sse/services/comboConfig.ts — the round-robin combo semaphore
# was hard-capped at 3 concurrent requests per model with no override, which
# serialized higher-concurrency traffic behind that cap.
# Validated to >= 1, clamped to <= 32. | Default: 3
# COMBO_CONCURRENCY_PER_MODEL=3
# Opt-in sub-budget for stream-readiness deadline failures in a combo run.
# A stalled upstream fails the readiness window on EVERY target while the
# combo rotates (each rotation re-dispatches the full body after tens of
# seconds to minutes of waiting), multiplying user latency and gateway memory
# before the global-attempts cap — calibrated for fast failures — kicks in.
# Unset/0 (default) = disabled, no behavior change. A positive integer
# terminates the combo with a clean 504 once that many readiness-deadline
# failures accumulated (504 with error.code STREAM_READINESS_TIMEOUT; the
# target that exhausts the budget is still locked out / cooled down).
# Used by: open-sse/services/combo/comboPredicates.ts + executeTargetAttempt.ts
# OMNIROUTE_COMBO_MAX_DEADLINE_FAILURES=3
# Agentic-stall combo failover (opt-in, default OFF).
# Used by: open-sse/services/combo/agenticStall.ts + agenticStallFailover.ts — a combo
# member answering a tool-result turn with "finish: stop + narration + zero tool calls"
# fails over to the next target; if none does better, the stalled answer is returned.
# Streamed turns are held back from the client until the verdict is settled.
# Set to 1 (or true) to enable. | Default: false
# OMNIROUTE_AGENTIC_STALL_FAILOVER=false
# Disable conversation-history tracking (#13150).
# Used by: open-sse/services/conversationTracker.ts. resolveConversationId()
# returns an untracked result before it reads SQLite or parses message history,
# and the switch also covers client-supplied session IDs. Routing sessions are
# unaffected and existing records are not deleted. Use it when the dashboard's
# conversation view is unused and the turn table has grown large.
# Set to 1 to disable. | Default: unset (tracking enabled)
# OMNIROUTE_DISABLE_CONVERSATION_TRACKING=1
# Unpriced successful usage in per-API-key USD limits and shared Team budgets. Leave unset to use the
# upstream boolean opt-out below, otherwise the default fails closed.
# An explicit enum (DB override before env) takes precedence over the boolean.
# Values: fail_closed | count_as_zero. Lookup failures always fail closed.
# Used by: src/shared/utils/featureFlags.ts (enforcement and admin report).
# UNPRICED_USAGE_BUDGET_POLICY=fail_closed
# USAGE_LIMIT_IGNORE_UNPRICED=false
# Nadir API key for the opt-in `nadir` auto-combo router strategy.
# Used by: open-sse/services/autoCombo/nadirStrategy.ts — fallback for the combo's
# config.nadir.apiKey. Only read when a combo opts in with "routerStrategy": "nadir".
# Optional: keyless calls land on Nadir's anonymous tier, which is rate-limited per IP
# and so is not usable behind a shared gateway.
# Sensitive; prefer the per-combo config.nadir.apiKey when combos use different accounts.
# OMNIROUTE_NADIR_API_KEY=
# Base origin of the Nadir decision API.
# Used by: open-sse/services/autoCombo/nadirStrategy.ts — fallback for the combo's
# config.nadir.baseUrl. Only needed for a self-hosted Nadir, which keeps prompt heads
# inside your own network. A trailing /v1 is tolerated and stripped.
# Default: https://api.getnadir.com
# OMNIROUTE_NADIR_BASE_URL=https://api.getnadir.com
# Opt-in for the `decision` auto-combo router strategy (feature flag; a dashboard DB
# override wins). While off, decision combos read no credential, make no call and route
# with the rules strategy.
# Used by: open-sse/services/autoCombo/decisionStrategy.ts
# Default: false
# COMBO_DECISION_ROUTER_ENABLED=false
# Key for the `decision` router's network deciders (systemone, http), used when the
# combo's config.decision.connectionId is unset (and, for systemone, no typesafe
# connection is in scope). A combo never stores a key. Sensitive.
# Used by: open-sse/services/decision/credentials.ts
# OMNIROUTE_DECISION_API_KEY=
# Weekly window for per-API-key USD usage limits.
# Used by: src/lib/usage/apiKeyUsageLimits.ts (request enforcement, key usage-limit
# status, @@om-usage). Values: provider | calendar | Default: provider
# provider: the week ends at the earliest weekly reset among the upstream
# connections the key can reach (rolling 7 days when none is known).
# calendar: the local week, Monday 00:00 to the next Monday 00:00, the same for
# every key. Recommended when one pool of upstream accounts is shared
# by many individually budgeted keys.
# OMNIROUTE_API_KEY_WEEKLY_WINDOW=calendar
# IANA timezone for the calendar weekly window (e.g. Asia/Shanghai, UTC).
# Used by: src/lib/usage/apiKeyUsageLimits.ts. Unset or invalid: the timezone of
# the OmniRoute process (the TZ of the host or container). Ignored in provider mode.
# OMNIROUTE_API_KEY_WEEKLY_WINDOW_TIMEZONE=Asia/Shanghai
# Default maximum number of tools allowed in a request (OpenAI default 128).
# Used by: open-sse/config/constants.ts (MAX_TOOLS_LIMIT) — caps the tool list
# sent upstream when a provider has no known/proactive limit of its own; a
# provider with a known limit (e.g. grok-cli 200, nvidia 1536) still applies its
# own cap. Positive integers only; unset or invalid values keep 128.
# OMNIROUTE_MAX_TOOLS_LIMIT=128
# Responses -> Chat translation re-sends tool-output images (function_call_output,
# custom_tool_call_output, role "tool") as user image parts. Only the newest images within
# both budgets are kept; each older one becomes a text placeholder with its tool_call_id,
# and the cap logs one warning per request.
# Used by: open-sse/translator/request/openai-responses.ts (selectDroppedToolOutputImages).
# Positive integers only; unset or invalid values keep the defaults.
# OMNIROUTE_TOOL_OUTPUT_IMAGE_MAX_COUNT=16
# OMNIROUTE_TOOL_OUTPUT_IMAGE_MAX_BYTES=20971520
# Inconsistent Responses tool history (an output with no call, a call with no output, a missing,
# overlong or invalid call_id, malformed historical arguments). Off: OmniRoute repairs it and
# dispatches (#15216). On: the request gets a 400 before dispatch instead.
# Used by: open-sse/translator/helpers/responsesToolHistory.ts (isStrictResponsesToolHistoryEnabled).
# Accepts true or 1; anything else keeps the default.
# OMNIROUTE_RESPONSES_STRICT_TOOL_HISTORY=false
# SYNTX.ai prompt-emulated tool calling. Unset = on: SYNTX chat injects the local
# tool catalog into the prompt and parses <tool_call> blocks back into OpenAI
# tool_calls. Set to 0/false/off to skip the local-tool catalog injection.
# Used by: open-sse/executors/syntxChat.ts (isSyntxPromptToolEmulationEnabled).
# OMNIROUTE_PROMPT_EMULATE_TOOLS=1
# ═══════════════════════════════════════════════════════════════════════════════
# 7. URLS & CLOUD SYNC
# ═══════════════════════════════════════════════════════════════════════════════
# URLs used for internal sync jobs, OAuth callbacks, and cloud relay.
# Internal base URL — used by server-side sync jobs to call /api/sync/cloud.