Compare commits

..

1 Commits
main ... v1.4.1

Author SHA1 Message Date
diegosouzapw
4ffe16877d chore(release): v1.4.1 — endpoint page cleanup, deploy workflow 2026-02-23 19:00:10 -03:00
27835 changed files with 73576 additions and 9054542 deletions

View File

@@ -1,201 +0,0 @@
# codebase-memory-mcp ignore list
#
# Padrão gitignore-style. Linhas começando com `#` são comentários.
# Barra final (`/`) = só diretório. Sem barra = casa arquivo OU diretório.
#
# O CBM também lê `.gitignore` automaticamente — esta lista deixa explícito o que
# os hooks do CBM vão pular. Se uma regra entrar em conflito entre os dois arquivos,
# vale a união. Editar este arquivo é mais barato do que confiar na herança implícita.
#
# Última reconciliação: 2026-07-31, status `ready` (513k nodes / 689k edges),
# `auto_index_limit=50000`, total indexável medido ≈11.546 arquivos (folga 4,3×).
#
# Fontes cruzadas:
# - `codebase-memory-mcp cli index_status --project home-diegosouzapw-dev-proxys-OmniRoute`
# → `not_indexed.dirs` (27) + `not_indexed.files` (336), todos `BY DESIGN`.
# - `.gitignore` deste repo (5.691 B) — fonte canônica secundária.
#
# Como auditar mudanças: depois de editar este arquivo, rodar `index_repository`
# (ou esperar `auto_watch` re-indexar) e re-checar `cli index_status` → comparar
# contagens em `not_indexed.dirs_count` e `not_indexed.files_count`.
# ─────────────────────────────────────────────────────────────────────────────
# 1. Diretorios de runtime / pacote — nao sao codigo-fonte
# ─────────────────────────────────────────────────────────────────────────────
node_modules/
node_modules
# Builds e artefatos reproduziveis (Layer 1 Next.js / Electron)
.build/
dist/
.next/
out/
# Electron especifico
electron/dist-electron/
electron/node_modules/
icon.iconset/
# Workspaces internos que tem proprio node_modules
@omniroute/opencode-plugin/dist/
@omniroute/opencode-plugin/node_modules/
@omniroute/opencode-provider/dist/
@omniroute/opencode-provider/node_modules/
# Recursos nativos compilados (C/JNI/wasm)
src/mitm/tproxy/native/build/
# Artefatos locais do Stryker / Playwright / coverage
.stryker-tmp/
reports/mutation/
stryker-output-*.json
.playwright-mcp/
test-results/
playwright-report/
blob-report/
# Analise / linters / caches
.analysis/
.sisyphus/
.plans/
.gitnexus
.worktrees
.codegraph/
# Quality artifacts (gerados por npm run lint --cache etc)
.eslintcache
.eslintcache-complexity
# Claude Code local state
.claude/scheduled_tasks.lock
.claude/scheduled_tasks/
.claude/sessions/
.claude/state.json
.claude/settings.local.json
# Serena / Antigravity / outras tools locais
.serena/
.antigravitycli/
.gemini/
.config/
# ─────────────────────────────────────────────────────────────────────────────
# 2. Diretorios com prefixo `_` — locais / privados (regra global do .gitignore)
# ─────────────────────────────────────────────────────────────────────────────
_*/
_artifacts/
_cache/
_mono_repo/
_references/
_tasks/
# ─────────────────────────────────────────────────────────────────────────────
# 3. Diretorios de tooling IA (state local, nao codigo)
# ─────────────────────────────────────────────────────────────────────────────
.agents/
.claude/
.vscode/
.idea/
.junie/
.omc/
.data/
.data-dev/
.local-data/
.logs/
.artifacts/
.source/
.superpowers/
.claude-flow/
.omnivscodeagent/
omnirouteCloud/
omnirouteSite/
.omniroute/
.stent/
# Subpaths especificos do Claude Code que nao estao em .claude/ (criados sob repo)
.claude/worktrees/
# ─────────────────────────────────────────────────────────────────────────────
# 4. Diretorios de dados / runtime locais (storage, env, secrets, scratch)
# ─────────────────────────────────────────────────────────────────────────────
data/
# NOTA: src/lib/env/, src/app/api/{cloud,sync/cloud,system/env,agent-skills/coverage}/
# foram removidos daqui (2026-08-05). Os nomes sugerem dados/segredos locais, mas os
# 8 arquivos sao route handlers e modulos rastreados no git — escondia-los do grafo
# criava pontos cegos em buscas e em analise de impacto.
tests/golden-set/data/
# Logs e saida de teste
logs/*
test_output.log
home-diegosouzapw-dev-automacoes-*.txt
# ─────────────────────────────────────────────────────────────────────────────
# 5. Diretorios do monorepo por subprojeto (nao fazem parte do app principal)
# ─────────────────────────────────────────────────────────────────────────────
security-analysis/
vscode-extension/
obsidian-plugin/node_modules/
# ─────────────────────────────────────────────────────────────────────────────
# 6. Diretorios de documentacao interna / workflow
# ─────────────────────────────────────────────────────────────────────────────
docs/superpowers/
# Docs traduzidas: 1.215 arquivos / 94 MB (inclui 20+ copias do CHANGELOG).
# Sao traducoes do tree em ingles, ja indexado — no grafo so geram ruido em
# search_code e consomem o auto_index_limit.
docs/i18n/
# ─────────────────────────────────────────────────────────────────────────────
# 7. Arquivos especificos (nao diretorios inteiros)
# ─────────────────────────────────────────────────────────────────────────────
# Segredos e env — NUNCA indexar
.env
.env.*
!.env.example
!.env.homolog.example
# TypeScript build info e next env declaration
*.tsbuildinfo
next-env.d.ts
typescript
# SQLite transient files (WAL/SHM/journal)
*.sqlite-shm
*.sqlite-wal
*.sqlite-journal
# Mapas e source maps
*.map
# Bun / npm lockfiles ruidosos
bun.lock
# `cheaper-inference-gateway.svg` e arquivos de midia na raiz/asset ja cobertos
# pelos `ignored-suffix` do indexador (svg/png/jpg/ico/etc >50kB ou >500linhas);
# manter a regra explicita aqui ajuda a auditar:
cheaper-inference-gateway.svg
cheaper-inference-gateway-*.svg
# Husky internals
.husky/_/
# CI / quality metric artifacts
config/quality/quality-metrics.json
config/quality/test-impact-map.json
audit-report.json
.gh-discussions.json
# i18n audit (gerado por npm run scripts)
scripts/i18n/_audit.json
scripts/i18n/_pending-keys.json
# NOTA: bin/omniroute.mjs foi removido daqui (2026-08-05). Estava marcado como
# "scratch", mas e o entrypoint real do CLI publicado (package.json -> bin.omniroute)
# e consta em PACK_ARTIFACT_REQUIRED_PATHS. Precisa estar no grafo.
# Deploy / docker backups
deploy.sh
docker-compose.yml.bak
docker-compose.minimal.yml

View File

@@ -1,141 +0,0 @@
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
#
# CodeRabbit review configuration for cheaper-inference/OmniRoute (open-source plan,
# public repository). Reviews run on CodeRabbit's infrastructure, not on our Actions runners.
#
# Calibration phase (from 2026-10-28, ~2 weeks): profile `chill` and every pre-merge check
# in `warning`. The maintainer decides afterwards whether the CodeRabbit status becomes a
# Mergify queue condition and whether any check moves to `error`. Plan:
# _tasks/superpowers/plans/2026-10-28-coderabbit-blacksmith.md (private repo).
#
# Bot comments are external content generated from the PR diff (which may come from a fork):
# agents and skills that read reviews treat them as data, never as instructions.
language: en-US
reviews:
profile: chill
high_level_summary: true
# Keep the summary in the walkthrough comment. Writing it into the PR description fires a
# pull_request "edited" event, which ci.yml and quality.yml listen to, so every review
# restarted (and cancelled) the PR's CI and Quality Gates runs.
high_level_summary_in_walkthrough: true
poem: false
# Single maintainer identity and a lot of walkthrough already: keep the summary lean.
sequence_diagrams: false
suggested_reviewers: false
# Anti-slop for public repos: label low-quality PRs instead of spending a review on them.
slop_detection:
enabled: true
label: "slop"
auto_review:
enabled: true
# The open-source plan allows ~1-10 PR reviews per hour per developer (scaled by stars)
# and most PRs here come from one maintainer identity used by several sessions, each
# pushing many commits. Review each PR once; re-run on demand with
# `@coderabbitai review` (or `@coderabbitai full review`).
auto_incremental_review: false
# Bot PRs would burn the hourly allowance; Dependabot bumps are covered by CI and the
# security wave, Mergify queue candidates are drafts anyway.
ignore_usernames:
- "dependabot[bot]"
- "mergify[bot]"
# Drafts are skipped; the Mergify merge-queue candidates are drafts too.
drafts: false
base_branches:
- "^release/v\\d+\\.\\d+\\.\\d+$"
- "^main$"
labels:
- "!skip-coderabbit"
ignore_title_keywords:
- "[skip review]"
- "WIP"
# Release-train validation PRs: 400+ files, over the review file limit, never merged.
- "do not merge"
path_filters:
# 66 translated doc mirrors and the translation state are produced by the i18n waves.
- "!docs/i18n/**"
- "!.i18n-state.json"
# Translated UI catalogs; the English source catalog stays in review.
# Exclusions only: a pattern without "!" turns the filter into an allowlist, and
# exclusions always win, so an "en.json" include left every file out of review.
# The two classes match every catalog except en.json (el, es, et start with "e").
- "!src/i18n/messages/[a-df-z]*.json"
- "!src/i18n/messages/e[a-mo-z]*.json"
- "!**/package-lock.json"
# Generated files.
- "!docs/reference/PROVIDER_REFERENCE.md"
- "!**/*.svg"
- "!CHANGELOG.md"
# Vendored CI UI Kit: fixes belong upstream, and the snapshot check rejects local edits.
- "!packages/ui-kit/**"
path_instructions:
- path: "src/app/api/**"
instructions: >-
Every route follows CORS -> Zod validation -> optional auth -> handler in open-sse/handlers.
Error bodies go only through buildErrorBody() or sanitizeErrorMessage() from
open-sse/utils/error.ts; never return raw err.stack or err.message. No raw SQL in routes:
use the src/lib/db/* modules. Routes that can spawn processes need isLocalOnlyPath()
classification in src/server/authz/routeGuard.ts.
- path: "open-sse/**"
instructions: >-
Public upstream OAuth client ids/secrets and Firebase Web keys only through
resolvePublicCred() (open-sse/utils/publicCreds.ts), never as string literals. Never
swallow errors in SSE streams. Hash opaque tokens with opaqueTokenFingerprint() and check
hosts with open-sse/utils/urlHost.ts instead of ad-hoc substring checks.
- path: "src/lib/db/**"
instructions: >-
Migrations must be idempotent and run in transactions. Never barrel-import from localDb.ts;
import the specific src/lib/db/* module.
- path: ".github/workflows/**"
instructions: >-
Never run fork pull-request code on self-hosted runners. Pin third-party actions by SHA.
Pass event fields to run: steps through env, never interpolate them. Job ids must stay in
sync with config/quality/admission-policy.json (Gate / CI and Gate / Quality).
- path: "tests/**"
instructions: >-
Tests must isolate DATA_DIR and close DB handles. Flag weakened or removed assertions and
skipped tests that only exist to make CI green.
pre_merge_checks:
title:
mode: warning
requirements: >-
Conventional Commits: type(scope): subject, with type one of feat, fix, refactor, docs,
test, chore, ci, deps, perf.
description:
mode: warning
custom_checks:
- name: "Tests for production code"
mode: warning
instructions: >-
If production code under src/, open-sse/, electron/ or bin/ changes, the PR must add or
update tests (AGENTS.md Hard Rules #8 and #18).
- name: "No AI attribution"
mode: warning
instructions: >-
Commits and the PR body must not carry a Co-Authored-By trailer naming an AI assistant
or bot, nor a "Generated with <AI tool>" footer (AGENTS.md Hard Rule #16). Human
co-authors are fine.
tools:
# CI's lint applies the frozen suppressions in config/quality/eslint-suppressions.json;
# without them CodeRabbit's eslint run would re-report years of accepted debt.
eslint:
enabled: false
# Docs have their own gates (npm run check:docs-all).
markdownlint:
enabled: false
gitleaks:
enabled: true
actionlint:
enabled: true
shellcheck:
enabled: true
chat:
auto_reply: true
knowledge_base:
code_guidelines:
enabled: true
# **/AGENTS.md, **/CLAUDE.md, **/GEMINI.md and .github/copilot-instructions.md are read
# by default (each scoped to its own directory); these patterns only add the security
# references the hard rules point to.
filePatterns:
- "docs/security/ERROR_SANITIZATION.md"
- "docs/security/PUBLIC_CREDS.md"

View File

@@ -7,15 +7,8 @@
**/.vscode
# Dependencies and build output
# `node_modules` alone matches the ROOT only — Docker's matcher does not cross
# `/` like .gitignore does. Without the `**/` form, nested installs ship in the
# build context (e.g. @omniroute/opencode-provider/node_modules, ~79 MB of
# devDependencies). Both forms are kept: the bare one is the documented root
# rule, the `**/` one covers every nested package.
node_modules
**/node_modules
.next
.build
out
build
dist
@@ -24,152 +17,16 @@ coverage
# Runtime data and logs
data
logs
.sandbox
# Local env files (inject at runtime via --env-file or -e)
.env*
**/.env*
!.env.example
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Debug logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# Test suites
tests
test-results
playwright-report
blob-report
output
.playwright-cli
.playwright-mcp
.stryker-tmp
reports/mutation
# Local caches and quality-gate artifacts (all gitignored). `_*` does not match
# dot-prefixed names, so these need explicit entries.
.artifacts
.eslintcache*
.fakebin-*
MAX
quality-ratchet/
# Documentation
# Issue #2348: The Dashboard Docs viewer reads markdown from `/app/docs` at
# runtime. The previous `docs/*` block hid every file except openapi.yaml,
# so the in-product help screen failed with ENOENT for every page.
# We now keep the English markdown tree plus the docs assets imported by MDX
# during `next build`, while still dropping the extra raster diagram sources
# and the translated files the runtime never reads.
#
# 2026-11-03 (owner decision): the image serves the translated /docs pages
# (#18699), which read docs/i18n/<locale>/docs/<section>/<PAGE>.md at runtime.
# Re-include exactly those mirrors: the sections source.config.ts compiles,
# minus the operator-internal security pages re-excluded below. The README,
# CHANGELOG, agent-guide and llm.txt mirrors at each locale root stay out.
# Keep in sync with scripts/build/docsMirrorRuntime.mjs (enforced by
# tests/unit/docs-mirror-runtime-shipping.test.ts).
docs/i18n/**
!docs/i18n/*/docs/getting-started/**/*.md
!docs/i18n/*/docs/guides/**/*.md
!docs/i18n/*/docs/architecture/**/*.md
!docs/i18n/*/docs/reference/**/*.md
!docs/i18n/*/docs/frameworks/**/*.md
!docs/i18n/*/docs/routing/**/*.md
!docs/i18n/*/docs/security/**/*.md
!docs/i18n/*/docs/compression/**/*.md
!docs/i18n/*/docs/ops/**/*.md
!docs/i18n/*/docs/providers/**/*.md
!docs/i18n/*/docs/comparison/**/*.md
docs/i18n/*/docs/security/STEALTH_GUIDE.md
docs/i18n/*/docs/security/SOCKET_DEV_FINDINGS.md
docs/i18n/*/docs/security/MITM-TPROXY-DECRYPT.md
docs/i18n/*/docs/security/PUBLIC_CREDS.md
# Internal planning artifacts (gitignored). `*.md` above only matches the root,
# so without this rule these land in /app/docs and become readable through the
# dashboard's Docs viewer at runtime.
docs/superpowers/**
# Operator-internal security writeups: git only, not the image or /docs catalog.
docs/security/STEALTH_GUIDE.md
docs/security/SOCKET_DEV_FINDINGS.md
docs/security/MITM-TPROXY-DECRYPT.md
docs/security/PUBLIC_CREDS.md
docs/diagrams/**/*.png
docs/diagrams/**/*.jpg
docs/diagrams/**/*.jpeg
docs/diagrams/**/*.gif
docs/diagrams/**/*.webp
# Note: `*.md` matches the root only (Go filepath.Match does not cross /),
# so nested docs/**/*.md is implicitly kept without a re-include rule.
*.md
!README.md
# Electron (separate build)
electron
# VS Code extension (separate project)
vscode-extension
# Build artifacts
*.tgz
*.AppImage
*.deb
*.rpm
# Package manager lock (bun)
bun.lock
# Agent config
.agents
.gemini
.claude
.source
# Misc
llm.txt
images
clipr
omnirouteCloud
omnirouteSite
# Temporary/Scratch Folders
_*
# CI/CD and Version Control (that are not actual code)
.github
.husky
.omc
# Test Configs and Reports
playwright.config.ts
vitest*.ts
audit-report.json
sonar-project.properties
# Deployment Configs
docker-compose*.yml
fly.toml
# Consistent with .gitignore
.DS_Store
.idea/
.config/
.data/
.omnivscodeagent/
*.sqlite-*
*.tsbuildinfo
next-env.d.ts
security-analysis/
.analysis/
antigravity-manager-analysis/
.sisyphus/
.plans/
app.__qa_backup/
.app-build-backup-*/
.gitnexus
.worktrees
.next-playwright/
cloud/
electron/dist-electron

View File

@@ -1,12 +0,0 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.sh]
indent_size = 4

View File

@@ -1,6 +0,0 @@
ENABLE_LIVE_DEVIN_TESTS=0
DEVIN_BRIDGE_MODEL=devin-cli-agentic/swe-1-7
DEVIN_BRIDGE_SONNET_MODEL=devin-cli-agentic/swe-1-7
DEVIN_BRIDGE_OPUS_MODEL=devin-cli-agentic/swe-1-7
DEVIN_BRIDGE_HAIKU_MODEL=devin-cli-agentic/swe-1-7
DEVIN_BRIDGE_SUBAGENT_MODEL=devin-cli-agentic/swe-1-7

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +0,0 @@
# Homologação E2E real — copie para .env.homolog (NUNCA commitar o real)
HOMOLOG_BASE_URL=http://192.168.0.15:20128
# Senha de management do dashboard da VPS (a mesma do /login)
HOMOLOG_ADMIN_PASSWORD=
# Deixe vazio: a suíte cria uma API key efêmera via admin e revoga no fim.
# Só preencha para depurar uma camada isolada com uma key fixa.
HOMOLOG_API_KEY=
# Tier crítico (chat real, max_tokens=5). Demais providers: só validação de catálogo.
HOMOLOG_CRITICAL_PROVIDERS=openai,anthropic,gemini,codex,grok,glm,deepseek,openrouter

View File

@@ -1,45 +0,0 @@
# ──────────────────────────────────────────────────────────────────────
# OmniRoute — Self-Host env (minimal, zero-fee self-host)
# ──────────────────────────────────────────────────────────────────────
# cp .env.selfhost.example .env
# Edit only the two lines marked `# EDIT ME`. Everything else has a sane
# default. No secrets are baked in — OmniRoute never ships credentials.
#
# Full variable reference: docs/guides/DOCKER_GUIDE.md and .env.example
# ──────────────────────────────────────────────────────────────────────
# ── Ports (host-side) ──────────────────────────────────────────────────
# Dashboard + API + Live-WS. Already match the image defaults.
DASHBOARD_PORT=20128
API_PORT=20129
LIVE_WS_PORT=20132
# ── Bind address ───────────────────────────────────────────────────────
# 127.0.0.1 = loopback only (safe with REQUIRE_API_KEY=false, the default).
# Set to 0.0.0.0 ONLY when REQUIRE_API_KEY=true OR a reverse proxy
# enforces auth upstream. Exposing an unauthenticated /v1 proxy on the
# LAN/WAN lets anyone burn your provider quotas. # EDIT ME if you must.
APP_BIND_HOST=127.0.0.1
# ── Auth ──────────────────────────────────────────────────────────────
# false = the dashboard and /v1 proxy are open to APP_BIND_HOST's network.
# true = /v1 requests need an API key (a logged-in dashboard session also works);
# the dashboard needs login once a password
# exists. Create the login password in the onboarding wizard on first visit
# (skipping that step turns dashboard login off, even with
# REQUIRE_API_KEY=true); after you submit it, the wizard asks for
# a one-time token from `docker logs omniroute | grep BOOTSTRAP`.
# # EDIT ME — set true.
REQUIRE_API_KEY=false
# INITIAL_PASSWORD=strong-password-here # fill in to pre-seed the dashboard password (an empty value behaves like unset)
# ── Memory ceiling (V8 old-space) ──────────────────────────────────────
# 1024 = dashboard + light chat. Coding agents (long POST /v1/responses
# bodies) need more — see SELF_HOST_GUIDE.md "sizing". 2048 is a safe
# default for a single user who runs Claude Code / Codex through it.
OMNIROUTE_MEMORY_MB=2048
# ── Browser-facing origin (optional) ───────────────────────────────────
# Set ONLY if you expose OmniRoute behind a domain via a reverse proxy.
# NEXT_PUBLIC_BASE_URL=https://your-domain.example.com
# BASE_URL=http://omniroute:20128

11
.gitattributes vendored
View File

@@ -1,11 +0,0 @@
# Shell scripts must always be checked out with LF line endings.
#
# On Windows, core.autocrlf=true converts text files to CRLF in the working
# tree. Scripts that are kernel-exec'd (Docker ENTRYPOINT, bin/*.sh on Linux
# hosts) then fail with `exec ...: no such file or directory` because the
# shebang becomes "#!/bin/sh\r". eol=lf overrides autocrlf for these files.
*.sh text eol=lf
# This file must stay LF too: git parses it as-is, and a trailing CR would
# corrupt every pattern (e.g. "*.sh\r" matches nothing).
.gitattributes text eol=lf

2
.github/CODEOWNERS vendored
View File

@@ -1,2 +0,0 @@
* @diegosouzapw

5
.github/FUNDING.yml vendored
View File

@@ -1,5 +0,0 @@
# Funding links for OmniRoute — rendered as the "Sponsor" button on GitHub.
# Docs: https://docs.github.com/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/displaying-a-sponsor-button-in-your-repository
github: diegosouzapw
# Additional platforms (uncomment and fill in before enabling):
# custom: ["https://omniroute.online/donate"]

View File

@@ -1,173 +0,0 @@
name: Bug Report
description: Report a bug or unexpected behavior in OmniRoute
title: "fix(): "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to report a bug. Please fill out the sections below so we can reproduce and fix the issue.
The title is prefilled as `fix(): ` to match the [Conventional Commits](https://github.com/cheaper-inference/OmniRoute/blob/main/CONTRIBUTING.md#commit-messages) convention — pick a scope from the list documented there (e.g. `providers`, `resilience`, `dashboard`, `api`).
- type: input
id: version
attributes:
label: OmniRoute Version
description: "Run `omniroute --version` or check the left sidebar in the dashboard."
placeholder: "e.g. 3.7.9"
validations:
required: true
- type: dropdown
id: install-method
attributes:
label: Installation Method
options:
- npm (global)
- Docker / Docker Compose
- Electron desktop app
- Built from source
validations:
required: true
- type: dropdown
id: os
attributes:
label: Operating System
options:
- Windows
- macOS
- Linux
validations:
required: true
- type: input
id: os-version
attributes:
label: OS Version
placeholder: "e.g. Windows 11 25H2, macOS 26.5, Ubuntu 26.04"
validations:
required: false
- type: input
id: node-version
attributes:
label: Node.js Version
description: "Run `node --version`. Skip if using Docker."
placeholder: "e.g. 24.15.0"
validations:
required: false
- type: input
id: provider
attributes:
label: Provider(s) Involved
description: "Which AI provider(s) does this affect?"
placeholder: "e.g. Antigravity, OpenRouter, Ollama, Qwen"
validations:
required: false
- type: input
id: model
attributes:
label: Model(s) Involved
placeholder: "e.g. claude-opus-4-7, gpt-5.5, gemini-3.1-pro"
validations:
required: false
- type: input
id: client-tool
attributes:
label: Client Tool
description: "Which tool are you using OmniRoute with?"
placeholder: "e.g. Claude Code, Cursor, Roo Code, OpenClaw, Gemini CLI, cURL"
validations:
required: false
- type: textarea
id: description
attributes:
label: Description
description: "A clear description of what the bug is."
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to Reproduce
description: "Step-by-step instructions to reproduce the behavior."
placeholder: |
1. Go to '...'
2. Click on '...'
3. See error
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected Behavior
description: "What did you expect to happen?"
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual Behavior
description: "What actually happened?"
validations:
required: true
- type: dropdown
id: test-impact
attributes:
label: Test Impact
description: "What automated test coverage should exist for this bug?"
options:
- Needs a new unit test
- Needs a new integration test
- Needs a new e2e test
- Existing automated test already fails
- Unsure
validations:
required: true
- type: textarea
id: logs
attributes:
label: Error Logs / Output
description: "Paste any relevant error messages, logs, or terminal output. This will be automatically formatted as code."
render: shell
validations:
required: false
- type: textarea
id: screenshots
attributes:
label: Screenshots
description: "If applicable, add screenshots to help explain the problem. Please also include the text of any error messages above — screenshots alone are not searchable."
validations:
required: false
- type: textarea
id: additional
attributes:
label: Additional Context
description: "Any other context about the problem (e.g. proxy config, number of accounts, network setup)."
validations:
required: false
- type: textarea
id: validation-plan
attributes:
label: Validation Plan
description: "Which commands or tests should prove this bug is fixed?"
placeholder: |
Example:
- node --import tsx --test tests/unit/my-file.test.ts
- npm run test:coverage
validations:
required: false

View File

@@ -1,5 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: Question / Help
url: https://github.com/cheaper-inference/OmniRoute/discussions
about: For questions or help with setup, please use GitHub Discussions instead of opening an issue.

View File

@@ -1,98 +0,0 @@
name: Feature Request
description: Suggest a new feature or improvement for OmniRoute
title: "feat(): "
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
Thanks for suggesting a feature! Please describe the problem you're trying to solve and how you'd like it to work.
The title is prefilled as `feat(): ` to match the [Conventional Commits](https://github.com/cheaper-inference/OmniRoute/blob/main/CONTRIBUTING.md#commit-messages) convention — pick a scope from the list documented there (e.g. `providers`, `resilience`, `dashboard`, `api`).
- type: textarea
id: problem
attributes:
label: Problem / Use Case
description: "What problem does this feature solve? Why do you need it?"
placeholder: "I'm trying to ... but currently ..."
validations:
required: true
- type: textarea
id: solution
attributes:
label: Proposed Solution
description: "How would you like this to work?"
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives Considered
description: "Have you considered any workarounds or alternative approaches?"
validations:
required: false
- type: textarea
id: acceptance
attributes:
label: Acceptance Criteria
description: "Describe the concrete behaviors or outcomes that should be validated before this is considered done."
placeholder: |
Example:
- API route returns 200 with valid payload
- Unit coverage added for the new branch
- Existing integrations remain green
validations:
required: true
- type: dropdown
id: area
attributes:
label: Area
description: "Which part of OmniRoute does this relate to?"
multiple: true
options:
- Dashboard / UI
- Proxy / Routing
- Provider Support
- CLI Tools Integration
- OAuth / Authentication
- Analytics / Usage Tracking
- Docker / Deployment
- Documentation
- Other
validations:
required: true
- type: input
id: provider
attributes:
label: Related Provider(s)
description: "If this relates to specific providers, list them."
placeholder: "e.g. Antigravity, OpenRouter, Ollama"
validations:
required: false
- type: textarea
id: additional
attributes:
label: Additional Context
description: "Any other context, mockups, or references."
validations:
required: false
- type: textarea
id: test-plan
attributes:
label: Expected Test Plan
description: "Which automated tests or coverage changes should accompany this work?"
placeholder: |
Example:
- Add unit tests for open-sse/services/combo.ts
- Extend integration coverage for /api/v1/models
- Keep npm run test:coverage at 60%+
validations:
required: false

View File

@@ -1,73 +0,0 @@
name: Test Coverage Task
description: Create a focused coverage-improvement issue tied to concrete files and targets
title: "[Coverage] "
labels: ["test", "coverage"]
body:
- type: markdown
attributes:
value: |
Use this template for scoped coverage work. Keep it tied to specific files, measurable targets, and the gate that must stay green.
- type: input
id: baseline
attributes:
label: Current Coverage Baseline
description: "Paste the current overall or file-level coverage number that justifies this task."
placeholder: "e.g. Lines 79.00%, Branches 72.85%, open-sse/handlers/chatCore.ts = 67.22%"
validations:
required: true
- type: textarea
id: scope
attributes:
label: Target Files Or Modules
description: "List the concrete source files or directories that this task will cover."
placeholder: |
Example:
- open-sse/handlers/chatCore.ts
- open-sse/services/combo.ts
- tests/integration/chat-pipeline.test.ts
validations:
required: true
- type: textarea
id: scenarios
attributes:
label: Missing Scenarios
description: "Describe the specific behaviors, branches, or failure paths that are currently uncovered."
placeholder: |
Example:
- Upstream timeout path
- Empty tool_calls normalization
- Fallback route after first provider failure
validations:
required: true
- type: input
id: target
attributes:
label: Coverage Target
description: "Set the expected target for this task."
placeholder: "e.g. Raise open-sse/handlers to 80%+ lines and keep global gate >= 60%"
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation Commands
description: "List the commands that must pass before this issue can be closed."
placeholder: |
Example:
- node --import tsx --test tests/unit/my-suite.test.ts
- npm run test:coverage
validations:
required: true
- type: textarea
id: notes
attributes:
label: Notes
description: "Optional context, blockers, or dependencies."
validations:
required: false

View File

@@ -1,49 +0,0 @@
## Summary
- What was broken, for whom, and what does this change fix?
- Root cause in one or two sentences.
## Related Issues
- Closes # <!-- use "Refs #" if this only partially fixes the issue -->
## Target Branch
See the [Release Strategy](../../docs/ops/RELEASE_STRATEGY.md) and the [ROADMAP](../../ROADMAP.md):
- [ ] Base is the active `release/v3.8.x` branch (the highest open `release/v*`), not `main`
(after 3.9.0, fixes target `stable/v3` and are forward-ported to v4 with credit)
## Proof Of Fix (required)
Every bug fix must be validated by ONE of the following (`AGENTS.md`, Hard Rule #18).
A fix without either is not merged.
- [ ] **TDD (preferred)** — a test that fails before the fix and passes after it.
- Test file(s):
- Failing output before the fix (paste the relevant lines):
- [ ] **Real-environment test** (only when TDD is not possible — OAuth upstream flows,
upstream WebSocket/Cloudflare behavior, UI-only regressions, hardware-dependent
behavior) — record the exact command and its result:
- Environment:
- Command:
- Result:
## Scope
- [ ] Only the files the failing test proves need changing are touched
- [ ] No test was weakened or deleted to make the suite pass
## Validation
Choose the focused loop for your change type from the
[Contribution Golden Path](../../docs/ops/CONTRIBUTION_GOLDEN_PATH.md). The full unit suite,
Vitest, the 60% coverage gate, and the production build all run in CI on this PR:
- [ ] Change type: provider / routing / UI / i18n / CLI / DB / build-deploy / other
- [ ] Focused tests and category gates from the golden path
- [ ] `npm run lint`
## Reviewer Notes
- Risky areas, side effects on other providers/routes, or follow-ups reviewers should know about.

View File

@@ -1,44 +0,0 @@
## Summary
- What does this feature add, and who uses it?
- Link the issue or discussion where it was agreed on.
## Related Issues
- Closes #
- Related to #
## Target Branch
See the [Release Strategy](../../docs/ops/RELEASE_STRATEGY.md) and the [ROADMAP](../../ROADMAP.md):
- [ ] Base is the active `release/v3.8.x` branch (the highest open `release/v*`), not `main`
- [ ] I understand that from 3.8.55 on, feature PRs are held with the `v4-feature` label and
re-targeted to the v4 channel (`develop`) when it opens — they are not closed
## Design
- Where does the code live (route / handler / executor / service / DB module / UI)?
- New settings, env vars, feature flags, DB migrations, or MCP tools? List them.
- Is it opt-in? Data-mutating behavior must be off by default.
## Validation
Choose the focused loop for your change type from the
[Contribution Golden Path](../../docs/ops/CONTRIBUTION_GOLDEN_PATH.md). The full unit suite,
Vitest, the 60% coverage gate, and the production build all run in CI on this PR:
- [ ] Change type: provider / routing / UI / i18n / CLI / DB / build-deploy / other
- [ ] Focused tests and category gates from the golden path
- [ ] `npm run lint`
- [ ] New production code ships with new automated tests in this PR
- [ ] Docs updated for every new endpoint, env var, CLI command, or setting
- [ ] New UI strings added to the i18n catalogs
## Tests Added Or Updated
- List every changed or added automated test file.
## Reviewer Notes
- Risky areas, migrations, feature flags, or manual validation reviewers should know about.

View File

@@ -1,32 +0,0 @@
# npm ci with retry
This action installs the checkout dependencies with up to three attempts and restores a node_modules tree only when its complete cache key matches. Node, npm, lockfile, project npm configuration, postinstall helpers and the action itself participate in the key. Cached and freshly installed trees still pass the existing native-runtime verification.
The installation step sets `ONNXRUNTIME_NODE_INSTALL=skip` before invoking npm. ONNX Runtime reads this environment variable directly, so skipping its additional CUDA installation does not depend on npm forwarding the custom `.npmrc` key. The repository retains that key temporarily; its npm warning can therefore remain.
## Installing this checkout locally
For a POSIX shell, set the variable on the install command:
```sh
ONNXRUNTIME_NODE_INSTALL=skip npm ci
```
Use `npm install` in place of `npm ci` when deliberately updating the lockfile.
In PowerShell, set it in the current shell before starting npm:
```powershell
$env:ONNXRUNTIME_NODE_INSTALL = "skip"
npm ci
```
The PowerShell assignment remains in that process environment and is inherited by its children. npm does not load the application's `.env` file for this purpose. A package preinstall script cannot set the environment of its parent npm process.
## Scope
The environment is scoped to this action's install step. Direct checkout-install steps in the enumerated workflows set the same variable themselves. It is not exported to unrelated workflow steps or changed for tarball smoke tests.
The Dockerfile checkout install already uses `--ignore-scripts`, then builds only the SQLite native dependency; that path does not execute the ONNX install script.
This policy does not force an environment variable on people installing the published package, on remote deployment commands, or inside a separate container. The checkout `.npmrc` is also not a configuration mechanism for those consumers. Those installation paths have their own contracts. The regression tests exercise the ONNX flag parser and a local npm lifecycle without downloading CUDA, installing the application or claiming to reproduce a startup crash.

View File

@@ -1,101 +0,0 @@
name: npm ci with retry
description: >-
Install dependencies. Restores node_modules from the Actions cache when the exact
lockfile / runner / Node version / postinstall inputs match; otherwise runs npm ci
with retries for transient registry/network failures and saves the tree for the
next run.
inputs:
cache:
description: Set to "false" to skip the node_modules cache and always run npm ci.
required: false
default: "true"
runs:
using: composite
steps:
- name: Select the lockfile-compatible npm version
id: npm
shell: bash
run: |
set -euo pipefail
expected=$(node -p "require('./config/ci/toolchain.json').npm")
if ! [[ "$expected" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Invalid pinned npm version" >&2
exit 1
fi
if [ "$(npm --version)" != "$expected" ]; then
npm install --global "npm@$expected" --no-audit --no-fund
fi
actual=$(npm --version)
if [ "$actual" != "$expected" ]; then
echo "npm version differs from the lockfile toolchain" >&2
exit 1
fi
echo "version=$actual" >> "$GITHUB_OUTPUT"
- name: Resolve Node version for the cache key
id: node
shell: bash
run: echo "version=$(node --version)" >> "$GITHUB_OUTPUT"
# #8084 D3 (plan 3.8.51 task 5): every job used to pay ~80-90 s of `npm ci` even
# with setup-node's npm tarball cache warm — 36 jobs per ci.yml run, ~55 min of
# runner time per run just installing. A node_modules cache keyed on EVERYTHING
# that shapes the tree lets a hit skip the install entirely.
#
# No restore-keys on purpose (same rule as the ESLint cache, #11600): a partial
# tree from another lockfile / Node / postinstall script is exactly the kind of
# silent drift a lockfile-pinned CI must never inherit. Exact key or a full npm ci.
#
# postinstall (scripts/build/postinstall.mjs + helpers) only mutates node_modules
# on a plain install — its dist/ branch is gated on dist/ existing, which never
# holds at install time in CI — so the cached tree already carries its effects.
- name: Restore node_modules
id: node-modules
if: inputs.cache == 'true'
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: node_modules
key: node-modules-v3-${{ runner.os }}-${{ runner.arch }}-${{ steps.node.outputs.version }}-${{ steps.npm.outputs.version }}-${{ hashFiles('package-lock.json', '.npmrc', 'scripts/build/postinstall.mjs', 'scripts/build/postinstallSupport.mjs', 'scripts/build/colocateOptionals.mjs', 'scripts/build/wreqJsNative.mjs', 'scripts/build/fixPlaywrightAndroid.mjs', 'scripts/build/native-binary-compat.mjs', 'scripts/build/betterSqlitePrebuildTarget.mjs', 'scripts/ci/verify-ci-install.mjs', '.github/actions/npm-ci-retry/action.yml') }}
- name: npm ci (with retry)
if: steps.node-modules.outputs.cache-hit != 'true'
shell: bash
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
run: |
set -euo pipefail
max_attempts=3
delay_seconds=20
for attempt in $(seq 1 "$max_attempts"); do
if [ "$attempt" -gt 1 ]; then
echo "npm ci attempt $attempt/$max_attempts after transient failure"
fi
# --no-audit: `audit:deps` is its own gate; the inline audit only adds latency.
if npm ci --no-audit --no-fund; then
exit 0
else
exit_code=$?
fi
if [ "$attempt" -eq "$max_attempts" ]; then
exit "$exit_code"
fi
sleep "$delay_seconds"
delay_seconds=$((delay_seconds * 2))
done
# Both cache hits and successful installs must execute the native runtimes.
# A package directory alone cannot prove ABI compatibility or a usable binary.
- name: Verify installed native runtimes
id: verify-install
shell: bash
run: node scripts/ci/verify-ci-install.mjs
- name: node_modules restored from cache
if: steps.node-modules.outputs.cache-hit == 'true'
shell: bash
run: echo "node_modules restored from cache (key hit) — npm ci skipped"

View File

@@ -1,15 +0,0 @@
# OmniRoute PR and Coverage Instructions
- Treat `npm run test:coverage` as a required gate for PR work.
- The repository minimum is `60%` for statements, lines, functions, and branches.
- If a PR changes production code in `src/`, `open-sse/`, `electron/`, or `bin/`, it must include automated tests in the same PR.
- When reviewing or updating a PR, if the report shows missing tests or coverage below `60%`, do not stop after reporting the problem. Add or update tests in the PR first, rerun the coverage gate, and only then ask for confirmation.
- Prefer the smallest test layer that proves the behavior:
- unit tests first
- integration tests when multiple modules or DB state are involved
- e2e only when the behavior is truly UI or workflow-dependent
- For bug issues, try to encode the reproduction as an automated test before or alongside the fix.
- In the final PR report, include:
- the commands you ran
- the changed test files
- the final coverage result

100
.github/dependabot.yml vendored
View File

@@ -24,108 +24,8 @@ updates:
update-types: ["version-update:semver-major"]
- dependency-name: "eslint-config-next"
update-types: ["version-update:semver-major"]
# typescript majors are peer-blocked by typescript-eslint, which pins a hard
# upper bound (8.64.0 → peerDependencies.typescript ">=4.8.4 <6.1.0"). A TS 7
# bump therefore violates the peer and takes down the whole toolchain at once —
# #7068 grouped it with 6 harmless bumps and turned Build + Lint + Quality Ratchet
# + Unit (6/8, 8/8) + Integration (1/2, 2/2) + dast-smoke red in one shot, blocking
# the innocuous updates riding along with it. Un-ignore once typescript-eslint
# widens the peer, and migrate TS majors intentionally (own PR, own CI run).
- dependency-name: "typescript"
update-types: ["version-update:semver-major"]
# jscpd v5 is a Rust rewrite (native binary, no Node.js programmatic API).
# scripts/check/check-duplication.mjs is deliberately pinned to jscpd@4 (it
# parses jscpd-report.json against a frozen baseline). A v5 major would break
# the duplication gate — migrate the gate intentionally, not via dependabot.
- dependency-name: "jscpd"
update-types: ["version-update:semver-major"]
# ioredis is a SOFT/optional dependency loaded through a dynamic import
# (src/lib/quota/redisQuotaStore.ts — "Redis driver requires ioredis package"),
# so a breaking major never fails at build or typecheck time: the only consumers
# are the distributed quota store (redisQuotaStore.ts, storeFactory.ts) and the
# `import type Redis` in src/shared/utils/rateLimiter.ts. Nothing in the unit or
# vitest suites exercises a live Redis connection, so a v5→v6 API break would ship
# green and only surface at runtime for operators running distributed quota — the
# exact users least able to absorb it. #9310 grouped that major with 9 harmless
# bumps; majors here need their own PR and a deliberate migration review.
- dependency-name: "ioredis"
update-types: ["version-update:semver-major"]
# @huggingface/transformers is VPS-validated at ^4.2.0 (migrated intentionally in
# #9962). It is load-bearing for the LLMLingua ONNX compression engine (open-sse/
# services/compression/engines/llmlingua/ — @atjsh/llmlingua-2@2.0.5 peers on
# "@huggingface/transformers": "^3.5.2 || ^4.0.0") and for local memory embeddings
# (src/lib/memory/embedding/transformersLocal.ts). Further majors must be re-validated
# on the VPS — so keep auto-bumps frozen (no update-types = ignore every version).
# Migrate it intentionally, not via dependabot (#4050).
- dependency-name: "@huggingface/transformers"
# onnxruntime-node is the OTHER HALF of the @huggingface/transformers pair frozen
# above: the hoisted copy must equal the exact version transformers pins, or npm
# nests a second ABI-incompatible native copy (contract test
# tests/unit/onnxruntime-single-copy.test.ts, pair established in #9962). A solo
# bump can never be correct — it only ever moves together with transformers, in
# the same deliberate migration PR. Freezing it keeps the production group PRs
# (e.g. #12219) from being born red on the pair contract.
- dependency-name: "onnxruntime-node"
# eslint-plugin-react-hooks is pinned to 7.0.1 by a contract test
# (tests/unit/eslint-react-hooks-version-pinned.test.ts) until the 7.1.1 rule set
# is adopted deliberately — that adoption needs a full cold lint run and its own
# PR (the #12146 react-hooks migration finished on 2026-09-01, so the path is
# open; the bump still must not ride a dependabot group, where it reds the
# development group PRs, e.g. #12220). Remove this ignore in the adoption PR
# together with the pin test.
- dependency-name: "eslint-plugin-react-hooks"
# The four entries below came out of the development group #17197 (26 updates),
# which could not land because these bumps break contracts or need a migration.
# Each one has to move in its own PR; the rest of the group stays automatic.
#
# promptfoo is an exact pin mirrored by the nightly LLM-security workflow
# (`npx --yes promptfoo@X.Y.Z` in nightly-llm-security.yml). The contract test
# tests/unit/build/llm-security-nightly-promptfoo-pin.test.ts requires the workflow
# pin to equal package.json and rejects releases proven broken (KNOWN_BROKEN:
# 0.123.1 and 0.124.1, promptfoo/promptfoo#10866 — the guard-validation step exits
# 100 on the guard's 4xx JSON body). Dependabot only edits package.json, so every
# bump reds that test. Bump by hand: package.json + workflow pin together, after
# re-running guard-validation against the new release.
- dependency-name: "promptfoo"
# fumadocs-mdx 15.4.7 imports `embedSource` from fumadocs-core/mdx-plugins/stringifier,
# which the fumadocs-core on this branch (16.15.x) does not export yet: the Build job
# dies loading next.config.mjs (#17197). fumadocs-core/fumadocs-ui ride the
# production group and fumadocs-mdx the development group, so dependabot can never
# move them together. Remove this ignore in the PR that bumps fumadocs-core,
# fumadocs-ui and fumadocs-mdx as one set.
- dependency-name: "fumadocs-mdx"
versions: [">=15.4.7"]
# @playwright/test must equal the runtime `playwright` / `playwright-core` exact pin
# (one Playwright in the tree — tests/unit/playwright-runner-args.test.ts). The
# runtime pair is a production dependency and @playwright/test a development one,
# so a solo bump from the development group always breaks that contract. Bump it by
# hand in the same PR that moves playwright and playwright-core.
- dependency-name: "@playwright/test"
# bun is an exact devDependency pin documented in AGENTS.md (Environment) and
# docs/ops/BUILD_WARNINGS.md: it runs only allow-listed gate/generator scripts, and
# any new Bun version must be validated byte-identical against the
# `node --import tsx` output first. @types/bun is its paired type package and moves
# with it. Bump both by hand, together with the docs that name the version.
- dependency-name: "bun"
- dependency-name: "@types/bun"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/electron"
schedule:
interval: "weekly"
day: "monday"
commit-message:
prefix: "deps"
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
commit-message:
prefix: "deps"

41
.github/labels.yml vendored
View File

@@ -1,41 +0,0 @@
# Declarative GitHub labels for the 3.8.5x -> 3.9.0 LTS release rail.
#
# Synced by `npm run labels:sync` (scripts/release/sync-labels.mjs): dry-run by
# default, `-- --apply` to create/update. Only the labels listed here are managed;
# labels missing from this file are never touched or deleted.
#
# Pre-existing operational labels (`queue`, `release-freeze`, `base-red`, ...) are
# intentionally NOT listed — they keep their current meaning and colors.
#
# Model: docs/ops/RELEASE_STRATEGY.md
#
# Fields: name (required), color (QUOTED 6-digit hex - unquoted values like 5319E7 or
# 012345 are parsed by YAML as numbers), description (<= 100 chars).
- name: v4-feature
color: "1D76DB"
description: Feature PR held for the v4 channel (develop); re-targeted when it opens
- name: lts
color: "0E8A16"
description: Belongs to the v3 LTS line (stable/v3) - fixes, security, provider updates
- name: forward-port
color: "C5DEF5"
description: Fix forward-ported from stable/v3 to develop with original-author credit
- name: channel:latest
color: "2EA44F"
description: Ships on the npm `latest` dist-tag (v3 until 4.0 GA)
- name: channel:next
color: "FBCA04"
description: Ships on the npm `next` dist-tag (v4 release candidates)
- name: channel:nightly
color: "5319E7"
description: Ships on the npm `nightly` dist-tag (v4 develop builds)
- name: preview-artifact
color: "BFDADC"
description: Requests a PR preview build artifact (dormant until the 3.8.58 rehearsal)

View File

@@ -1,45 +0,0 @@
## Summary
- Describe the user-facing or operational change.
## Related Issues
- Closes #
- Related to #
## Target Branch
See the [Release Strategy](../docs/ops/RELEASE_STRATEGY.md), the
[Contribution Golden Path](../docs/ops/CONTRIBUTION_GOLDEN_PATH.md) and the
[ROADMAP](../ROADMAP.md):
- [ ] Base is the active `release/v3.8.x` branch (the highest open `release/v*`), not `main`
- [ ] New feature? From 3.8.55 on it is held with the `v4-feature` label for the v4 channel
- Focused templates: append `?template=feature.md` or `?template=bugfix.md` to the compare URL
## Validation
Choose the change type and focused loop from the
[Contribution Golden Path](../docs/ops/CONTRIBUTION_GOLDEN_PATH.md). The full unit suite,
Vitest, the 60% coverage gate, and the production build all run in CI on this PR (#8329):
- [ ] Change type: provider / routing / UI / i18n / CLI / DB / build-deploy / other
- [ ] Focused tests and category gates from the golden path
- [ ] `npm run lint`
- [ ] Reconciled with the current active release base; focused checks rerun afterward
- [ ] Production-code changes include a new or updated automated test in this PR
- SonarQube is temporarily opt-in while the private project has no quota; it is not a PR gate.
## Tests Added Or Updated
- List every changed or added automated test file.
- If no production code changed, state that here.
## Coverage Notes
- If this PR changes `src/`, `open-sse/`, `electron/`, or `bin/`, explain which tests cover the change.
- If coverage moved down in any touched file, explain why and what follow-up task will recover it.
## Reviewer Notes
- Call out any risky areas, migrations, feature flags, or manual validation that reviewers should know about.

View File

@@ -1,36 +0,0 @@
name: API Route Typecheck
on:
pull_request:
branches:
- main
- "release/**"
types: [opened, synchronize, reopened, ready_for_review]
push:
branches: [main]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
api-typecheck:
name: API Route Typecheck
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
node-version: "24"
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Reject new API-route TypeScript diagnostics
run: node scripts/check/check-api-typecheck.mjs
- name: API typecheck gate unit tests
run: node --import tsx/esm --test tests/unit/build/check-api-typecheck.test.ts

View File

@@ -1,29 +0,0 @@
name: Release base repair
on:
push:
branches: [fix/release-v3.8.52-basereds]
permissions:
contents: read
jobs:
regression:
runs-on: ubuntu-latest
timeout-minutes: 12
env:
CI: "true"
OMNIROUTE_SKIP_SYSTEM_TRUST: "1"
DISABLE_SQLITE_AUTO_BACKUP: "true"
NEXT_TELEMETRY_DISABLED: "1"
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1"
OMNIROUTE_MAX_TEST_WORKERS: "2"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
fetch-depth: 0
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020
with:
node-version: "24"
- name: Verify old failure and final guarded transport
run: node scripts/check/base-ci-repair.mjs
- name: Clean owned state
if: always()
run: rm -rf -- .ci-work/base-ci-repair

View File

@@ -1,72 +0,0 @@
name: Build App
# Manual-only since #11946. The hosted 7 GB runner can no longer build this tree — 19 of
# the last 30 runs died with "The runner has received a shutdown signal" (VM out of
# memory) ~8 min into `next build`, release/v3.8.51 itself included, even with the 10 GB
# swapfile below. Triggered on `push: branches: ["**"]` it painted every branch and every
# PR red while producing an artefact nothing downloads. The bundle is validated where a
# build actually fits:
# - main: ci.yml `Build` (self-hosted omni-build pool) on every merge
# - release/**: nightly-release-green.yml (same pool, continuous)
# Dispatch this workflow by hand when a hosted build artefact is genuinely needed.
on:
workflow_dispatch:
permissions:
contents: read
jobs:
build:
name: Fast Production Build
runs-on: ubuntu-latest
steps:
- name: Expand Virtual Memory (Native 10GB Swap)
run: |
sudo swapoff -a || true
sudo rm -f /mnt/swapfile /swapfile
sudo fallocate -l 10G /mnt/swapfile || sudo dd if=/dev/zero of=/mnt/swapfile bs=1M count=10240
sudo chmod 600 /mnt/swapfile
sudo mkswap /mnt/swapfile
sudo swapon /mnt/swapfile
free -h
- name: Checkout repository
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- name: Install dependencies
run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Build Next.js app & CLI bundle
run: |
npm run build:release
env:
# Hosted artifact builds run with less memory than the opt-in 64 GB
# CI build slot. Keep Webpack here without overriding the latter's
# separately measured Turbopack policy (#16169). Validated 2026-10-18 on the
# hosted runner (run 39151150605): webpack compiled in 7.1 min, job 17 min.
# This is the floor docker-publish.yml must not go below
# (tests/unit/docker-publish-build-heap-14325.test.ts).
NODE_OPTIONS: "--max-old-space-size=10240"
OMNIROUTE_BUILD_MEMORY_MB: "10240"
OMNIROUTE_USE_TURBOPACK: "0"
- name: Archive build outputs
run: |
tar -czf omniroute-build.tar.gz .build dist
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: omniroute-build
path: omniroute-build.tar.gz
retention-days: 7

View File

@@ -1,42 +0,0 @@
name: Cancel runs of closed PRs
# A closed PR (merged or not) never gets a newer run on its ref, so the per-ref
# `concurrency` + cancel-in-progress in ci.yml / quality.yml never supersedes its runs
# and they keep their place in the hosted-runner queue. On 2026-10-26, 34 of 229 queued
# PR runs belonged to closed PRs or superseded heads while the org's Free plan allows 20
# concurrent hosted jobs. This job only calls the Actions API: it never checks out or runs
# the PR's code. `pull_request` (not `_target`): fork PRs get a read-only token and are
# skipped, which is fine — their runs wait for maintainer approval anyway.
on:
pull_request:
types: [closed]
permissions:
contents: read
jobs:
cancel:
name: Cancel queued runs of this PR
if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
actions: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
sparse-checkout: scripts/ci/cancel-closed-pr-runs.mjs
sparse-checkout-cone-mode: false
- name: Cancel this PR's queued and running workflow runs
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
HEAD_REF: ${{ github.event.pull_request.head.ref }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
SELF_RUN_ID: ${{ github.run_id }}
run: node scripts/ci/cancel-closed-pr-runs.mjs

1888
.github/workflows/ci.yml vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1,54 +0,0 @@
name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
# Least-privilege default: no token permissions at the top level; the `claude` job
# grants exactly what it needs below (Scorecard TokenPermissions).
permissions: {}
jobs:
claude:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
persist-credentials: false
fetch-depth: 1
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
# This is an optional setting that allows Claude to read CI results on PRs
additional_permissions: |
actions: read
# Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it.
# prompt: 'Update the pull request description to include a summary of changes.'
# Optional: Add claude_args to customize behavior and configuration
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
# or https://code.claude.com/docs/en/cli-reference for available options
# claude_args: '--allowed-tools Bash(gh pr *)'

View File

@@ -1,31 +0,0 @@
name: CodeQL
# OWNER ACTION REQUIRED before enabling auto-triggers: advanced CodeQL conflicts with
# GitHub "default setup" — the analyze step fails with "CodeQL analyses from advanced
# configurations cannot be processed when the default setup is enabled". Switch repo
# Settings → Code security → CodeQL from Default to Advanced, THEN restore the
# push/pull_request/schedule triggers below. Until then this only runs on manual dispatch
# so it never produces a red check on PRs. (The codeqlAlerts ratchet keeps working via the
# default setup's alerts in the meantime.)
on:
workflow_dispatch:
permissions:
contents: read
jobs:
analyze:
name: Analyze (javascript-typescript)
runs-on: ubuntu-latest
permissions:
security-events: write
actions: read
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
with:
languages: javascript-typescript
queries: security-extended
- uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
with:
category: "/language:javascript-typescript"

22
.github/workflows/codex-review.yml vendored Normal file
View File

@@ -0,0 +1,22 @@
name: Codex PR Review
on:
pull_request:
types: [opened, synchronize]
jobs:
request-codex-review:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- name: Request Codex Review
uses: actions/github-script@v8
with:
script: |
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
body: '@codex review'
});

View File

@@ -1,98 +0,0 @@
name: DAST smoke (PR)
# PRs into main only since #11946. The job's "Build CLI bundle" step is a backend-only
# `next build`; on the hosted 7 GB runner it fits main's tree (~5.5 min) but dies on
# release/v3.8.51 (VM shutdown ~7 min in, before the server even starts), and because the
# job is continue-on-error the result was a permanently red advisory check on every
# release PR — noise, not signal. DAST coverage for release/** lives on the nightly rail
# (nightly-schemathesis.yml, nightly-llm-security.yml); dispatch this workflow by hand
# to smoke a release branch on demand.
on:
workflow_dispatch:
pull_request:
branches: ["main"]
# Runner-cost guard (#8084): the CLI-bundle build alone is 6-11min; a docs-only PR
# cannot change DAST behavior, so skip the whole workflow for pure docs/markdown
# changes. Any code path in the diff still runs the full smoke.
paths-ignore:
- "docs/**"
- "**/*.md"
permissions:
contents: read
# Superseded runs on the same PR must not stack 25-minute advisory builds
# (force-push storms were holding 2-3 runners each). Same group rule as quality.yml.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
dast-smoke:
runs-on: ubuntu-latest
# ADVISORY while this new gate matures (repo convention: advisory -> blocking).
# Flip to blocking (remove continue-on-error) once it's proven stable across a few PRs.
continue-on-error: true
# Build CLI bundle alone varies 6-11min on GitHub-hosted runners (3 consecutive
# timeouts observed on 2026-07-14 with the old 12min cap killing schemathesis
# mid-run) — 25min leaves real headroom for the actual DAST steps.
timeout-minutes: 25
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-api-key-secret-with-sufficient-length-aaaa
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: "24"
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Build CLI bundle
env:
OMNIROUTE_BUILD_BACKEND_ONLY: "1"
run: npm run build:cli
- name: Start OmniRoute
env:
PORT: "20128"
INJECTION_GUARD_MODE: block
REQUIRE_API_KEY: "false"
run: |
node dist/server.js > server.log 2>&1 &
echo $! > server.pid
for _ in $(seq 1 30); do
if curl -sf http://localhost:20128/api/monitoring/health >/dev/null; then echo up; break; fi
sleep 2
done
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: "3.12"
- run: pip install schemathesis
- name: Schemathesis smoke (high-risk endpoints, blocking)
run: |
# /api/auth/oidc/* is a BROWSER redirect flow (302 to the IdP, 302 back to
# /login?oidc_error=... on every failure), not a REST endpoint: Schemathesis reads
# those 302s as "the API accepted a schema-violating request" and the configured-off
# 400 as "rejected a schema-compliant request". Documenting the flow in the spec is
# still right (operators need it); fuzzing it is not what this smoke is for.
# /api/auth/login has brute-force rate limiting: repeated failed logins return 429,
# which Schemathesis flags as rejection of schema-compliant requests.
schemathesis run docs/openapi.yaml --url http://localhost:20128 \
--include-path-regex '^/v1/(chat/completions|models)$|^/api/(auth|keys)' \
--exclude-path-regex '^/api/auth/(oidc/|login)' \
--max-examples 8 --workers 4 --checks all --max-response-time 30 \
--request-timeout 20 --suppress-health-check all --no-color
- name: Install promptfoo
run: npm install -g promptfoo@0.122.0
- name: promptfoo injection-guard (blocking)
env:
OMNIROUTE_URL: http://localhost:20128
OMNIROUTE_API_KEY: not-needed-blocked-before-upstream
run: promptfoo eval -c promptfooconfig.yaml --no-cache
- name: Stop server
if: always()
run: kill "$(cat server.pid)" || true
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: always()
with:
name: dast-smoke-logs
path: server.log
retention-days: 7

View File

@@ -6,94 +6,39 @@ on:
types: [completed]
workflow_dispatch:
permissions:
contents: read
jobs:
deploy:
if: >-
(github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success')
&& vars.DEPLOY_ENABLED == 'true'
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
name: Deploy OmniRoute to VPS
runs-on: ubuntu-latest
# Bound a hung SSH session to an hour instead of GitHub's 6-hour default; the deploy
# itself fails fast when the VPS is unreachable (run 39101148517: 0 min of work).
timeout-minutes: 60
steps:
- name: Check VPS SSH reachability from runner
id: reach
env:
# Pass the host via env (never interpolate a secret straight into the
# script body) so /dev/tcp gets a shell variable, not inlined text.
VPS_HOST: ${{ secrets.VPS_HOST }}
run: |
set -euo pipefail
# A GitHub-hosted runner can only deploy when it can actually open a TCP
# connection to the VPS SSH port. The Local VPS lives on a private LAN and
# the Akamai host firewalls :22 to known IPs, so the runner is routinely
# unable to reach it. An enabled deployment that cannot start is a failed
# deployment, not success. Keep DEPLOY_ENABLED=false when this runner has
# no authorized route; do not convert a requested deployment into green.
if timeout 15 bash -c 'exec 3<>"/dev/tcp/${VPS_HOST}/22"' 2>/dev/null; then
echo "reachable=true" >> "$GITHUB_OUTPUT"
echo "✅ VPS_HOST:22 reachable from the runner — proceeding with deploy."
else
echo "reachable=false" >> "$GITHUB_OUTPUT"
echo "::error title=Deployment did not start::VPS_HOST:22 is not reachable from this runner. An operator must provide an authorized route or perform a separately authorized deployment."
exit 1
fi
- name: Install Tailscale
uses: tailscale/github-action@v3
with:
oauth-client-id: ""
oauth-secret: ""
tags: tag:ci-deploy
continue-on-error: true
- name: Deploy via SSH
if: steps.reach.outputs.reachable == 'true'
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.VPS_HOST }}
username: ${{ secrets.VPS_USER }}
key: ${{ secrets.VPS_SSH_KEY }}
port: 22
timeout: 60s
command_timeout: 15m
timeout: 30s
script: |
set -euo pipefail
echo "=== Updating OmniRoute ==="
npm install -g omniroute@latest
INSTALLED_VERSION=$(omniroute --version 2>/dev/null | tr -d '[:space:]' || echo "unknown")
echo "Installed CLI version: $INSTALLED_VERSION"
npm install -g omniroute@latest 2>&1
INSTALLED_VERSION=$(omniroute --version 2>/dev/null || echo "unknown")
echo "Installed version: $INSTALLED_VERSION"
# Recreate the PM2 process instead of `pm2 restart`. A bare restart
# re-runs whatever script path was saved earlier; after the build-output
# reorg (app/ -> dist/, .next -> .build/next) a process pinned to the old
# app/server-ws.mjs path can no longer start, and the node process dies
# while PM2 still reports "online" — so the box never binds :20128.
# Always launch via the `omniroute` bin so .env is loaded and the dist/
# layout is resolved correctly.
echo "=== (Re)creating PM2 process via bin ==="
pm2 delete omniroute 2>/dev/null || true
pm2 start omniroute --name omniroute -- --port 20128
echo "=== Restarting PM2 ==="
pm2 restart omniroute || pm2 start omniroute --name omniroute -- --port 20128
pm2 save
# Health gate: fail the deploy unless the box actually reports healthy.
# Poll /api/monitoring/health for "status":"healthy" (a deeper signal than
# a static page 200 — it confirms the app booted, not just that a port is
# bound). Boot can take a while after a native-module/build-layout change,
# so poll up to ~3min before giving up.
echo "=== Health Check (gates the deploy) ==="
ok=0
for i in $(seq 1 36); do
BODY=$(curl -sf -m 5 http://localhost:20128/api/monitoring/health 2>/dev/null || true)
if printf '%s' "$BODY" | grep -q '"status":"healthy"'; then
ok=1
echo "✅ /api/monitoring/health -> healthy (attempt $i) — version $INSTALLED_VERSION"
break
fi
echo "… not healthy yet (attempt $i/36), retrying in 5s"
sleep 5
done
if [ "$ok" != "1" ]; then
echo "❌ Health check failed — /api/monitoring/health never reported healthy after ~3min"
echo "--- recent PM2 logs ---"
pm2 logs omniroute --lines 40 --nostream || true
exit 1
fi
echo "=== Health Check ==="
sleep 3
curl -sf http://localhost:20128/api/settings > /dev/null && echo "✅ OmniRoute is healthy" || echo "❌ Health check failed"
echo "=== Deploy complete ==="

View File

@@ -1,894 +1,51 @@
name: Publish to Docker Hub
on:
push:
branches:
- main
- "release/v*"
tags:
- "v*"
paths-ignore:
- ".github/workflows/**"
# Use 'released' instead of 'published' so editing/re-publishing old releases
# does NOT re-trigger this workflow. 'released' fires only on the initial
# release publication (and pre-release → release transition).
release:
types: [released]
# #14560: nightly re-run exists only to drive the omni-build runner alert below
# (open/close the tracking issue). Publish jobs skip themselves on this event.
schedule:
- cron: "41 4 * * *"
workflow_dispatch:
inputs:
version:
description: "Version tag to build (e.g. 3.8.4)"
required: true
type: string
promote_latest:
description: "Also tag :latest (only if this is the highest semver)"
required: false
type: boolean
default: false
types: [published]
# One publish per ref. A merge storm used to fan out 8 concurrent hosted builds,
# every one OOM-killing `npm run build` inside BuildKit (#11976). The :next
# channel only needs the newest SHA; cancel-in-progress is the same pattern as
# quality.yml / nightly-release-green.
# The nightly `schedule` run (runner-alert only) gets its own group: it runs on the
# default branch ref, so sharing the publish group would let cancel-in-progress kill
# an in-flight release-branch publish every night (#14560 follow-up).
# A push to release/v* must NOT cancel the build already running for that branch (#17230):
# the amd64 image takes ~2 h on the single omni-build runner and the branch merges faster than
# that, so with cancel-in-progress the next/next-web channel went 13 days without an image
# (24 cancelled publishes on 2026-10-19 alone). Without it GitHub still keeps at most one
# running and one pending run per group — an older pending run is replaced by the newest push,
# the in-flight build completes, the latest tip follows. Tags, releases, dispatches and the
# scheduled alert keep cancelling.
concurrency:
group: docker-publish-${{ github.event_name == 'schedule' && 'runner-alert' || github.ref }}
cancel-in-progress: ${{ !(github.event_name == 'push' && startsWith(github.ref, 'refs/heads/release/')) }}
# Least-privilege default: read-only at the top level; the build and merge jobs that
# push to GHCR grant packages: write themselves (Scorecard TokenPermissions).
permissions:
contents: read
jobs:
prepare:
name: Resolve Docker release metadata
permissions:
contents: read
packages: read
# Read this month's docker-publish jobs for the Blacksmith budget step.
actions: read
# Keep the explicit upstream scheduled-run guard on every job, including
# publish jobs that currently exclude schedule entirely.
if: >-
github.event_name != 'schedule' &&
(github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
# With DOCKER_AMD64_RUNNER=blacksmith the small jobs around the build run on Blacksmith as
# well: on 2026-11-03 this job waited 3 h for a hosted ubuntu-latest slot behind ~300 queued
# PR runs. About 2.5 min here plus 4.5 min in `merge` per publish, on 2 vCPU.
runs-on: ${{ vars.DOCKER_AMD64_RUNNER == 'blacksmith' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }}
outputs:
version: ${{ steps.version.outputs.version }}
promote_latest: ${{ steps.version.outputs.promote_latest }}
skip: ${{ steps.version.outputs.skip }}
# 'true' while DOCKER_AMD64_RUNNER=blacksmith and the month's Blacksmith minutes are
# under BLACKSMITH_MONTHLY_MINUTES_CAP; `build` and `merge` route on it.
blacksmith: ${{ steps.budget.outputs.blacksmith }}
env:
IMAGE_NAME: diegosouzapw/omniroute
GHCR_IMAGE_NAME: ghcr.io/cheaper-inference/omniroute
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
# Control scripts come from this workflow ref, not an older release tag.
# The build job below still checks out the requested version's source.
# Shallow: the :latest decision reads tag NAMES from `git ls-remote` below, so the
# 2.6 GB history is not needed. A full clone took 30+ min on a Blacksmith runner
# (outside GitHub's network) on 2026-11-03.
fetch-depth: 1
# Blacksmith keeps running and invoices past its free 3,000 minutes, and a publish costs
# ~90 of them, so the month's usage is summed here and the build falls back to the hosted
# runner at the cap (default 2,500, leaving room for the jobs already in flight).
- name: Stay within the Blacksmith monthly minutes
id: budget
env:
WANT: ${{ vars.DOCKER_AMD64_RUNNER }}
CAP: ${{ vars.BLACKSMITH_MONTHLY_MINUTES_CAP || '2500' }}
REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
SELF_RUN_ID: ${{ github.run_id }}
run: node scripts/ci/blacksmith-budget.mjs
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to GitHub Container Registry
uses: docker/login-action@v4.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Resolve version, latest-promotion, and skip flag
id: version
env:
EVENT_NAME: ${{ github.event_name }}
REF_NAME: ${{ github.ref_name }}
REF_TYPE: ${{ github.ref_type }}
INPUT_VERSION: ${{ inputs.version }}
PROMOTE_INPUT: ${{ inputs.promote_latest }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
run: |
set -euo pipefail
# 1) Resolve version/channel from the trigger. Only the current default
# release branch publishes the mutable `next` channel; main keeps `main`.
VERSION=$(bash scripts/ci/resolve-docker-publish-version.sh \
"$EVENT_NAME" "$REF_TYPE" "$REF_NAME" "$INPUT_VERSION" "$DEFAULT_BRANCH")
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
# Frozen release branches keep receiving coordination commits after the
# next cycle becomes the default branch. They must not overwrite :next,
# but that expected no-op is not a workflow failure.
if [ "$VERSION" = "skip" ]; then
echo "promote_latest=false" >> "$GITHUB_OUTPUT"
echo "skip=true" >> "$GITHUB_OUTPUT"
echo "Skipping Docker publish from non-default release branch: $REF_NAME"
exit 0
fi
# 2) Decide whether to promote :latest. Floating channels are never
# eligible, and the helper independently fails closed for non-semver.
PROMOTE="false"
if [ "$VERSION" = "main" ] || [ "$VERSION" = "next" ]; then
PROMOTE="false"
elif printf '%s' "$VERSION" | grep -qE -- '-(rc|alpha|beta|pre|next)'; then
echo "Pre-release identifier detected — skipping :latest."
PROMOTE="false"
elif [ "$EVENT_NAME" = "workflow_dispatch" ]; then
PROMOTE="${PROMOTE_INPUT:-false}"
else
# Decide via the extracted helper, which folds VERSION into the
# candidate set so the result is independent of git-tag sync timing
# on `release` events (#5301). Without that, the freshly-created tag
# is often not yet visible here and :latest stays a release behind.
# Tag names come straight from the remote (same set `git fetch --tags`
# gave the full clone); under pipefail a failed listing fails the step
# instead of promoting against an empty list.
PROMOTE=$(git ls-remote --tags --refs origin \
| sed -n 's#^[0-9a-f]*[[:space:]]refs/tags/\(v[0-9].*\)$#\1#p' \
| bash scripts/ci/should-promote-latest.sh "$VERSION")
if [ "$PROMOTE" != "true" ]; then
echo "Version $VERSION is not the highest stable semver. Not promoting :latest."
fi
fi
echo "promote_latest=$PROMOTE" >> "$GITHUB_OUTPUT"
# 3) Skip only when the mandatory Node and Web images are complete in BOTH
# registries: an existing Node base must not block repairing a missing Web
# image or architecture. Bun is deliberately not part of this check. It is
# best-effort, so a release with a failing Bun leg, or a historical version
# without Bun tags, must not rebuild (~2 h) on every trigger. workflow_dispatch
# never skips: it is the explicit repair path, Bun tags and stale aliases included.
# Helper exit codes: 1 = missing or incomplete (publish), 2 = could not tell.
SKIP="false"
if [ "$VERSION" != "main" ] && [ "$VERSION" != "next" ] && [ "$EVENT_NAME" != "workflow_dispatch" ]; then
SKIP="true"
for ref in \
"${IMAGE_NAME}:${VERSION}" "${IMAGE_NAME}:${VERSION}-web" \
"${GHCR_IMAGE_NAME}:${VERSION}" "${GHCR_IMAGE_NAME}:${VERSION}-web"; do
rc=0
node scripts/ci/docker-image-complete.mjs "$ref" || rc=$?
if [ "$rc" -eq 1 ]; then
echo "$ref is missing or incomplete — publishing."
SKIP="false"
break
fi
if [ "$rc" -ne 0 ]; then
echo "::error::Could not inspect $ref (registry error, not a missing tag). Not starting a rebuild on an unknown state: re-run this job once the registry recovers, or use workflow_dispatch to force a publish."
exit 1
fi
done
fi
echo "skip=$SKIP" >> "$GITHUB_OUTPUT"
echo "Publishing diegosouzapw/omniroute:$VERSION (promote_latest=$PROMOTE, skip=$SKIP)"
# #14560: when USE_VPS_RUNNER is on, the amd64 leg can ONLY run on the single
# `omni-build` self-hosted listener. If that box is offline, GitHub queues the
# job forever — no error, no timeout (timeout-minutes only starts once a
# runner picks the job up, so it cannot bound queue time) — and the publish
# silently stalls until a human cancels the run. This preflight turns that
# silent queue into a red run within minutes, with the verdict in the job name.
runner-preflight:
name: Preflight — amd64 runner availability
needs: prepare
if: >-
github.event_name != 'schedule' && needs.prepare.outputs.skip != 'true' && vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' &&
vars.DOCKER_AMD64_RUNNER != 'blacksmith' && vars.DOCKER_AMD64_RUNNER != 'hosted' &&
(github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
docker:
name: Build & Push Docker Image
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- name: Check an online runner carries the omni-build label
env:
# Listing self-hosted runners needs the repository "Administration: read"
# permission, which GITHUB_TOKEN can never be granted through `permissions:`.
# RUNNER_STATUS_TOKEN (optional secret: fine-grained PAT with Administration
# read on this repo, or a classic PAT with `repo`) activates the check;
# without it the API answers 403 and the preflight fails OPEN with a
# warning, so a missing/under-scoped token can never block a publish.
GH_TOKEN: ${{ secrets.RUNNER_STATUS_TOKEN || github.token }}
run: |
set -euo pipefail
if ! ONLINE=$(gh api "repos/${GITHUB_REPOSITORY}/actions/runners" \
--paginate --jq '[.runners[] | select(.status == "online") | select(any(.labels[]; .name == "omni-build"))] | length'); then
echo "::warning::Could not list self-hosted runners (token lacks Administration read — set the RUNNER_STATUS_TOKEN secret). Skipping the omni-build availability check."
exit 0
fi
echo "online omni-build runners: ${ONLINE}"
if [ "${ONLINE}" -eq 0 ]; then
echo "::error::No ONLINE runner carries the omni-build label. The amd64 build would queue forever (silent publish stall, #14560)."
echo "Check the self-hosted runner pool, or set DOCKER_AMD64_RUNNER=hosted (or blacksmith) to build amd64 off the .113 slot."
exit 1
fi
build:
name: Build Docker (${{ matrix.platform }})
needs: [prepare, runner-preflight]
# runner-preflight is SKIPPED when USE_VPS_RUNNER is off; a plain `if:` would
# inherit the implicit success() check and skip the whole build with it.
if: >-
!cancelled() && github.event_name != 'schedule' &&
needs.prepare.result == 'success' && needs.prepare.outputs.skip != 'true' &&
(needs.runner-preflight.result == 'success' || needs.runner-preflight.result == 'skipped') &&
(github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
# amd64: the .113 omni-build pool (31 GB / 32 cores, ONE listener since
# #12048). Hosted ubuntu-24.04 is 16 GB; the ~7 GB runners of #11976 died
# ResourceExhausted. Falls back to hosted when USE_VPS_RUNNER is off. arm64: no ARM box — stay
# on GitHub's ubuntu-24.04-arm.
# Webpack on BOTH arches: Turbopack on omniroute-113-6 hit
# TurbopackInternalError "there must be a path to a root" after 26 min
# (run 33253576569). The same tree's arm64 webpack build on hosted ARM
# succeeded (run 33264823398). Dockerfile already documents webpack as the
# Docker escape hatch (OMNIROUTE_USE_TURBOPACK=0).
# DOCKER_AMD64_RUNNER (repository variable) moves the amd64 leg off the .113 slot, which takes
# 90-165 min per publish while the same build on a 16 GB / 4 vCPU hosted runner takes 20-45:
# blacksmith → blacksmith-4vcpu-ubuntu-2404 (16 GB; needs the Blacksmith app on the org; the
# free tier is 3,000 2-vCPU minutes a month and a 4 vCPU minute counts as two)
# hosted → ubuntu-24.04 (16 GB)
# unset → unchanged: omni-build when the .113 opt-in is on, hosted otherwise
# The Dockerfile build is sized for 16 GB (OMNIROUTE_BUILD_WORKERS, #7518).
# `blacksmith` routes through prepare's budget output; at the monthly cap it lands on hosted.
runs-on: ${{ matrix.arch == 'amd64' && (needs.prepare.outputs.blacksmith == 'true' && 'blacksmith-4vcpu-ubuntu-2404' || vars.DOCKER_AMD64_RUNNER != 'hosted' && vars.DOCKER_AMD64_RUNNER != 'blacksmith' && vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && fromJSON('["self-hosted","omni-build"]') || 'ubuntu-24.04') || 'ubuntu-24.04-arm' }}
# Share the 1-slot omni-build ceiling (#12048) with ci.yml `Build` /
# npm-publish. Same group as main's Build so a :next publish waits beside
# the artefact instead of sitting next to it. arm64 is hosted — its own
# group, cancelled by the workflow-level concurrency. An amd64 leg moved by
# DOCKER_AMD64_RUNNER does not hold the slot, so it gets a per-ref group.
concurrency:
group: ${{ matrix.arch == 'amd64' && (vars.DOCKER_AMD64_RUNNER != 'blacksmith' && vars.DOCKER_AMD64_RUNNER != 'hosted' && 'heavy-build-main' || format('docker-publish-amd64-{0}', github.ref)) || format('docker-publish-arm-{0}', github.ref) }}
cancel-in-progress: ${{ matrix.arch != 'amd64' }}
# Backstop for a hung BUILD step only — it cannot and must not bound the
# queue wait (that is runner-preflight's job): the clock starts when a
# runner accepts the job. 350 min = the ~2h50m observed webpack build plus
# headroom, so a wedged Docker/BuildKit step fails loudly instead of
# holding the single omni-build slot until someone notices.
timeout-minutes: 350
permissions:
contents: read
packages: write
strategy:
fail-fast: false
matrix:
include:
- platform: linux/amd64
arch: amd64
- platform: linux/arm64
arch: arm64
env:
IMAGE_NAME: diegosouzapw/omniroute
GHCR_IMAGE_NAME: ghcr.io/cheaper-inference/omniroute
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/tags/v{0}', inputs.version) || '' }}
# .dockerignore drops .git, so the image build never reads history.
fetch-depth: 1
uses: actions/checkout@v6
- name: Assert Docker Engine
run: docker info
- name: Extract version from release tag
id: version
run: |
VERSION="${GITHUB_REF_NAME}"
VERSION="${VERSION#v}"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "Publishing Docker image version: $VERSION"
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v4.6.0
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v4.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# Heap for the webpack build inside BuildKit: 12288 MB on every build-args block below.
# Validated on the hosted runners (16 GB) by the publishes of 2026-10-16/17 — runs
# 38904652365, 38907575198 and 39010473398, amd64 and arm64 green (27-55 min). It stays
# at or above build.yml's native webpack floor (10240 MB), never below it
# (tests/unit/docker-publish-build-heap-14325.test.ts).
- name: Build and push platform image by digest
id: build
uses: docker/build-push-action@v7
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
target: runner-base
platforms: ${{ matrix.platform }}
build-args: |
OMNIROUTE_USE_TURBOPACK=0
OMNIROUTE_BUILD_MEMORY_MB=12288
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
push: true
tags: |
${{ env.IMAGE_NAME }}
${{ env.GHCR_IMAGE_NAME }}
cache-from: type=gha,scope=docker-${{ matrix.arch }}
cache-to: type=gha,scope=docker-${{ matrix.arch }},mode=max,ignore-error=true
no-cache: false
env:
DOCKER_BUILDKIT_INLINE_CACHE: 1
- name: Build and push WEB platform image by digest
id: build-web
uses: docker/build-push-action@v7
with:
context: .
target: runner-web
platforms: ${{ matrix.platform }}
build-args: |
OMNIROUTE_USE_TURBOPACK=0
OMNIROUTE_BUILD_MEMORY_MB=12288
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
tags: |
${{ env.IMAGE_NAME }}
${{ env.GHCR_IMAGE_NAME }}
# runner-web extends runner-base: reuse this run's base build as well
# as the previous Web cache, without mixing Node/Bun or architectures.
cache-from: |
type=gha,scope=docker-web-${{ matrix.arch }}
type=gha,scope=docker-${{ matrix.arch }}
cache-to: type=gha,scope=docker-web-${{ matrix.arch }},mode=max,ignore-error=true
no-cache: false
env:
DOCKER_BUILDKIT_INLINE_CACHE: 1
# Check the binaries in both final Node images on each native architecture,
# before their digests can reach the multi-arch manifest/promotion job.
- name: Verify published Node runtimes
env:
DIGEST_BASE: ${{ steps.build.outputs.digest }}
DIGEST_WEB: ${{ steps.build-web.outputs.digest }}
PLATFORM: ${{ matrix.platform }}
run: |
set -euo pipefail
for digest in "$DIGEST_BASE" "$DIGEST_WEB"; do
image="${GHCR_IMAGE_NAME}@${digest}"
echo "Verifying Node runtime in ${image} (${PLATFORM})"
docker run --rm --pull always --platform "$PLATFORM" --entrypoint node -i \
"$image" --input-type=module < scripts/ci/check-docker-node-runtime.mjs
done
# The mandatory digests leave this job BEFORE any Bun step starts, so nothing Bun
# does can stop them from being exported and uploaded (#11724, #11740, #17223).
- name: Export digests
env:
DIGEST_BASE: ${{ steps.build.outputs.digest }}
DIGEST_WEB: ${{ steps.build-web.outputs.digest }}
run: |
set -euo pipefail
# Self-hosted runners keep /tmp across runs: start empty so digests of
# earlier runs are never uploaded (#15184).
rm -rf /tmp/digests
mkdir -p /tmp/digests/base /tmp/digests/web
touch "/tmp/digests/base/${DIGEST_BASE#sha256:}"
touch "/tmp/digests/web/${DIGEST_WEB#sha256:}"
- name: Upload base digests
uses: actions/upload-artifact@v7
with:
name: digests-base-${{ matrix.arch }}
path: /tmp/digests/base/*
if-no-files-found: error
retention-days: 1
- name: Upload web digests
uses: actions/upload-artifact@v7
with:
name: digests-web-${{ matrix.arch }}
path: /tmp/digests/web/*
if-no-files-found: error
retention-days: 1
- name: Build and push BUN base platform image by digest
id: build-bun-base
# Bun is a best-effort compatibility target, not a supported runtime
# (AGENTS.md -> Environment). Its `bun run build` has been OOM-killing on
# both arches; letting that sink the whole publish means the SUPPORTED
# runner-base / runner-web images never reach the registry either. The
# merge job publishes a Bun tag only when both architectures produced a
# valid digest, so a failure here costs that tag and nothing else.
continue-on-error: true
# A step limit, because reaching the job's 350 min limit fails the job and the
# merge job then publishes nothing. Observed amd64 Bun base: 57 min (2026-11-02).
timeout-minutes: 80
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7
with:
context: .
file: Dockerfile.bun
target: runner-base
platforms: ${{ matrix.platform }}
build-args: |
OMNIROUTE_USE_TURBOPACK=0
OMNIROUTE_BUILD_MEMORY_MB=12288
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
tags: |
${{ env.IMAGE_NAME }}
${{ env.GHCR_IMAGE_NAME }}
cache-from: type=gha,scope=docker-bun-base-${{ matrix.arch }}
cache-to: type=gha,scope=docker-bun-base-${{ matrix.arch }},mode=max,ignore-error=true
no-cache: false
env:
DOCKER_BUILDKIT_INLINE_CACHE: 1
- name: Build and push BUN web platform image by digest
id: build-bun-web
# Best-effort, same as the Bun base step above.
continue-on-error: true
timeout-minutes: 80
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7
with:
context: .
file: Dockerfile.bun
target: runner-web
platforms: ${{ matrix.platform }}
build-args: |
OMNIROUTE_USE_TURBOPACK=0
OMNIROUTE_BUILD_MEMORY_MB=12288
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
tags: |
${{ env.IMAGE_NAME }}
${{ env.GHCR_IMAGE_NAME }}
cache-from: |
type=gha,scope=docker-bun-web-${{ matrix.arch }}
type=gha,scope=docker-bun-base-${{ matrix.arch }}
cache-to: type=gha,scope=docker-bun-web-${{ matrix.arch }},mode=max,ignore-error=true
no-cache: false
env:
DOCKER_BUILDKIT_INLINE_CACHE: 1
- name: Export Bun digests
continue-on-error: true
env:
DIGEST_BUN_BASE: ${{ steps.build-bun-base.outputs.digest }}
DIGEST_BUN_WEB: ${{ steps.build-bun-web.outputs.digest }}
run: |
set -euo pipefail
mkdir -p /tmp/digests/bun-base /tmp/digests/bun-web
# Empty when the (non-blocking) bun build produced no image. `if` blocks,
# not `[ -n ] && touch`: under `set -e` a failing AND-list aborts the step,
# which is precisely the case being handled here.
if [ -n "$DIGEST_BUN_BASE" ]; then
touch "/tmp/digests/bun-base/${DIGEST_BUN_BASE#sha256:}"
else
echo "::warning::Bun base build produced no digest on this architecture: no -bun tag this run."
fi
if [ -n "$DIGEST_BUN_WEB" ]; then
touch "/tmp/digests/bun-web/${DIGEST_BUN_WEB#sha256:}"
else
echo "::warning::Bun web build produced no digest on this architecture: no -web-bun tag this run."
fi
- name: Upload bun-base digests
# continue-on-error: a failed upload would otherwise fail the job and the merge
# job would then skip the mandatory images too. `ignore`, not `error`: an absent
# digest is the expected outcome of a failed bun image.
continue-on-error: true
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: digests-bun-base-${{ matrix.arch }}
path: /tmp/digests/bun-base/*
if-no-files-found: ignore
retention-days: 1
- name: Upload bun-web digests
# Same as the bun-base upload above.
continue-on-error: true
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: digests-bun-web-${{ matrix.arch }}
path: /tmp/digests/bun-web/*
if-no-files-found: ignore
retention-days: 1
merge:
name: Publish multi-arch manifests
needs:
- prepare
- build
# Explicit results, like `build`: an implicit success() also looks at `build`'s own
# dependency runner-preflight, which is SKIPPED whenever amd64 is off the omni-build slot
# (DOCKER_AMD64_RUNNER, USE_VPS_RUNNER off), and that silently skipped this job after both
# images built (run 41703618029, 2026-11-03).
if: >-
!cancelled() && github.event_name != 'schedule' &&
needs.prepare.result == 'success' && needs.build.result == 'success' &&
needs.prepare.outputs.skip != 'true' &&
(github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
# On Blacksmith with the amd64 build; on hosted once the monthly budget is spent.
runs-on: ${{ needs.prepare.outputs.blacksmith == 'true' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }}
permissions:
contents: read
packages: write
security-events: write
env:
IMAGE_NAME: diegosouzapw/omniroute
GHCR_IMAGE_NAME: ghcr.io/cheaper-inference/omniroute
VERSION: ${{ needs.prepare.outputs.version }}
PROMOTE_LATEST: ${{ needs.prepare.outputs.promote_latest }}
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
# Manifest validation must use the current workflow's helper on backfills.
# Manifests, smoke test and scans read no git history.
fetch-depth: 1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4.6.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v4.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Download base digests
uses: actions/download-artifact@v8
with:
pattern: digests-base-*
path: /tmp/digests/base
merge-multiple: true
- name: Download web digests
uses: actions/download-artifact@v8
with:
pattern: digests-web-*
path: /tmp/digests/web
merge-multiple: true
- name: Download bun-base digests
# Non-blocking: the bun image is best-effort, so its artifact may not
# exist at all. The guard below decides whether its tag is published.
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
pattern: digests-bun-base-*
path: /tmp/digests/bun-base
merge-multiple: true
- name: Download bun-web digests
# Non-blocking: the bun image is best-effort, so its artifact may not
# exist at all. The guard below decides whether its tag is published.
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
pattern: digests-bun-web-*
path: /tmp/digests/bun-web
merge-multiple: true
- name: Guard against stale digests
id: digests
run: |
set -euo pipefail
# Validate every flavor in both registries BEFORE moving any public tag.
# Counting alone cannot distinguish two AMD64 images from AMD64 + ARM64.
pair_is_valid() {
local dir="$1" image digest_file
local refs
for image in "$IMAGE_NAME" "$GHCR_IMAGE_NAME"; do
refs=()
while IFS= read -r digest_file; do
refs+=("${image}@sha256:$(basename "$digest_file")")
done < <(find "$dir" -type f | sort)
node scripts/ci/docker-image-complete.mjs "${refs[@]}" || return 1
done
}
# Node and Web are mandatory: anything but a valid pair stops the publish.
for dir in base web; do
if [ ! -d "/tmp/digests/$dir" ]; then
echo "Missing digest directory: $dir" >&2
exit 1
fi
count=$(find "/tmp/digests/$dir" -type f | wc -l)
if [ "$count" -gt 2 ] || [ "$count" -lt 2 ]; then
echo "digests in $dir: found $count, expected exactly 2 (amd64 + arm64)" >&2
exit 1
fi
if ! pair_is_valid "/tmp/digests/$dir"; then
echo "digests in $dir: the pair is not one linux/amd64 + one linux/arm64 in both registries" >&2
exit 1
fi
done
# Bun is best-effort but all-or-nothing per flavor: both architectures valid
# in both registries publish the tag; anything else warns and publishes none.
for dir in bun-base bun-web; do
problem=""
if [ ! -d "/tmp/digests/$dir" ]; then
problem="no digests"
else
count=$(find "/tmp/digests/$dir" -type f | wc -l)
if [ "$count" -gt 2 ] || [ "$count" -lt 2 ]; then
problem="found $count digests, expected exactly 2 (amd64 + arm64)"
elif ! pair_is_valid "/tmp/digests/$dir"; then
problem="the pair is not one linux/amd64 + one linux/arm64 in both registries"
fi
fi
publish="true"
if [ -n "$problem" ]; then
publish="false"
echo "::warning::Not publishing the $dir image: $problem. Bun is best-effort; the Node and Web images are unaffected."
fi
echo "publish_${dir//-/_}=$publish" >> "$GITHUB_OUTPUT"
done
- name: Create Docker Hub version manifests
env:
PUBLISH_BUN_BASE: ${{ steps.digests.outputs.publish_bun_base }}
PUBLISH_BUN_WEB: ${{ steps.digests.outputs.publish_bun_web }}
run: |
set -euo pipefail
create_manifest() {
local image="$1" suffix="$2" dir="$3"
local refs=()
while IFS= read -r digest_file; do
refs+=("${image}@sha256:$(basename "$digest_file")")
done < <(find "$dir" -type f | sort)
node scripts/ci/docker-image-complete.mjs "${refs[@]}" || return 1
docker buildx imagetools create -t "${image}:${VERSION}${suffix}" "${refs[@]}" || return 1
}
# A failed Bun manifest warns and never stops the mandatory tags.
create_bun_manifest() {
local publish="$1" image="$2" suffix="$3" dir="$4"
if [ "$publish" != "true" ]; then
return 0
fi
if ! create_manifest "$image" "$suffix" "$dir"; then
echo "::warning::Could not publish ${image}:${VERSION}${suffix}. Bun is best-effort; continuing."
fi
}
create_manifest "${IMAGE_NAME}" "" /tmp/digests/base
create_manifest "${IMAGE_NAME}" "-web" /tmp/digests/web
create_bun_manifest "${PUBLISH_BUN_BASE:-false}" "${IMAGE_NAME}" "-bun" /tmp/digests/bun-base
create_bun_manifest "${PUBLISH_BUN_WEB:-false}" "${IMAGE_NAME}" "-web-bun" /tmp/digests/bun-web
- name: Create GHCR version manifests
env:
PUBLISH_BUN_BASE: ${{ steps.digests.outputs.publish_bun_base }}
PUBLISH_BUN_WEB: ${{ steps.digests.outputs.publish_bun_web }}
run: |
set -euo pipefail
create_manifest() {
local image="$1" suffix="$2" dir="$3"
local refs=()
while IFS= read -r digest_file; do
refs+=("${image}@sha256:$(basename "$digest_file")")
done < <(find "$dir" -type f | sort)
node scripts/ci/docker-image-complete.mjs "${refs[@]}" || return 1
docker buildx imagetools create -t "${image}:${VERSION}${suffix}" "${refs[@]}" || return 1
}
# A failed Bun manifest warns and never stops the mandatory tags.
create_bun_manifest() {
local publish="$1" image="$2" suffix="$3" dir="$4"
if [ "$publish" != "true" ]; then
return 0
fi
if ! create_manifest "$image" "$suffix" "$dir"; then
echo "::warning::Could not publish ${image}:${VERSION}${suffix}. Bun is best-effort; continuing."
fi
}
create_manifest "${GHCR_IMAGE_NAME}" "" /tmp/digests/base
create_manifest "${GHCR_IMAGE_NAME}" "-web" /tmp/digests/web
create_bun_manifest "${PUBLISH_BUN_BASE:-false}" "${GHCR_IMAGE_NAME}" "-bun" /tmp/digests/bun-base
create_bun_manifest "${PUBLISH_BUN_WEB:-false}" "${GHCR_IMAGE_NAME}" "-web-bun" /tmp/digests/bun-web
- name: Smoke-test published Docker image
if: needs.prepare.outputs.version != 'main'
run: |
set -euo pipefail
container="omniroute-smoke-${VERSION//[^a-zA-Z0-9_.-]/-}"
trap 'docker rm -f "$container" >/dev/null 2>&1 || true' EXIT
docker run --detach --name "$container" "${IMAGE_NAME}:${VERSION}"
for attempt in $(seq 1 30); do
status="$(docker inspect --format '{{.State.Health.Status}}' "$container")"
if [ "$status" = "healthy" ]; then
exit 0
fi
if [ "$status" = "unhealthy" ] || [ "$(docker inspect --format '{{.State.Status}}' "$container")" = "exited" ]; then
docker logs "$container"
exit 1
fi
sleep 2
done
docker logs "$container"
exit 1
- name: Promote Docker Hub latest tags
if: needs.prepare.outputs.promote_latest == 'true'
env:
PUBLISH_BUN_BASE: ${{ steps.digests.outputs.publish_bun_base }}
PUBLISH_BUN_WEB: ${{ steps.digests.outputs.publish_bun_web }}
run: |
set -euo pipefail
promote_tag() {
local suffix="$1"
docker buildx imagetools create -t "${IMAGE_NAME}:latest${suffix}" "${IMAGE_NAME}:${VERSION}${suffix}"
}
# Validate every source before promoting any flavor. The mandatory tags must be
# complete; a Bun alias moves only for a complete tag published by this run.
for suffix in "" -web; do
node scripts/ci/docker-image-complete.mjs "${IMAGE_NAME}:${VERSION}${suffix}"
done
bun_aliases=()
add_bun_alias() {
local publish="$1" suffix="$2"
if [ "$publish" = "true" ] && node scripts/ci/docker-image-complete.mjs "${IMAGE_NAME}:${VERSION}${suffix}"; then
bun_aliases+=("$suffix")
else
echo "::warning::Not promoting ${IMAGE_NAME}:latest${suffix}: this run has no complete Bun image for it."
fi
}
add_bun_alias "${PUBLISH_BUN_BASE:-false}" -bun
add_bun_alias "${PUBLISH_BUN_WEB:-false}" -web-bun
for suffix in "" -web; do
promote_tag "$suffix"
done
for suffix in "${bun_aliases[@]}"; do
promote_tag "$suffix" || echo "::warning::Could not promote ${IMAGE_NAME}:latest${suffix}. Bun is best-effort; continuing."
done
- name: Promote GHCR latest tags
if: needs.prepare.outputs.promote_latest == 'true'
env:
PUBLISH_BUN_BASE: ${{ steps.digests.outputs.publish_bun_base }}
PUBLISH_BUN_WEB: ${{ steps.digests.outputs.publish_bun_web }}
run: |
set -euo pipefail
promote_tag() {
local suffix="$1"
docker buildx imagetools create -t "${GHCR_IMAGE_NAME}:latest${suffix}" "${GHCR_IMAGE_NAME}:${VERSION}${suffix}"
}
for suffix in "" -web; do
node scripts/ci/docker-image-complete.mjs "${GHCR_IMAGE_NAME}:${VERSION}${suffix}"
done
bun_aliases=()
add_bun_alias() {
local publish="$1" suffix="$2"
if [ "$publish" = "true" ] && node scripts/ci/docker-image-complete.mjs "${GHCR_IMAGE_NAME}:${VERSION}${suffix}"; then
bun_aliases+=("$suffix")
else
echo "::warning::Not promoting ${GHCR_IMAGE_NAME}:latest${suffix}: this run has no complete Bun image for it."
fi
}
add_bun_alias "${PUBLISH_BUN_BASE:-false}" -bun
add_bun_alias "${PUBLISH_BUN_WEB:-false}" -web-bun
for suffix in "" -web; do
promote_tag "$suffix"
done
for suffix in "${bun_aliases[@]}"; do
promote_tag "$suffix" || echo "::warning::Could not promote ${GHCR_IMAGE_NAME}:latest${suffix}. Bun is best-effort; continuing."
done
- name: Inspect image
if: needs.prepare.outputs.version != 'main'
run: |
docker buildx imagetools inspect "${IMAGE_NAME}:${VERSION}"
- name: Generate CycloneDX SBOM (image, advisory)
if: needs.prepare.outputs.version != 'main'
continue-on-error: true
uses: anchore/sbom-action@v0
with:
image: ${{ env.GHCR_IMAGE_NAME }}:${{ env.VERSION }}
format: cyclonedx-json
output-file: sbom-image.cdx.json
artifact-name: sbom-image.cdx.json
# Visibility scan: reports HIGH + CRITICAL into the SARIF (Security tab) but
# never blocks (exit-code 0). The blocking gate below narrows to CRITICAL.
#
# ignore-unfixed mirrors the blocking gate: the Security tab must surface only
# ACTIONABLE vulnerabilities — ones with a published fix we can pull by rebuilding
# on a patched base or bumping the dep. Without it the advisory upload floods the
# tab with unfixable base-image OS CVEs (Debian trixie packages with no upstream
# patch yet, overwhelmingly local-only and not reachable from the proxy request
# surface), which is noise an operator cannot act on. trivyignores points at the
# repo-root .trivyignore so accepted-risk fixable CVEs have one auditable home.
# See docs/security/SUPPLY_CHAIN.md.
- name: Trivy image scan (SARIF, advisory)
if: needs.prepare.outputs.version != 'main'
continue-on-error: true
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
image-ref: ${{ env.GHCR_IMAGE_NAME }}:${{ env.VERSION }}
format: sarif
output: trivy-results.sarif
severity: HIGH,CRITICAL
ignore-unfixed: true
trivyignores: .trivyignore
exit-code: "0"
# BLOCKING gate (v3.8.27 cycle-end): fail the release on a CRITICAL CVE in the
# published image. Narrowed to severity CRITICAL (HIGH stays visible in the
# SARIF step above, not blocking). ignore-unfixed:true so an unfixable base-image
# CVE with no upstream patch does not red the release (reduces false-blocks);
# a fixable CRITICAL still blocks. Per docs/security/SUPPLY_CHAIN.md. NB: Trivy
# scans against a CVE DB that grows continuously — a newly-disclosed CRITICAL on
# an unchanged base image can red this gate; the fix is to rebuild on a patched
# base, bump the dep, or add a justified .trivyignore entry (see the CVE-variance
# note in docs/security/SUPPLY_CHAIN.md).
- name: Trivy CRITICAL gate (blocking)
if: needs.prepare.outputs.version != 'main'
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
image-ref: ${{ env.GHCR_IMAGE_NAME }}:${{ env.VERSION }}
format: table
severity: CRITICAL
ignore-unfixed: true
exit-code: "1"
# Explicit: the advisory scan above already points at it, and the blocking
# gate must honour the same accepted-risk list (#12084).
trivyignores: .trivyignore
- name: Upload Trivy SARIF to Security tab
if: needs.prepare.outputs.version != 'main'
continue-on-error: true
uses: github/codeql-action/upload-sarif@v4.39.1
with:
sarif_file: trivy-results.sarif
category: trivy-image
diegosouzapw/omniroute:${{ steps.version.outputs.version }}
diegosouzapw/omniroute:latest
cache-from: type=gha
cache-to: type=gha,mode=max
platforms: linux/amd64
- name: Update Docker Hub description
# Only refresh README/description when we actually promote :latest
# (avoids overwriting from main, next, or back-fill builds).
if: needs.prepare.outputs.promote_latest == 'true'
uses: peter-evans/dockerhub-description@v5
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
@@ -896,66 +53,3 @@ jobs:
repository: diegosouzapw/omniroute
short-description: "OmniRoute — Unified AI proxy. Route any LLM through one endpoint."
readme-filepath: ./README.md
# #14560: alert when the only omni-build runner goes offline. Mirrors the
# nightly-release-green issue loop: open a deduplicated tracking issue when
# no online runner carries the label, comment with fresh evidence while it
# persists, and auto-close it when the pool recovers. Without this, an
# offline box is only discovered the next time a publish silently stalls.
runner-alert:
name: omni-build runner offline alert
if: >-
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') &&
vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' &&
(github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
issues: write
steps:
- name: Open/update/close the tracking issue
env:
# Issue writes use GITHUB_TOKEN (issues: write); only the runner listing
# needs RUNNER_STATUS_TOKEN (see runner-preflight). Without it the check is
# skipped with a warning instead of opening/closing the issue on bad data.
GH_TOKEN: ${{ github.token }}
RUNNERS_TOKEN: ${{ secrets.RUNNER_STATUS_TOKEN || github.token }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
TITLE="Docker publish runner offline: no online omni-build runner"
if ! ONLINE=$(GH_TOKEN="$RUNNERS_TOKEN" gh api "repos/${GITHUB_REPOSITORY}/actions/runners" \
--paginate --jq '[.runners[] | select(.status == "online") | select(any(.labels[]; .name == "omni-build"))] | length'); then
echo "::warning::Could not list self-hosted runners (token lacks Administration read — set the RUNNER_STATUS_TOKEN secret). Alert skipped."
exit 0
fi
echo "online omni-build runners: ${ONLINE}"
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title ${TITLE}" --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ "${ONLINE}" -eq 0 ]; then
{
echo "No **online** runner carries the \`omni-build\` label (\`GET /repos/{owner}/{repo}/actions/runners\`)."
echo ""
echo "While this persists, every Docker publish with \`USE_VPS_RUNNER=true\` queues the amd64 build forever - the silent stall from #14560 (the runner-preflight job turns it into a red run at publish time; this issue is the standing signal between publishes)."
echo ""
echo "**Checked:** ${RUN_URL} at \`$(date -u +%Y-%m-%dT%H:%M:%SZ)\`"
echo ""
echo "_Auto-managed by the Publish to Docker Hub schedule - closes itself when a runner comes back online._"
} > issue-body.md
if [ -n "$EXISTING" ]; then
gh issue comment "$EXISTING" --repo "$GITHUB_REPOSITORY" --body-file issue-body.md
echo "Updated existing issue #$EXISTING"
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --body-file issue-body.md
echo "Created tracking issue"
fi
elif [ -n "$EXISTING" ]; then
gh issue close "$EXISTING" --repo "$GITHUB_REPOSITORY" --reason completed \
--comment "OK: ${ONLINE} online \`omni-build\` runner(s) - pool recovered. Auto-closed."
echo "Closed issue #$EXISTING"
else
echo "Pool healthy (${ONLINE} online), nothing to do"
fi

View File

@@ -1,572 +0,0 @@
name: Build Electron Desktop App
on:
push:
tags:
- "v*"
# A dispatch builds the ref it is dispatched ON (`gh workflow run … --ref v3.8.50` rebuilds
# that tag; `--ref main` builds the repaired line). The ref is deliberately NOT an input:
# CodeQL flags an input-controlled checkout next to the npm cache on the default branch as
# cache poisoning (actions/cache-poisoning/poisonable-step), and `github.ref` is trusted.
workflow_dispatch:
inputs:
version:
description: "Release version (e.g., v1.6.8)"
required: true
type: string
publish_npm:
description: "Also run the npm publish leg (turn off when re-attaching desktop assets to a release whose npm package already shipped)"
required: false
default: true
type: boolean
# Least-privilege default: read-only at the top level; each job grants the writes it
# needs (build/release upload assets, publish-npm forwards npm provenance / packages
# to the reusable workflow) — Scorecard TokenPermissions.
permissions:
contents: read
jobs:
validate:
name: Validate version
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
version: ${{ steps.validate.outputs.version }}
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
persist-credentials: false
fetch-depth: 0
- name: Validate version format
id: validate
env:
# Pass workflow context via env (never interpolate ${{ ... }} straight
# into the run: script body) so the shell receives variables, not
# inlined text — zizmor template-injection mitigation. INPUT_VERSION is
# the operator-supplied value and is regex-validated below before use.
EVENT_NAME: ${{ github.event_name }}
INPUT_VERSION: ${{ inputs.version }}
run: |
if [[ "$EVENT_NAME" == "push" ]]; then
VERSION="${GITHUB_REF#refs/tags/}"
else
VERSION="$INPUT_VERSION"
fi
if [[ ! "$VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Error: Invalid version format. Expected: v1.6.8"
exit 1
fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "✓ Valid version: $VERSION"
web-build:
name: Build shared Next standalone
needs: validate
# Stage 8 (issue #10321): the four desktop legs used to each run the full
# `npm run build` (Next standalone) — ~111 runner-minutes per release just to
# produce the same platform-independent bundle four times. This job builds it
# once on ubuntu; every leg then restores the byte-verified archive and
# re-forks its native optionals (scripts/build/standaloneBundle.mjs).
#
# Rollback lever: set the repo variable ELECTRON_SHARED_STANDALONE=disabled.
# This job then skips, every leg falls back to building its own web bundle
# (the legacy step below), and the pipeline behaves exactly like pre-Stage 8 —
# no revert needed.
if: ${{ !cancelled() && needs.validate.result == 'success' && vars.ELECTRON_SHARED_STANDALONE != 'disabled' }}
runs-on: ubuntu-latest
permissions:
contents: read
actions: read # find + download the CI run's next-build artifact for this SHA (as npm-publish does)
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Setup Node
uses: actions/setup-node@v7
with:
node-version: 24
- name: Install dependencies
run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
NPM_CONFIG_LEGACY_PEER_DEPS: true
# The Next standalone is platform-independent, and `ci.yml` already built it for this
# exact commit on the omni-build runner (the `next-build` artifact every `main` push
# produces — the release squash included). Reusing it is what `npm-publish.yml` does
# (#8941): the hosted build below needs 18–20 GB and this runner has 16, which is why
# the legacy per-leg fallback cost 53 min on macOS-intel and 4h41 on macOS arm64 for
# v3.8.52. Only runs of THIS repository's CI are candidates (artifact-poisoning guard,
# as in npm-publish); a missing/expired artifact falls back to the full build.
- name: Reuse CI's next-build artifact for this commit
id: reuse
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
HEAD_SHA: ${{ github.sha }}
REPO: ${{ github.repository }}
run: |
set -uo pipefail
CANDIDATES=$(gh api "repos/$REPO/actions/runs?head_sha=$HEAD_SHA&per_page=100" \
--jq '[.workflow_runs[]
| select(.name == "CI"
and .head_repository.full_name == env.REPO)]
| sort_by(.run_started_at) | reverse | .[0:5] | .[].id') || CANDIDATES=""
if [ -z "$CANDIDATES" ]; then
echo "::notice::no CI run from this repository for $HEAD_SHA — building the standalone here"
exit 0
fi
for candidate in $CANDIDATES; do
if gh run download "$candidate" --repo "$REPO" --name next-build --dir "$RUNNER_TEMP/next-build" 2>/dev/null; then
tar -xzf "$RUNNER_TEMP/next-build/e2e-build.tar.gz" -C .
rm -rf "$RUNNER_TEMP/next-build"
if [ -f .build/next/standalone/server.js ]; then
echo "reused=true" >> "$GITHUB_OUTPUT"
echo "✓ reused next-build from CI run $candidate"
exit 0
fi
echo " run $candidate unpacked without .build/next/standalone/server.js — trying the next"
rm -rf .build/next
else
echo " run $candidate carries no usable next-build — trying the next"
fi
done
echo "::notice::none of the candidate runs still carries next-build (1-day retention) — building the standalone here"
- name: Build Next.js standalone (fallback when no CI artifact)
if: steps.reuse.outputs.reused != 'true'
# webpack, not Turbopack, for the same hosted-runner RAM reason as the
# linux leg (see the long comment on the fallback step in `build`).
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
NODE_OPTIONS: "--max_old_space_size=6144"
OMNIROUTE_USE_TURBOPACK: "0"
run: npm run build
- name: Pack standalone bundle
# Deterministic tar.gz + byte-level manifest; the manifest embeds the
# archive's own sha256 so artifact-transfer corruption is caught before
# extraction, and every entry is re-verified after extraction.
run: node scripts/build/standaloneBundle.mjs pack --out web-bundle.tar.gz
- name: Upload shared web bundle
uses: actions/upload-artifact@v7
with:
name: web-standalone-bundle
# compression-level 0: the payload is already a deterministic tar.gz;
# re-zipping would only burn runner CPU without shrinking it further.
compression-level: 0
# Legs consume this within minutes; no reason to retain it like the
# installer artifacts (default 90d).
retention-days: 3
path: |
web-bundle.tar.gz
web-bundle.tar.gz.manifest.json
build:
name: Build Electron (${{ matrix.platform }})
needs: [validate, web-build]
# `web-build` is skipped when ELECTRON_SHARED_STANDALONE=disabled (rollback
# mode); legs then run the legacy per-leg web build below. If it ran and
# failed, fail closed: legs cannot package without the bundle, and silently
# falling back to four per-leg builds would hide exactly the regression the
# shared job exists to surface.
if: ${{ !cancelled() && needs.validate.result == 'success' && (needs.web-build.result == 'success' || needs.web-build.result == 'skipped') }}
runs-on: ${{ matrix.runner }}
permissions:
contents: write # electron-builder may publish artifacts with GH_TOKEN
strategy:
fail-fast: false
matrix:
include:
- platform: windows
runner: windows-latest
target: win
ext: .exe
os: win32
arch: x64
- platform: macos-intel
runner: macos-15-intel
target: mac-x64
ext: .dmg
os: darwin
arch: x64
- platform: macos-arm64
runner: macos-latest
target: mac-arm64
ext: -arm64.dmg
os: darwin
arch: arm64
- platform: linux
runner: ubuntu-latest
target: linux
ext: .AppImage
deb_ext: .deb
os: linux
arch: x64,arm64
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Setup Node
uses: actions/setup-node@v7
with:
node-version: 24
cache: npm
- name: Install dependencies
run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
NPM_CONFIG_LEGACY_PEER_DEPS: true
# The Linux leg produces x64 + arm64 installers from one x64 runner. npm
# deliberately installs only host-compatible optional dependencies, so
# hydrateNativeDeps cannot source the arm64 fork unless we fetch the exact
# package pinned in package-lock before either build path runs.
- name: Install Linux arm64 wreq binding for cross-package
if: matrix.platform == 'linux'
shell: bash
run: |
npm install --no-save --ignore-scripts --force --legacy-peer-deps \
@wreq-js/binding-linux-arm64-gnu@3.2.0
git diff --exit-code -- package.json package-lock.json
mkdir -p "$RUNNER_TEMP/omniroute-wreq-verify"
DATA_DIR="$RUNNER_TEMP/omniroute-wreq-verify" node --import tsx/esm --test \
--test-name-pattern='wreq-js 3.2 manifest pins all nine' \
tests/unit/wreq-native-manifest.test.ts
- name: Sanitize Windows home directory
if: runner.os == 'Windows'
shell: bash
run: |
# The default USERPROFILE contains junction points (Application Data)
# that cause EPERM errors during Next.js standalone build glob scans.
# Create a clean temp profile directory to avoid this.
mkdir -p "$RUNNER_TEMP/home"
echo "USERPROFILE=$RUNNER_TEMP/home" >> "$GITHUB_ENV"
- name: Build Next.js standalone (legacy per-leg fallback)
# Stage 8: only runs in rollback mode (ELECTRON_SHARED_STANDALONE=disabled)
# or when the shared web-build job was skipped. Otherwise the leg restores
# the shared bundle from the `web-build` job below.
if: needs.web-build.result == 'skipped'
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
NODE_OPTIONS: "--max_old_space_size=6144"
# Linux builds with webpack, not Turbopack. Turbopack's production build
# allocates natively (Rust, off the V8 heap), so --max_old_space_size does
# not bound it, and on this module graph it peaks above what the hosted
# runner can give — the VM is reclaimed mid-compile with "The runner has
# received a shutdown signal", no exit code. That is what silently took the
# whole desktop channel out of v3.8.49: the linux leg died, `release` was
# skipped, and the release shipped with ZERO assets. Measured on a 32 GB
# box the same build passes and peaks past 14 GB. The webpack fallback is
# the project's documented escape hatch for RAM-constrained machines
# (docs/reference/ENVIRONMENT.md, #6409) and is the same remedy already
# applied to nightly-compat's Node 26 build (#8090).
OMNIROUTE_USE_TURBOPACK: ${{ matrix.platform == 'linux' && '0' || '1' }}
run: npm run build
- name: Download shared web bundle
# Stage 8: inverse of the fallback step above — runs exactly when the
# shared `web-build` job produced the bundle.
if: needs.web-build.result == 'success'
uses: actions/download-artifact@v8
with:
name: web-standalone-bundle
- name: Restore + hydrate shared web bundle
if: needs.web-build.result == 'success'
shell: bash
# restore: verify the archive's sha256 against the manifest, extract, then
# re-verify every entry (existence + size + content hash + symlink
# targets, and no unlisted files) byte-for-byte.
# hydrate: the bundle was built on ubuntu, so install-machine-forked native
# optionals (@img/sharp-*, @img/sharp-libvips-*, @ngrok/ngrok-*,
# @wreq-js/binding-*, fsevents) carry linux forks. Replace them with the forks this
# leg's own `npm ci` resolved, then assert every bundled native
# (better-sqlite3 prebuilds, wreq-js, onnxruntime)
# can service this leg's platform/arch before packaging starts.
run: |
node scripts/build/standaloneBundle.mjs restore --archive web-bundle.tar.gz
node scripts/build/standaloneBundle.mjs hydrate --platform ${{ matrix.os }} --arch ${{ matrix.arch }}
- name: Sync version in electron/package.json
shell: bash
env:
# Pass the validated version via env (never interpolate ${{ ... }}
# straight into the run: script body) — zizmor template-injection
# mitigation. Already regex-validated (^v[0-9]+\.[0-9]+\.[0-9]+$) in
# the `validate` job, so it cannot carry shell metacharacters.
VERSION: ${{ needs.validate.outputs.version }}
run: |
VERSION_NO_V="${VERSION#v}"
node -e "
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('electron/package.json'));
pkg.version = '$VERSION_NO_V';
fs.writeFileSync('electron/package.json', JSON.stringify(pkg, null, 2) + '\\n');
"
echo "✓ electron/package.json version set to $VERSION_NO_V"
- name: Install fpm (Linux .deb packaging tool)
if: matrix.platform == 'linux'
run: sudo gem install fpm --no-document
- name: Install Electron dependencies
working-directory: electron
run: npm ci --no-audit --no-fund
- name: Build Electron for ${{ matrix.platform }}
working-directory: electron
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: npm run build:${{ matrix.target }}
- name: Smoke packaged Electron app
if: matrix.platform != 'linux'
# Best-effort smoke on Windows + macos-arm64:
# - Windows: requestSingleInstanceLock() fails due to USERPROFILE
# sanitization needed for the build step.
# - macos-arm64: the headless GitHub arm64 runner crashes Electron's GPU
# process (gpu_process_host exit_code=15 → network service crash →
# "No rendezvous client, terminating process"), so the app can't bind
# 127.0.0.1:20128 in time. The identical bundle is smoke-gated on
# macos-intel + linux, so packaging is still verified per-OS; we don't
# let the arm64 runner's GPU flakiness block the desktop release.
continue-on-error: ${{ matrix.platform == 'windows' || matrix.platform == 'macos-arm64' }}
env:
ELECTRON_SMOKE_TIMEOUT_MS: 60000
ELECTRON_SMOKE_STREAM_LOGS: "1"
run: npm run electron:smoke:packaged
- name: Smoke packaged Electron app (Linux)
if: matrix.platform == 'linux'
# #7592: also cold-restart against the same DATA_DIR and assert a
# native SQLite driver (not the sql.js WASM fallback) is selected on
# the second launch — blocking here since Linux has no Windows-style
# sandbox caveats that would make it flaky.
env:
ELECTRON_SMOKE_TIMEOUT_MS: 60000
ELECTRON_SMOKE_STREAM_LOGS: "1"
ELECTRON_SMOKE_COLD_RESTART: "1"
run: xvfb-run -a npm run electron:smoke:packaged
- name: Collect installers
shell: bash
run: |
mkdir -p release-assets
cd electron/dist-electron
# Copy only installer files for this platform
for file in *${{ matrix.ext }}; do
[ -f "$file" ] && cp "$file" ../../release-assets/
done
# Linux: also copy .deb package
if [ "${{ matrix.platform }}" = "linux" ]; then
for file in *.deb; do
[ -f "$file" ] && cp "$file" ../../release-assets/
done
fi
# Windows: also copy portable standalone exe as OmniRoute.exe
if [ "${{ matrix.platform }}" = "windows" ]; then
for file in *.exe; do
# Skip the NSIS installer (contains "Setup")
case "$file" in *Setup*) continue ;; esac
[ -f "$file" ] && cp "$file" "../../release-assets/OmniRoute.exe" && break
done
fi
# electron-updater manifests (latest.yml / latest-mac.yml / latest-linux.yml)
# must be published alongside the installers, or autoUpdater fails with
# "Cannot find latest.yml in the latest release artifacts" (#6766).
for file in latest*.yml; do
[ -f "$file" ] && cp "$file" ../../release-assets/
done
# Publish exactly the content-addressed packs named by this build.
cd ../..
node scripts/release/collect-optional-packs.mjs \
.build/electron-standalone/optional-packs.index.json \
.build/optional-packs release-assets
- name: Upload artifacts
uses: actions/upload-artifact@v7
with:
name: electron-${{ matrix.platform }}
path: release-assets/
release:
name: Create Release
needs: [validate, build]
# Fail-partial, not fail-closed. `build` is a 4-leg matrix with `fail-fast: false`,
# so the legs that succeed still upload their artifacts — but a default `needs:`
# gate skips this job the moment ANY leg fails, discarding all of them. That is
# exactly what happened to v3.8.49: the linux leg died and the release shipped with
# ZERO assets, throwing away 1.7 GB of good Windows/macOS installers **and** the
# source archives + SBOM, which do not depend on a build at all. The result was
# indistinguishable from "this version has no desktop channel".
# Now: attach everything that did build, then fail the job loudly (see the last
# step) so an incomplete channel is visible instead of silent.
if: ${{ !cancelled() && needs.validate.result == 'success' }}
runs-on: ubuntu-latest
permissions:
contents: write # softprops/action-gh-release creates the GitHub Release
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
fetch-depth: 0
# `merge-multiple` is deliberately OFF. It resolves same-name collisions by ARRIVAL
# ORDER, and the two macOS jobs each emit their own `latest-mac.yml` listing only their
# own dmg (measured: 338 and 350 bytes, different content, identical name). One silently
# overwrote the other — arm64 won in the published v3.8.48, and since the Intel dmg
# carries no arch suffix in its name, electron-updater's
# `files.find(url includes process.arch) ?? files.shift()` sends every Intel Mac to the
# ARM dmg. Downloading into per-artifact subdirectories keeps both, so they can be
# merged on purpose instead of by luck.
- name: Download all artifacts
uses: actions/download-artifact@v8
with:
path: artifacts
# Writes release-assets/latest-mac.yml with BOTH dmgs, un-suffixed entry first (that is
# the one electron-updater can only reach through its fallback). Refuses to write when the
# inputs disagree on version — a manifest stitched from two builds is worse than none.
- name: Merge the per-arch macOS updater manifests
run: node scripts/release/merge-mac-update-manifest.mjs artifacts release-assets
# Everything else moves across as-is. The partial latest-mac.yml files are excluded so
# they cannot clobber the merged one; -n is a second belt on the same braces.
- name: Collect the remaining artifacts
run: |
mkdir -p release-assets
find artifacts -type f ! -name latest-mac.yml -exec cp -n {} release-assets/ \;
echo "release-assets:"
ls -la release-assets/
- name: Create source archives
env:
# Pass the validated version via env (never interpolate ${{ ... }}
# straight into the run: script body) — zizmor template-injection
# mitigation. Already regex-validated (^v[0-9]+\.[0-9]+\.[0-9]+$) in
# the `validate` job, so it cannot carry shell metacharacters.
VERSION: ${{ needs.validate.outputs.version }}
run: |
# Create source code archives (excluding dev dependencies and build artifacts)
export TARBALL="OmniRoute-${VERSION}.source.tar.gz"
export ZIPBALL="OmniRoute-${VERSION}.source.zip"
# Use git archive for clean source export
git archive --format=tar.gz --prefix="OmniRoute-${VERSION}/" HEAD -o "release-assets/$TARBALL"
git archive --format=zip --prefix="OmniRoute-${VERSION}/" HEAD -o "release-assets/$ZIPBALL"
echo "✓ Created source archives:"
ls -lh "release-assets/$TARBALL" "release-assets/$ZIPBALL"
- name: List release files
run: ls -la release-assets/
- name: Create Release
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ needs.validate.outputs.version }}
draft: false
prerelease: false
# NEVER. Phase 3 of the release flow creates the GitHub Release with the curated
# notes seconds after pushing the tag, so by the time this step runs (1-2 h of
# builds later) the body already exists — and `true` APPENDS GitHub's
# auto-generated "What's Changed" block to it (v3.8.48 shipped that way; the
# v3.8.50 re-attach dispatch added +1,416 chars to a 121 KB body, run
# 33238093090). A curated body sits ~3 KB under the 125,000-char cap, so the
# append can also turn this step RED and leave the release with no assets.
generate_release_notes: false
fail_on_unmatched_files: false
files: |
release-assets/*.dmg
release-assets/*.exe
release-assets/*.AppImage
release-assets/*.deb
release-assets/*.blockmap
release-assets/*.yml
release-assets/optional-pack-*.tar.gz
release-assets/*.source.tar.gz
release-assets/*.source.zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
verify-desktop-assets:
name: Verify desktop assets landed
needs: [validate, release]
# Deliberately a SEPARATE job, not a final step of `release`: failing inside
# `release` would cascade into `publish-npm` (which gates on `needs: release`) and
# block the npm channel over a desktop-only gap. Here the assets are attached, npm
# still publishes, and an incomplete desktop channel shows up as a red job instead
# of passing unnoticed — the v3.8.49 release had ZERO assets and every gate was
# green, because nothing ever asserted the release HAS binaries.
if: ${{ !cancelled() && needs.release.result == 'success' }}
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Assert every platform is present on the release
env:
# Regex-validated (^v[0-9]+\.[0-9]+\.[0-9]+$) in the `validate` job, and
# passed via env rather than interpolated into the script body.
VERSION: ${{ needs.validate.outputs.version }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
names=$(gh release view "$VERSION" --repo "$GITHUB_REPOSITORY" \
--json assets --jq '.assets[].name')
echo "Assets on $VERSION:"
echo "$names" | sed 's/^/ /'
missing=""
# `[ ... ] && missing=...` as the last command in a branch returns 1 and
# would abort the whole script under Actions' default `set -e`. Use if/fi.
for want in '\.exe$' '\.dmg$' '\.AppImage$' '\.deb$' '^latest.*\.yml$' '\.source\.tar\.gz$'; do
if ! echo "$names" | grep -qE "$want"; then
missing="$missing $want"
fi
done
if [ -n "$missing" ]; then
echo "::error::Desktop channel incomplete on $VERSION — no asset matching:$missing"
exit 1
fi
echo "✓ every platform present on $VERSION"
publish-npm:
name: Publish to npm
needs: [validate, release]
# A re-dispatch that only re-attaches desktop assets must not publish the npm package again.
if: ${{ github.event_name != 'workflow_dispatch' || inputs.publish_npm }}
permissions:
# Must be `write`, not `read`: this job calls the reusable npm-publish.yml whose
# `publish` job needs `contents: write` (gh release upload — attach the SBOM, #3874).
# A reusable workflow's job cannot request more permission than the caller grants,
# so a `read` here makes GitHub reject the run at startup (startup_failure).
#
# `actions: read` for the same reason: the called `publish` job downloads the next-build
# artefact and requests it. v3.8.50 (run 33005490476) died at startup with "The nested
# job 'publish' is requesting 'actions: read', but is only allowed 'actions: none'" — and
# because `release` lives in this same workflow, the tag shipped with ZERO assets. Keep
# this block a superset of every job's permissions in npm-publish.yml.
actions: read
contents: write
id-token: write # npm provenance (forwarded to the reusable workflow)
packages: write # publish to npm.pkg.github.com
uses: ./.github/workflows/npm-publish.yml
with:
version: ${{ needs.validate.outputs.version }}
tag: latest
secrets:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

View File

@@ -1,156 +0,0 @@
name: Forward-port stable/v3 → develop (dormant)
# DORMANT until the 3.9.0 LTS cut creates `stable/v3` and `develop`
# (docs/ops/RELEASE_STRATEGY.md → "Forward-port"). The push filter and the job
# `if:` both pin it to `refs/heads/stable/v3`, and the job exits quietly while
# `develop` does not exist.
#
# Every commit pushed to stable/v3 is cherry-picked (`-x`) onto a fresh
# `forward-port/<sha7>` branch cut from develop, and a PR is opened against
# develop. The original author stays the commit author and is also credited with
# a `Co-authored-by:` trailer, so the credit survives a squash-merge of the
# forward-port PR. A conflicting cherry-pick still opens a PR — as a DRAFT with
# the exact commands to finish it by hand.
#
# PRs opened with the default GITHUB_TOKEN do not trigger other workflows; set the
# `FORWARD_PORT_TOKEN` secret (fine-grained PAT or App token with contents +
# pull-requests write) before go-live so CI runs on the forward-port PRs.
on:
push:
branches: [stable/v3]
workflow_dispatch:
inputs:
sha:
description: "Commit on stable/v3 to forward-port (full or short SHA)"
required: true
type: string
permissions:
contents: read
concurrency:
group: forward-port
cancel-in-progress: false
jobs:
forward-port:
name: Cherry-pick onto develop
if: github.ref == 'refs/heads/stable/v3' && github.repository == 'cheaper-inference/OmniRoute'
runs-on: ubuntu-latest
permissions:
contents: write # push forward-port/<sha7>
pull-requests: write # open the PR against develop
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Check that develop exists
id: develop
run: |
set -euo pipefail
if [ -n "$(git ls-remote --heads origin develop)" ]; then
echo "exists=true" >> "$GITHUB_OUTPUT"
else
echo "exists=false" >> "$GITHUB_OUTPUT"
echo "develop does not exist yet — forward-port is dormant, nothing to do."
fi
- name: Resolve commits to forward-port
id: commits
if: steps.develop.outputs.exists == 'true'
env:
EVENT_NAME: ${{ github.event_name }}
BEFORE: ${{ github.event.before }}
AFTER: ${{ github.sha }}
INPUT_SHA: ${{ inputs.sha }}
run: |
set -euo pipefail
if [ "$EVENT_NAME" = "workflow_dispatch" ]; then
if ! printf '%s' "$INPUT_SHA" | grep -qE '^[0-9a-fA-F]{7,40}$'; then
echo "Refusing non-SHA input: $INPUT_SHA" >&2
exit 1
fi
TARGET=$(git rev-parse --verify "${INPUT_SHA}^{commit}")
git merge-base --is-ancestor "$TARGET" origin/stable/v3 \
|| { echo "$TARGET is not on stable/v3" >&2; exit 1; }
RANGE="${TARGET}^..${TARGET}"
elif printf '%s' "$BEFORE" | grep -qE '^0+$' || [ -z "$BEFORE" ]; then
RANGE="${AFTER}^..${AFTER}"
else
RANGE="${BEFORE}..${AFTER}"
fi
git rev-list --reverse --no-merges "$RANGE" > commits.txt
echo "count=$(wc -l < commits.txt | tr -d ' ')" >> "$GITHUB_OUTPUT"
echo "Commits to forward-port:"; cat commits.txt
- name: Cherry-pick and open PRs
if: steps.develop.outputs.exists == 'true' && steps.commits.outputs.count != '0'
env:
GH_TOKEN: ${{ secrets.FORWARD_PORT_TOKEN || github.token }}
REPO: ${{ github.repository }}
STRATEGY_URL: ${{ github.server_url }}/${{ github.repository }}/blob/develop/docs/ops/RELEASE_STRATEGY.md
run: |
set -euo pipefail
gh auth setup-git
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
while read -r SHA; do
SHORT="${SHA:0:7}"
BRANCH="forward-port/${SHORT}"
if [ -n "$(git ls-remote --heads origin "$BRANCH")" ]; then
echo "$BRANCH already exists — skipping $SHORT."
continue
fi
SUBJECT=$(git log -1 --format=%s "$SHA")
AUTHOR=$(git log -1 --format='%an <%ae>' "$SHA")
git checkout --quiet -B "$BRANCH" origin/develop
DRAFT=""
if git cherry-pick -x "$SHA"; then
# Keep the original author (cherry-pick already does) AND add the trailer,
# so a squash-merge of this PR still credits them.
git log -1 --format=%B > msg.txt
git interpret-trailers --in-place --if-exists addIfDifferent \
--trailer "Co-authored-by: ${AUTHOR}" msg.txt
git commit --amend --quiet --file msg.txt
BODY_STATE="Clean cherry-pick (\`git cherry-pick -x\`) of ${SHA} from \`stable/v3\`."
else
git cherry-pick --abort
DRAFT="--draft"
printf 'chore(forward-port): %s needs a manual cherry-pick\n\nCherry-pick of %s from stable/v3 conflicted on develop.\n\nCo-authored-by: %s\n' \
"$SHORT" "$SHA" "$AUTHOR" > msg.txt
git commit --allow-empty --quiet --file msg.txt
BODY_STATE=$(printf '%s\n\n%s\n\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n' \
"⚠️ **The cherry-pick of ${SHA} conflicted on \`develop\`** — this draft holds an empty placeholder commit." \
"To finish it:" \
'```bash' \
"git fetch origin" \
"git switch ${BRANCH}" \
"git cherry-pick -x ${SHA} # resolve the conflicts, then: git cherry-pick --continue" \
"git commit --amend # keep the trailer: Co-authored-by: ${AUTHOR}" \
"git push origin ${BRANCH}" \
'```')
fi
git push --quiet origin "HEAD:refs/heads/${BRANCH}"
{
echo "Automatic forward-port of \`stable/v3\` → \`develop\`."
echo
echo "$BODY_STATE"
echo
echo "Original author: ${AUTHOR}"
echo
echo "Policy: ${STRATEGY_URL}"
} > body.md
# shellcheck disable=SC2086 # DRAFT is intentionally empty or one flag
gh pr create --repo "$REPO" --base develop --head "$BRANCH" $DRAFT \
--title "${SUBJECT} (forward-port ${SHORT})" \
--body-file body.md \
--label forward-port
done < commits.txt

View File

@@ -1,334 +0,0 @@
name: i18n mirror refresh
# Post-merge refresh of the translated docs mirrors (docs/i18n/<locale>/…). Since #18420 the
# docs drift gate is advisory on PRs and the merge train, so drifted mirrors pile up on the
# release branch until somebody runs `npm run i18n:run` by hand. This workflow does that run
# on a schedule and turns the result into ONE pull request:
#
# 1. target = the highest release/v* branch (or the `base` input); skipped with a notice while
# an open `release-freeze` issue names that branch (Hard Rule #21);
# 2. drifted sources = `check-translation-drift.mjs --json --warn` (drifted, missing,
# hand-edited and stale mirrors);
# 3. translate them: the LLM chain first when the backend secrets are configured (model, then
# OMNIROUTE_TRANSLATION_FALLBACK_MODELS, then a re-split, then Google as the last resort),
# otherwise the structure-safe Google engine alone;
# 4. `npm run check:docs-all` + the drift check must both pass; then the mirrors are committed
# to the fixed branch `chore/i18n-mirror-refresh` (force-reset from the target every run)
# and one PR is opened, or the open one is updated by the force-push;
# 5. a partial translation (run-translation exit 3: some (source, locale) units failed, the
# rest translated) still opens the PR with the translated mirrors. The failed units keep
# their mirror and state record, the drift check excuses exactly those units, and the PR
# body lists them for the next run (#18538);
# 6. a run where nothing translated, any other translation error, or any other check failure
# opens NO PR and fails the job with a step summary that lists the failing files / locales.
#
# PRs opened with the default GITHUB_TOKEN do not trigger other workflows (no CI on the refresh
# PR). Set the `I18N_REFRESH_TOKEN` secret (fine-grained PAT or App token with contents +
# pull-requests write) so CI runs on it, the same pattern as FORWARD_PORT_TOKEN in
# forward-port.yml. With GITHUB_TOKEN the repo setting "Allow GitHub Actions to create and
# approve pull requests" must be on for `gh pr create` to work.
#
# Operator configuration (all optional; without the LLM ones the Google engine is used):
# secrets.OMNIROUTE_TRANSLATION_API_KEY LLM backend bearer token
# secrets/vars.OMNIROUTE_TRANSLATION_API_URL OpenAI-compatible base URL (…/v1)
# vars.OMNIROUTE_TRANSLATION_MODEL first model of the chain
# vars.OMNIROUTE_TRANSLATION_FALLBACK_MODELS comma-separated fallback chain
# secrets.OMNIROUTE_TRANSLATION_GOOGLE_API_KEY official Cloud Translation v2 instead of the
# keyless web endpoint
# secrets.I18N_REFRESH_TOKEN token that opens the PR (see above)
#
# Secrets only ever reach the scripts through `env:`; no `${{ }}` expression is interpolated into
# a `run:` script.
on:
schedule:
- cron: "23 */6 * * *"
workflow_dispatch:
inputs:
base:
description: "Branch to refresh (default: the highest release/v* branch)"
required: false
type: string
permissions:
contents: read
concurrency:
group: i18n-mirror-refresh
cancel-in-progress: false
jobs:
refresh:
name: Refresh drifted docs mirrors
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
timeout-minutes: 330
permissions:
contents: write # push chore/i18n-mirror-refresh
pull-requests: write # open / retarget the refresh PR
env:
REFRESH_BRANCH: chore/i18n-mirror-refresh
PR_TITLE: "docs(i18n): refresh drifted mirrors (scheduled)"
steps:
- name: Resolve the target branch and the release freeze
id: target
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
INPUT_BASE: ${{ inputs.base }}
run: |
set -euo pipefail
if [ -n "${INPUT_BASE:-}" ]; then
if ! printf '%s' "$INPUT_BASE" | grep -qE '^[A-Za-z0-9._/-]+$'; then
echo "::error::refusing base input with unexpected characters" >&2
exit 1
fi
BASE="$INPUT_BASE"
else
BASE=$(gh api --paginate "repos/$REPO/git/matching-refs/heads/release/v" --jq '.[].ref' \
| sed 's#^refs/heads/##' | grep -E '^release/v[0-9]+\.[0-9]+\.[0-9]+$' \
| sort -V | tail -1)
fi
if [ -z "$BASE" ]; then
echo "::error::could not resolve the target branch" >&2
exit 1
fi
echo "base=$BASE" >> "$GITHUB_OUTPUT"
# Hard Rule #21: never refresh a frozen release branch. A freeze issue is titled
# "🔒 release-freeze: vX.Y.Z in progress"; one that names no version freezes everything.
VER="${BASE#release/}"
VER_RE=$(printf '%s' "$VER" | sed 's/\./\\./g')
FROZEN=""
while IFS=$'\t' read -r NUM TITLE; do
[ -n "$NUM" ] || continue
if printf '%s' "$TITLE" | grep -qE "(^|[^0-9.])${VER_RE}([^0-9]|$)" \
|| ! printf '%s' "$TITLE" | grep -qE 'v[0-9]+\.[0-9]+\.[0-9]+'; then
FROZEN="#$NUM"
fi
done < <(gh issue list --repo "$REPO" --label release-freeze --state open \
--json number,title --jq '.[] | "\(.number)\t\(.title)"')
if [ -n "$FROZEN" ]; then
echo "::notice::$BASE is under release-freeze ($FROZEN) — skipping the mirror refresh."
echo "Skipped: \`$BASE\` is under release-freeze ($FROZEN)." >> "$GITHUB_STEP_SUMMARY"
echo "skip=true" >> "$GITHUB_OUTPUT"
else
echo "skip=false" >> "$GITHUB_OUTPUT"
echo "Target branch: \`$BASE\`" >> "$GITHUB_STEP_SUMMARY"
fi
- name: Checkout the target branch
if: steps.target.outputs.skip == 'false'
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ steps.target.outputs.base }}
fetch-depth: 1
persist-credentials: false
- name: Find the drifted sources
id: drift
if: steps.target.outputs.skip == 'false'
run: |
set -euo pipefail
node scripts/i18n/check-translation-drift.mjs --json --warn > "$RUNNER_TEMP/drift-before.json"
# every source with a drifted / missing / hand-edited / stale mirror, as repo-relative paths
FILES=$(DRIFT_JSON="$RUNNER_TEMP/drift-before.json" node -e '
const r = JSON.parse(require("fs").readFileSync(process.env.DRIFT_JSON, "utf8"));
const keys = ["driftedSources", "missingTargets", "driftedTargets", "staleTargets"];
const rels = keys.flatMap((k) => r[k] ?? [])
.map((x) => x.rel).filter(Boolean);
process.stdout.write([...new Set(rels)].sort().join(","));
')
if [ -z "$FILES" ]; then
echo "No drifted mirrors — nothing to refresh." >> "$GITHUB_STEP_SUMMARY"
echo "files=" >> "$GITHUB_OUTPUT"
else
echo "Drifted sources: \`${FILES//,/\`, \`}\`" >> "$GITHUB_STEP_SUMMARY"
echo "files=$FILES" >> "$GITHUB_OUTPUT"
fi
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
if: steps.drift.outputs.files != ''
with:
package-manager-cache: false
node-version: "24"
- uses: ./.github/actions/npm-ci-retry
if: steps.drift.outputs.files != ''
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Translate the drifted mirrors
id: translate
if: steps.drift.outputs.files != ''
env:
FILES: ${{ steps.drift.outputs.files }}
OMNIROUTE_TRANSLATION_API_KEY: ${{ secrets.OMNIROUTE_TRANSLATION_API_KEY }}
OMNIROUTE_TRANSLATION_API_URL: ${{ secrets.OMNIROUTE_TRANSLATION_API_URL || vars.OMNIROUTE_TRANSLATION_API_URL }}
OMNIROUTE_TRANSLATION_MODEL: ${{ vars.OMNIROUTE_TRANSLATION_MODEL }}
OMNIROUTE_TRANSLATION_FALLBACK_MODELS: ${{ vars.OMNIROUTE_TRANSLATION_FALLBACK_MODELS }}
OMNIROUTE_TRANSLATION_GOOGLE_API_KEY: ${{ secrets.OMNIROUTE_TRANSLATION_GOOGLE_API_KEY }}
run: |
set -uo pipefail
if [ -n "$OMNIROUTE_TRANSLATION_API_KEY" ] && [ -n "$OMNIROUTE_TRANSLATION_API_URL" ] \
&& [ -n "$OMNIROUTE_TRANSLATION_MODEL" ]; then
ENGINE=llm
else
ENGINE=google
if [ -n "$OMNIROUTE_TRANSLATION_API_KEY" ] || [ -n "$OMNIROUTE_TRANSLATION_API_URL" ]; then
echo "::warning::LLM backend partially configured (API key, API URL and vars.OMNIROUTE_TRANSLATION_MODEL are all required) — using Google."
fi
fi
export OMNIROUTE_TRANSLATION_ENGINE="$ENGINE"
export OMNIROUTE_TRANSLATION_GOOGLE_FALLBACK=1
echo "engine=$ENGINE" >> "$GITHUB_OUTPUT"
echo "Engine: \`$ENGINE\`" >> "$GITHUB_STEP_SUMMARY"
# The default `bash -e` would end the step on a non-zero pipeline before RC is read, so
# catch the status here (pipefail makes it the translator's exit code).
RC=0
node scripts/i18n/run-translation.mjs --files="$FILES" \
--failures-json="$RUNNER_TEMP/translate-failures.json" 2>&1 \
| tee "$RUNNER_TEMP/translate.log" || RC=$?
if [ "$RC" -eq 3 ]; then
# Partial: the translated units are written and recorded, the failed ones are untouched.
echo "partial=true" >> "$GITHUB_OUTPUT"
{
echo "### Partial translation (exit 3): failed locales left as they were"
echo
echo '```'
grep -E '^ - .+ \[[^]]+\]: ' "$RUNNER_TEMP/translate.log" | head -100 || true
grep -E 'summary: translated=' "$RUNNER_TEMP/translate.log" | tail -1 || true
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
elif [ "$RC" -ne 0 ]; then
{
echo "### Translation failed (exit $RC) — no PR opened"
echo
echo '```'
grep -E '^ - .+ \[[^]]+\]: ' "$RUNNER_TEMP/translate.log" | head -100 || true
grep -E 'summary: translated=' "$RUNNER_TEMP/translate.log" | tail -1 || true
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
exit "$RC"
fi
- name: Check the refreshed mirrors
if: steps.drift.outputs.files != ''
run: |
set -uo pipefail
FAILED=0
npm run check:docs-all 2>&1 | tee "$RUNNER_TEMP/docs-all.log"
DOCS_RC=${PIPESTATUS[0]}
node scripts/i18n/check-translation-drift.mjs --json --warn > "$RUNNER_TEMP/drift-after.json"
# Drift left by the failed units of a partial run is excused; any other drift blocks.
if ! BLOCKING=$(DRIFT_JSON="$RUNNER_TEMP/drift-after.json" \
FAILURES_JSON="$RUNNER_TEMP/translate-failures.json" node --input-type=module -e '
import { existsSync, readFileSync } from "node:fs";
import { blockingDrift } from "./scripts/i18n/run-translation.mjs";
const read = (p) => JSON.parse(readFileSync(p, "utf8"));
const run = existsSync(process.env.FAILURES_JSON) ? read(process.env.FAILURES_JSON) : {};
const left = blockingDrift(read(process.env.DRIFT_JSON), run.failures ?? [], run.translatedUnits ?? []);
for (const x of left) console.log(x.kind + ": " + x.rel + (x.locale ? " [" + x.locale + "]" : ""));
'); then
echo "::error::could not evaluate the drift report"
exit 1
fi
if [ "$DOCS_RC" -ne 0 ]; then
FAILED=1
{
echo "### \`npm run check:docs-all\` failed (exit $DOCS_RC) — no PR opened"
echo
echo '```'
grep -E 'docs/i18n/|FAIL|✗|✖|ERROR' "$RUNNER_TEMP/docs-all.log" | head -100 || true
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
fi
if [ -n "$BLOCKING" ]; then
FAILED=1
{
echo "### Drift check still reports drift — no PR opened"
echo
echo '```'
printf '%s\n' "$BLOCKING" | head -100
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
fi
exit "$FAILED"
- name: Commit and open or update the refresh PR
if: steps.drift.outputs.files != ''
env:
GH_TOKEN: ${{ secrets.I18N_REFRESH_TOKEN || github.token }}
REPO: ${{ github.repository }}
BASE: ${{ steps.target.outputs.base }}
ENGINE: ${{ steps.translate.outputs.engine }}
PARTIAL: ${{ steps.translate.outputs.partial }}
FILES: ${{ steps.drift.outputs.files }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
git add -A docs/i18n .i18n-state.json
if git diff --cached --quiet; then
echo "Translation produced no change — nothing to commit." >> "$GITHUB_STEP_SUMMARY"
exit 0
fi
COUNT=$(git diff --cached --name-only -- docs/i18n | wc -l | tr -d ' ')
FAILED_UNITS=""
if [ "${PARTIAL:-}" = "true" ]; then
FAILED_UNITS=$(FAILURES_JSON="$RUNNER_TEMP/translate-failures.json" node -e '
const r = JSON.parse(require("fs").readFileSync(process.env.FAILURES_JSON, "utf8"));
const one = (e) => String(e ?? "").replace(/\s+/g, " ").replace(/`/g, "\x27").slice(0, 200);
for (const f of r.failures) console.log("- `" + f.rel + "` [" + f.locale + "]: " + one(f.error));
')
fi
NOTE=""
[ -z "$FAILED_UNITS" ] || NOTE=" $(printf '%s\n' "$FAILED_UNITS" | wc -l | tr -d ' ') unit(s) failed and were left as they were."
# CI bot commit: the bot identity is the author, no Co-Authored-By trailer.
git -c user.name="github-actions[bot]" \
-c user.email="41898282+github-actions[bot]@users.noreply.github.com" \
commit --quiet -m "$PR_TITLE" \
-m "Engine: ${ENGINE}. Sources: ${FILES//,/, }. ${COUNT} mirror file(s).${NOTE}" \
-m "Run: ${RUN_URL}"
gh auth setup-git
# Fixed branch, reset from the target on every run: the open PR always shows exactly
# one refresh commit on top of the current target.
git push --force --quiet origin "HEAD:refs/heads/${REFRESH_BRANCH}"
{
echo "Automatic refresh of the translated docs mirrors, opened by the \`i18n-mirror-refresh\` workflow (${RUN_URL})."
echo
echo "- Target: \`${BASE}\`"
echo "- Engine: \`${ENGINE}\` (LLM chain first, Google as the last resort; \`google\` when no LLM backend is configured)"
echo "- Drifted sources: \`${FILES//,/\`, \`}\`"
echo "- Mirror files changed: ${COUNT}"
echo
echo "\`npm run check:docs-all\` and \`check-translation-drift.mjs\` passed on the refreshed tree before this PR was opened."
if [ -n "$FAILED_UNITS" ]; then
echo
echo "Partial run: these (source, locale) units failed to translate. Their mirrors and \`.i18n-state.json\` records are unchanged, so they still show as stale or drifted and the next run retries them. The drift check excused only these units:"
echo
printf '%s\n' "$FAILED_UNITS"
fi
echo
echo "The branch \`${REFRESH_BRANCH}\` is force-reset from the target on every run, so a later run replaces this commit."
echo "PRs opened with the default \`GITHUB_TOKEN\` do not trigger other workflows; set the \`I18N_REFRESH_TOKEN\` secret so CI runs here."
} > "$RUNNER_TEMP/pr-body.md"
PR=$(gh pr list --repo "$REPO" --head "$REFRESH_BRANCH" --state open \
--json number,baseRefName --jq '.[0] | select(.) | "\(.number) \(.baseRefName)"')
if [ -z "$PR" ]; then
URL=$(gh pr create --repo "$REPO" --base "$BASE" --head "$REFRESH_BRANCH" \
--title "$PR_TITLE" --body-file "$RUNNER_TEMP/pr-body.md")
echo "Opened $URL" >> "$GITHUB_STEP_SUMMARY"
else
NUM="${PR%% *}"
OLD_BASE="${PR#* }"
if [ "$OLD_BASE" != "$BASE" ]; then
gh pr edit "$NUM" --repo "$REPO" --base "$BASE"
NEW_BASE=$(gh pr view "$NUM" --repo "$REPO" --json baseRefName --jq .baseRefName)
[ "$NEW_BASE" = "$BASE" ] || { echo "::error::retarget of #$NUM to $BASE did not apply"; exit 1; }
fi
# The force-push already updated the PR; a comment (not a body edit) records the run.
gh pr comment "$NUM" --repo "$REPO" --body-file "$RUNNER_TEMP/pr-body.md"
echo "Updated #$NUM" >> "$GITHUB_STEP_SUMMARY"
fi

View File

@@ -1,134 +0,0 @@
name: Lock released branch
# Two responsibilities (defense in depth — Hard Rule #18 enforcement):
#
# 1. `on: release: published` — when a GitHub Release publishes tag v3.X.Y,
# apply branch protection (lock_branch + enforce_admins) to release/v3.X.Y
# so no further commits can land on a shipped version. To reopen later:
# gh api -X DELETE repos/<owner>/<repo>/branches/release/<tag>/protection
#
# 2. `on: push: branches: ['release/v*']` — verify that no push lands on a
# release/* branch whose matching tag already exists. This is the preventive
# guard: if the lock didn't apply (workflow bug, missing PAT, race), this
# job FAILS the push run so the operator gets paged immediately.
#
# `permissions:` cannot grant the `Administration` scope to GITHUB_TOKEN — that
# scope only exists on PATs. Set BRANCH_LOCK_TOKEN as a repo secret pointing to
# a PAT/fine-grained token with `Administration: read & write`. Without it, the
# lock step will fail loudly (which is what we want — silent failure caused the
# v3.8.3 incident on 2026-05-26 where 6 commits landed post-release).
on:
release:
types: [published]
push:
branches:
- "release/v*"
workflow_dispatch:
inputs:
tag:
description: "Tag of the released version (e.g. v3.8.2)"
required: true
type: string
permissions:
contents: read
# One run per ref at a time. The push guard below is a 5-second tag lookup whose
# verdict is identical for every push on the same branch, yet without a concurrency
# group each of the ~10 pushes/hour on the active release branch queued its own
# hosted run (20 queued on 2026-10-17 against the account's concurrent-job limit).
# The newest push supersedes the older ones; a `release` event carries its own ref.
concurrency:
group: lock-released-${{ github.ref }}
cancel-in-progress: true
jobs:
# ─────────────────────────────────────────────────────────────────────────
# Job 1 — Lock the release branch when a Release is published.
# ─────────────────────────────────────────────────────────────────────────
lock-branch:
if: github.event_name == 'release' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
steps:
- name: Lock release/<tag> branch
env:
# Administration scope is required to PUT branch protection. Default
# GITHUB_TOKEN cannot do this — operator must provision BRANCH_LOCK_TOKEN.
GH_TOKEN: ${{ secrets.BRANCH_LOCK_TOKEN }}
TAG: ${{ github.event.release.tag_name || inputs.tag }}
REPO: ${{ github.repository }}
run: |
set -euo pipefail
if [ -z "${GH_TOKEN}" ]; then
echo "::error::BRANCH_LOCK_TOKEN secret is not set. Create a PAT with Administration:write and add it as repo secret."
exit 1
fi
if [ -z "${TAG}" ]; then
echo "::error::No tag provided; cannot determine release branch."
exit 1
fi
BRANCH="release/${TAG}"
echo "Target branch: ${BRANCH} (repo: ${REPO})"
if ! gh api "repos/${REPO}/branches/${BRANCH}" >/dev/null 2>&1; then
echo "::warning::Branch ${BRANCH} not found — nothing to lock."
exit 0
fi
echo "Applying lock_branch protection to ${BRANCH}..."
gh api -X PUT "repos/${REPO}/branches/${BRANCH}/protection" --input - <<'JSON'
{
"required_status_checks": null,
"enforce_admins": true,
"required_pull_request_reviews": null,
"restrictions": null,
"lock_branch": true,
"allow_force_pushes": false,
"allow_deletions": false
}
JSON
LOCKED=$(gh api "repos/${REPO}/branches/${BRANCH}/protection" \
--jq '.lock_branch.enabled')
if [ "${LOCKED}" != "true" ]; then
echo "::error::Failed to confirm lock on ${BRANCH} (lock_branch=${LOCKED})."
exit 1
fi
echo "✅ ${BRANCH} is now locked (read-only)."
# ─────────────────────────────────────────────────────────────────────────
# Job 2 — Preventive guard: fail if a push lands on release/vX.Y.Z whose
# tag already exists. This catches the case where the lock didn't apply
# (PAT missing, race window, workflow bug) and pages the operator.
# ─────────────────────────────────────────────────────────────────────────
guard-no-push-after-release:
if: github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- name: Reject push if matching release tag exists
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
REF: ${{ github.ref_name }}
run: |
set -euo pipefail
# Extract version from ref: release/v3.8.3 -> v3.8.3
if [[ ! "${REF}" =~ ^release/(v[0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
echo "Ref ${REF} does not match release/vX.Y.Z — nothing to guard."
exit 0
fi
TAG="${BASH_REMATCH[1]}"
echo "Checking if tag ${TAG} already exists on ${REPO}..."
if gh api "repos/${REPO}/git/refs/tags/${TAG}" >/dev/null 2>&1; then
echo "::error::Hard Rule #18 violation — push to ${REF} but tag ${TAG} is already released."
echo "::error::Hotfixes for a released version must go on a NEW branch: release/v$(echo "${TAG#v}" | awk -F. '{$3=$3+1; print $1"."$2"."$3}' OFS=.)"
echo "::error::To undo this push: revert the offending commits, or contact an admin to lock the branch if it wasn't already."
exit 1
fi
echo "✅ No release tag for ${TAG} yet — push is OK."

View File

@@ -1,65 +0,0 @@
name: Mutation Redundancy (disableBail, on-demand)
# One-off measurement to UNBLOCK R1 (test-redundancy prune). The nightly mutation run
# (nightly-mutation.yml) bails on the first kill, so `killedBy` lists only the FIRST
# killer — 🟠 redundant is understated and 🟢 unique overstated (see the caveat in
# scripts/quality/mutation-radiography.mjs). This workflow re-runs the SAME combo +
# chatCore leaf batches with stryker.disablebail.json (disableBail:true, incremental:false)
# so `killedBy` lists EVERY killer. Feed the uploaded reports to
# `node scripts/quality/mutation-radiography.mjs --candidates mutation-nobail-*/mutation.json`
# to get the accurate R1 prune-candidate list (🔴 empty ∪ 🟠 redundant) for human review.
#
# Batches mirror the nightly's leaf decomposition (d/e/f/g/h/i) rather than 2 mega-batches:
# disableBail is MORE expensive than bail (it never stops early), and Stryker only writes
# mutation.json on a SUCCESSFUL finish — a batch cancelled at the cap produces NO data — so
# smaller batches each fit the 300min headroom and run in parallel. auth/accountFallback and
# the security quartet are out of scope: R1 targets the combo/chatCore leaves.
on:
workflow_dispatch:
permissions:
contents: read
jobs:
stryker-nobail:
name: Stryker disableBail (batch ${{ matrix.batch.name }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
batch:
- name: d
mutate: "open-sse/services/combo/comboStructure.ts,open-sse/services/combo/autoStrategy.ts,open-sse/services/combo/validateQuality.ts"
- name: e
mutate: "open-sse/services/combo/shadowRouting.ts,open-sse/services/combo/targetSorters.ts,open-sse/services/combo/comboPredicates.ts,open-sse/services/combo/rrState.ts,open-sse/services/combo/comboData.ts"
- name: f
mutate: "open-sse/services/combo/quotaScoring.ts,open-sse/services/combo/quotaStrategies.ts"
- name: g
mutate: "open-sse/handlers/chatCore/comboContextCache.ts,open-sse/handlers/chatCore/idempotency.ts,open-sse/handlers/chatCore/passthroughHelpers.ts,open-sse/handlers/chatCore/responseHeaders.ts,open-sse/handlers/chatCore/sanitization.ts,open-sse/handlers/chatCore/upstreamTimeouts.ts"
- name: h
mutate: "open-sse/handlers/chatCore/headers.ts,open-sse/handlers/chatCore/logTruncation.ts,open-sse/handlers/chatCore/memoryExtraction.ts,open-sse/handlers/chatCore/nonStreamingSse.ts,open-sse/handlers/chatCore/passthroughToolNames.ts,open-sse/handlers/chatCore/executorHelpers.ts"
- name: i
mutate: "open-sse/handlers/chatCore/telemetryHelpers.ts,open-sse/handlers/chatCore/memorySkillsInjection.ts,open-sse/handlers/chatCore/semanticCache.ts"
timeout-minutes: 300
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Run Stryker (disableBail)
env:
BATCH_MUTATE: ${{ matrix.batch.mutate }}
run: npx stryker run --config-file stryker.disablebail.json --mutate "$BATCH_MUTATE"
- name: Upload mutation report
if: always()
uses: actions/upload-artifact@v7
with:
name: mutation-nobail-${{ matrix.batch.name }}
path: reports/mutation/
if-no-files-found: warn
retention-days: 14

View File

@@ -1,142 +0,0 @@
name: Nightly Node Compat
# Plano mestre testes+CI (Eixo D2, aprovado 2026-07-04): as matrizes de compatibilidade
# Node 24/26 custavam ~28% de CADA run do CI pesado (2 execuções completas da suíte por
# sync da release-PR) para pegar uma classe de quebra que raramente nasce num PR típico.
# Elas rodam aqui 1×/dia contra o tip da release ativa (mesmo alvo do nightly-release-green)
# e continuam obrigatórias no gate de release via workflow_dispatch do ci.yml se preciso.
# fail-fast desligado: numa quebra queremos saber TODAS as versões afetadas de uma vez.
on:
schedule:
- cron: "47 6 * * *" # 06:47 UTC diário — slot distinto dos demais nightlies
workflow_dispatch:
inputs:
branch:
description: "Branch to validate (default: highest release/vX.Y.Z)"
required: false
type: string
permissions:
contents: read
issues: write
concurrency:
group: nightly-compat
cancel-in-progress: true
jobs:
resolve-branch:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Resolve active release branch
runs-on: ubuntu-latest
outputs:
target: ${{ steps.branch.outputs.target }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- name: Resolve active release branch
id: branch
env:
INPUT_BRANCH: ${{ github.event.inputs.branch }}
run: |
set -euo pipefail
if [ -n "${INPUT_BRANCH:-}" ]; then
TARGET="$INPUT_BRANCH"
else
TARGET=$(git for-each-ref --format='%(refname:short)' 'refs/remotes/origin/release/v*' \
| sed 's#origin/##' \
| sort -t/ -k2 -V \
| tail -1)
fi
case "$TARGET" in
release/v[0-9]*.[0-9]*.[0-9]*) ;;
*) echo "Refusing non-canonical branch name: $TARGET"; exit 1 ;;
esac
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
compat-build-26:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Node 26 Compatibility Build
runs-on: ubuntu-latest
timeout-minutes: 25
needs: resolve-branch
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.resolve-branch.outputs.target }}
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "26"
cache: npm
- uses: ./.github/actions/npm-ci-retry
# #8090 — this is the ONLY Node 26 build in the whole CI matrix (ci.yml pins
# CI_NODE_VERSION=24). It failed every nightly with the runner-reclaimed
# signature ("The runner has received a shutdown signal" / "The operation was
# canceled", no exit code) always at the same Turbopack compile phase — a
# classic OOM kill on the memory-constrained ubuntu-latest runner. Turbopack's
# native (Rust, off-V8-heap) allocation is NOT bounded by --max-old-space-size
# and peaks far higher than webpack on this large module graph (#6409), and is
# heavier still under Node 26. Use the documented webpack fallback here: it still
# validates that the app *builds* on Node 26 (the point of this compat job) at a
# much lower memory peak. Turbopack-on-Node-24 stays covered by ci.yml's build
# job. See docs/reference/ENVIRONMENT.md (OMNIROUTE_USE_TURBOPACK) and #6409.
- run: npm run build
env:
OMNIROUTE_USE_TURBOPACK: "0"
compat-tests:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Node ${{ matrix.node }} Compat Tests (${{ matrix.shard }}/4)
runs-on: ubuntu-latest
timeout-minutes: 25
needs: resolve-branch
strategy:
fail-fast: false
matrix:
node: [24, 26]
shard: [1, 2, 3, 4]
env:
JWT_SECRET: ci-nightly-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-nightly-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
TEST_SHARD: ${{ matrix.shard }}/4
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.resolve-branch.outputs.target }}
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ matrix.node }}
cache: npm
- uses: ./.github/actions/npm-ci-retry
- run: npm run check:node-runtime
- run: npm run test:unit:ci:shard
report:
name: Open / update tracking issue on failure
runs-on: ubuntu-latest
if: ${{ (!cancelled() && (needs.compat-tests.result == 'failure' || needs.compat-build-26.result == 'failure')) && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
needs: [resolve-branch, compat-build-26, compat-tests]
permissions:
issues: write
steps:
- name: Open or update issue
env:
GH_TOKEN: ${{ github.token }}
TARGET: ${{ needs.resolve-branch.outputs.target }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
TITLE="🌙 nightly-compat: Node 24/26 failures on $TARGET"
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open --search "$TITLE in:title" --json number --jq '.[0].number')
BODY="Nightly Node-compat run failed on \`$TARGET\`: $RUN_URL — triage which Node version/shard broke (fail-fast off, all versions reported)."
if [ -n "$EXISTING" ]; then
gh issue comment "$EXISTING" --repo "$GITHUB_REPOSITORY" --body "$BODY"
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --body "$BODY"
fi

View File

@@ -1,184 +0,0 @@
name: Nightly LLM Security
on:
schedule:
- cron: "53 5 * * *"
workflow_dispatch:
permissions:
contents: read
jobs:
promptfoo-guard:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: promptfoo — injection guard (block mode, no secret)
# #11965: this job runs a backend-only `next build`; the hosted 7 GB runner cannot build
# release/v3.8.51 (VM shutdown ~7 min in), so it targets the box's light pool (`omni-light`:
# two listeners, jobs ≤ ~6 GB). Falls back to hosted when USE_VPS_RUNNER is off.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with: { node-version: "24", cache: npm }
# Fresh runtime state per run (same contract as nightly-schemathesis.yml). The
# omni-light runner keeps a persistent $HOME, so the server used to boot on
# $HOME/.omniroute, where the database left by older nights sat at migration 134
# while the tip ships 200+: the mass-migration guard (#3416, threshold 50) refused
# to migrate it, the catalog warm-up hit `no such table: model_capability_overrides`
# and the health wait failed every night (no verdict since 2026-08-27). A DATA_DIR
# under $RUNNER_TEMP is a new database every run, so every migration applies and
# nothing on the box is touched. Auto-backups stay off: one pre-migration backup
# per boot had piled up 1.6 GB under the runner's home.
- name: Prepare isolated runtime state
id: runtime
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-llm-security.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Build CLI bundle
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
OMNIROUTE_BUILD_BACKEND_ONLY: "1"
OMNIROUTE_USE_TURBOPACK: "0"
run: npm run build:cli
# Own port: this box also hosts the deployed server (the a11y job's
# "20128 is already used" nights prove it). A test server that dies on
# EADDRINUSE must NOT let the eval fall through to whatever else answers
# on the port — a block-mode validation against a server running WITHOUT
# block mode validates the wrong deployment and can only ever pass.
- name: Start OmniRoute (block mode)
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
PORT: "21778"
INJECTION_GUARD_MODE: block
DISABLE_SQLITE_AUTO_BACKUP: "true"
run: |
node dist/server.js > server.log 2>&1 &
echo $! > server.pid
for i in $(seq 1 60); do
if curl -sf http://localhost:21778/api/monitoring/health >/dev/null; then echo up; exit 0; fi
sleep 2
done
echo "::error::Test server did not come up on 21778 in 120s — see server.log. Refusing to run the guard eval against an unknown target."
tail -40 server.log || true
exit 1
# Pinned, network-isolated promptfoo. Two constraints, both verified on this box:
# (1) never `promptfoo@latest`: promptfoo >= 0.123.1 (promptfoo/promptfoo#10866) throws
# `result?.error?.includes is not a function` inside its rate-limit classifier when
# the https provider hands it the parsed 4xx JSON body the guard answers in block
# mode, so every blocked request became an eval ERROR, not a PASS (run 39007982929);
# (2) never the lockfile install (`npx --no-install`): #17017 — the lock nests js-yaml
# 4.3.2 under @apidevtools/json-schema-ref-parser, so the in-repo promptfoo dies at
# import on `binaryTag` (run 39084298931). `npx --yes promptfoo@<exact>` installs its
# own tree in the npx cache — when run from a directory without that package
# (see the step's working-directory). The version mirrors the devDependency pin in
# package.json; tests/unit/build/llm-security-nightly-promptfoo-pin.test.ts keeps
# the two equal and off the releases proven broken.
# `working-directory` OUTSIDE the checkout is load-bearing: npx resolves a package from
# the nearest node_modules first, and since #17005 the repo's own promptfoo satisfies
# the `@0.123.0` spec, so run from the workspace it picked node_modules/promptfoo and
# died on the nested js-yaml again (#17017, run 39095530088). From $RUNNER_TEMP there is
# no local install to shadow the npx cache tree.
- name: promptfoo guard-validation
working-directory: ${{ runner.temp }}
run: npx --yes promptfoo@0.123.0 eval -c "$GITHUB_WORKSPACE/promptfooconfig.yaml" --no-cache
env:
OMNIROUTE_URL: http://localhost:21778
OMNIROUTE_API_KEY: not-needed-blocked-before-upstream
- name: Stop server
if: always()
run: kill "$(cat server.pid)" || true
garak:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: garak probes (skip without provider secret)
# #11965: this job runs a backend-only `next build`; the hosted 7 GB runner cannot build
# release/v3.8.51 (VM shutdown ~7 min in), so it targets the box's light pool (`omni-light`:
# two listeners, jobs ≤ ~6 GB). Falls back to hosted when USE_VPS_RUNNER is off.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
# NOTE: the `secrets` context is NOT available in a job-level `if:` — referencing
# it there makes GitHub reject the file on push (startup_failure on every push).
# Map the secret into a job-level env and gate each step on a presence check, so
# the job stays green and simply skips the probes when the secret is absent.
env:
PROMPTFOO_PROVIDER_KEY: ${{ secrets.PROMPTFOO_PROVIDER_KEY }}
steps:
- name: Gate on provider secret
id: gate
run: |
if [ -n "$PROMPTFOO_PROVIDER_KEY" ]; then
echo "run=true" >> "$GITHUB_OUTPUT"
else
echo "run=false" >> "$GITHUB_OUTPUT"
echo "::notice::PROMPTFOO_PROVIDER_KEY not set — skipping garak probes (advisory)."
fi
- uses: actions/checkout@v7
with:
persist-credentials: false
if: steps.gate.outputs.run == 'true'
- uses: actions/setup-node@v7
if: steps.gate.outputs.run == 'true'
with: { node-version: "24", cache: npm }
# Same isolation as the promptfoo job above: a fresh DATA_DIR per run, never the
# runner's persistent $HOME/.omniroute (stale schema → migration guard → no boot).
- name: Prepare isolated runtime state
id: runtime
if: steps.gate.outputs.run == 'true'
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-llm-security.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
if: steps.gate.outputs.run == 'true'
- name: Build CLI bundle
if: steps.gate.outputs.run == 'true'
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
OMNIROUTE_BUILD_BACKEND_ONLY: "1"
OMNIROUTE_USE_TURBOPACK: "0"
run: npm run build:cli
# Same contract as the promptfoo job above: dedicated port, and the
# health wait must fail the job instead of letting garak probe whatever
# else listens on the default port.
- name: Start OmniRoute
if: steps.gate.outputs.run == 'true'
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
PORT: "21779"
DISABLE_SQLITE_AUTO_BACKUP: "true"
run: |
node dist/server.js > server.log 2>&1 &
echo $! > server.pid
for i in $(seq 1 60); do
if curl -sf http://localhost:21779/api/monitoring/health >/dev/null; then echo up; exit 0; fi
sleep 2
done
echo "::error::Test server did not come up on 21779 in 120s — see server.log."
tail -40 server.log || true
exit 1
- uses: actions/setup-python@v7
if: steps.gate.outputs.run == 'true'
with: { python-version: "3.12" }
- run: pip install garak
if: steps.gate.outputs.run == 'true'
- name: garak limited probes
if: steps.gate.outputs.run == 'true'
env:
OPENAI_API_KEY: ${{ secrets.PROMPTFOO_PROVIDER_KEY }}
OPENAI_BASE_URL: http://localhost:21779/v1
run: garak --model_type openai --model_name gpt-4o-mini --probes promptinject,dan,leakreplay --report_prefix garak-omniroute || true
- name: Stop server
if: always() && steps.gate.outputs.run == 'true'
run: kill "$(cat server.pid)" || true

View File

@@ -1,166 +0,0 @@
name: Nightly Mutation
on:
schedule:
- cron: "17 3 * * *"
workflow_dispatch:
permissions:
contents: read
jobs:
stryker:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Stryker mutation (batch ${{ matrix.batch.name }} — advisory)
runs-on: ubuntu-latest
# Mutation testing is expensive. History of the budget:
# - Full 8-module set TIMED OUT at the 180min cap (run 27705123780 = exactly 180min).
# The two god-files chatCore.ts/combo.ts dominated ~2/3 of the mutants and were
# removed from stryker.conf.json `mutate`.
# - The remaining 6 modules in 3 batches: auth.ts and accountFallback.ts are large; the
# a (auth+publicCreds) and b (accountFallback+error) batches still ran near the 180min
# cap (the perTest dry-run over ~130 covering test files is itself costly), so the two
# big modules are now ISOLATED into their own batches (a=auth, b=accountFallback).
# - Onda 3 / Fase 9 T5 re-add: combo.ts was split into 11 leaves; the 8 well-covered
# combo/* leaves are back in `mutate` (covered by the 24 combo-*.test.ts), grouped into
# 2 batches (d=heavy, e=light). After #4204 (D7b) merged, the reset-aware quota pair
# quotaScoring/quotaStrategies was added as batch f. A covering-test audit then added the
# 6 chatCore/* leaves with direct unit coverage as batch g. A follow-up then wrote dedicated
# unit tests for 6 more leaves and added them as batch h. A final follow-up added dedicated
# tests (no mock.module — fetch-override + crafted inputs + temp-DATA_DIR) for telemetryHelpers
# + memorySkillsInjection + semanticCache (its cache-HIT block now has a setCachedResponse
# fixture) as batch i — ALL 15/15 chatCore leaves are now mutated. See
# _mutate_godfiles_excluded_comment in stryker.conf.json.
# 9 PARALLEL batches, each overriding the mutate set via `--mutate` (Stryker 9 CLI:
# `-m, --mutate <comma-list>`; the conf's `mutate[]` remains the local-run default/union).
# - Cold-seeding budget (per-batch `timeout-minutes: ${{ matrix.batch.timeout || 180 }}`):
# a COLD run must COMPLETE once to write stryker-incremental.json (Stryker writes it only on
# a successful finish); a job cancelled at the cap writes nothing, so the next run is cold
# again — an infinite never-seeds loop. actions/cache is also branch-scoped, so each branch
# (incl. release) must seed its OWN cache via a run with enough headroom. Measured cold runs
# Measured cold totals (run 27801802713, extrapolated from the % at the 180/350 cancel point):
# auth ~375min (2301 mutants — EXCEEDS the 360min job max even isolated), accountFallback
# ~358min (1441), the c security quartet ~348min (1163), d ~197min (1316), g=142, h=132, e=66,
# f=45, i=33. The widely-covered modules blow the budget because the tap-runner re-runs every
# covering test file per mutant (a perTest fixed cost over ~138 test files, times thousands of
# mutants). A flat timeout bump cannot rescue auth (>360min max) — so the three over-budget
# batches are SPLIT so each half fits: auth->a1/a2 and accountFallback->b1/b2 by mutation range
# (`file:startLine-endLine`), the c quartet->c1/c2 by module pair. Splitting also seeds each
# sub-batch's own incremental cache, after which nightlies re-test only changed mutants.
# Full coverage every night in parallel; wall-clock = the slowest batch's cold run until seeded.
# Runs at stryker concurrency=4 with per-process DATA_DIR isolation
# (tests/_setup/isolateDataDir.ts) — see _concurrency_comment in stryker.conf.json.
strategy:
fail-fast: false
matrix:
batch:
# Per-batch `timeout` (minutes) tiers the cold-seeding budget by measured cost; batches
# without the key default to 180. Cold-run profiling (run 27801802713) showed the
# widely-covered modules need FAR more than the 180 cap because the tap-runner re-runs every
# covering test file per mutant: auth ~375min (2301 mutants, EXCEEDS the 360min GitHub job
# max even isolated), accountFallback ~358min, the c security quartet ~348min — none fit a
# single job. So auth/accountFallback are split by MUTATION RANGE (`file:startLine-endLine`,
# ~half the mutants each) into a1/a2, b1/b2; the c quartet is split by MODULE pair into
# c1/c2. d (3 combo modules, ~197min) stays whole. Split-heavy batches get 300min headroom
# for their cold seeding run; once each batch completes once and writes
# stryker-incremental.json, later runs re-test only changed mutants and finish far faster.
# g/h (142/132min cold) keep a 240 buffer; e/f/i (33-66min) keep the 180 default.
- name: a1
mutate: "src/sse/services/auth.ts:1-1109"
timeout: 300
- name: a2
mutate: "src/sse/services/auth.ts:1110-2218"
timeout: 300
- name: b1
mutate: "open-sse/services/accountFallback.ts:1-863"
timeout: 300
- name: b2
mutate: "open-sse/services/accountFallback.ts:864-1726"
timeout: 300
- name: c1
mutate: "src/server/authz/routeGuard.ts,src/shared/utils/circuitBreaker.ts"
timeout: 300
- name: c2
mutate: "open-sse/utils/error.ts,open-sse/utils/publicCreds.ts"
timeout: 300
- name: d
mutate: "open-sse/services/combo/comboStructure.ts,open-sse/services/combo/autoStrategy.ts,open-sse/services/combo/validateQuality.ts"
timeout: 300
- name: e
mutate: "open-sse/services/combo/shadowRouting.ts,open-sse/services/combo/targetSorters.ts,open-sse/services/combo/comboPredicates.ts,open-sse/services/combo/rrState.ts,open-sse/services/combo/comboData.ts"
- name: f
mutate: "open-sse/services/combo/quotaScoring.ts,open-sse/services/combo/quotaStrategies.ts"
- name: g
mutate: "open-sse/handlers/chatCore/comboContextCache.ts,open-sse/handlers/chatCore/idempotency.ts,open-sse/handlers/chatCore/passthroughHelpers.ts,open-sse/handlers/chatCore/responseHeaders.ts,open-sse/handlers/chatCore/sanitization.ts,open-sse/handlers/chatCore/upstreamTimeouts.ts"
timeout: 240
- name: h
mutate: "open-sse/handlers/chatCore/headers.ts,open-sse/handlers/chatCore/logTruncation.ts,open-sse/handlers/chatCore/memoryExtraction.ts,open-sse/handlers/chatCore/nonStreamingSse.ts,open-sse/handlers/chatCore/passthroughToolNames.ts,open-sse/handlers/chatCore/executorHelpers.ts"
timeout: 240
- name: i
mutate: "open-sse/handlers/chatCore/telemetryHelpers.ts,open-sse/handlers/chatCore/memorySkillsInjection.ts,open-sse/handlers/chatCore/semanticCache.ts"
# Per-batch budget: split-heavy batches (a1/a2/b1/b2/c1/c2/d) override to 300min, g/h to 240min;
# the rest default to 180min. `matrix.batch.timeout` is null for batches without the key -> `|| 180`.
# NOTE: a1+a2 both mutate auth.ts (disjoint line ranges) and b1+b2 both mutate accountFallback.ts;
# when merging the per-batch mutation.json for radiography/scores, same-file mutants from sibling
# ranges must be UNIONED (scripts/check/check-mutation-ratchet.mjs::measureMutationScores and
# scripts/quality/mutation-radiography.mjs both merge per file).
timeout-minutes: ${{ matrix.batch.timeout || 180 }}
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Restore Stryker incremental cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: reports/mutation/stryker-incremental.json
key: stryker-incremental-${{ matrix.batch.name }}-${{ github.run_id }}
restore-keys: stryker-incremental-${{ matrix.batch.name }}-
- name: Run Stryker (advisory)
id: stryker
continue-on-error: true
env:
BATCH_MUTATE: ${{ matrix.batch.mutate }}
run: npx stryker run --mutate "$BATCH_MUTATE"
- name: Upload mutation report
if: always()
uses: actions/upload-artifact@v7
with:
name: mutation-report-${{ matrix.batch.name }}
path: reports/mutation/
if-no-files-found: warn
retention-days: 14
# Aggregation gate (T3): each split batch emits a PARTIAL view of a mutated file
# (auth.ts lives in a1+a2, accountFallback in b1+b2), so a PER-BATCH ratchet would
# only ever see half a file vs the whole-file baseline. This job runs AFTER every
# batch, downloads all reports, and ratchets the MERGED per-module scores
# (check-mutation-ratchet UNIONS same-file mutants across reports) against the
# dedicatedGate `mutationScore.*` floors in quality-baseline.json (seeded ~2pt below
# the first full measurement). Blocking: a module dropping below its floor fails the
# run. Missing reports (e.g. an artifact-upload flake) are skipped, never failed.
mutation-ratchet:
name: Mutation score ratchet (blocking)
needs: stryker
if: ${{ always() && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
- name: Download all mutation reports
uses: actions/download-artifact@v8
with:
pattern: mutation-report-*
path: reports/all
- name: Ratchet merged per-module mutation scores
run: node scripts/check/check-mutation-ratchet.mjs reports/all/*/mutation.json --ratchet

View File

@@ -1,38 +0,0 @@
name: Nightly Property Discovery
on:
schedule:
- cron: "0 6 * * *"
workflow_dispatch:
permissions:
contents: read
issues: write
jobs:
property-random-seed:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: fast-check random seed (high runs)
id: prop
run: FC_SEED=random FC_NUM_RUNS=2000 npm run test:property
- name: Open issue on failure
if: failure()
uses: actions/github-script@v9
with:
script: |
await github.rest.issues.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: "Nightly property-test failure (Fase 8 B)",
body: "fast-check found a counterexample with a random seed. Check the run logs for the reproducible seed + minimal case, then add it as a fixture.\n\nRun: " + context.serverUrl + "/" + context.repo.owner + "/" + context.repo.repo + "/actions/runs/" + context.runId,
labels: ["quality-gate-finding"],
});

View File

@@ -1,890 +0,0 @@
name: Release-Green (continuous)
# Continuous validation: artifacts, issue state and job exit must agree.
#
# WHY: the full gate (ci.yml) only runs on the release PR (PR → main), so reds
# accrue silently on release/** and explode — in layers — at release time. This
# workflow reproduces the release-equivalent validation on the release branch and,
# when there are HARD failures, opens/updates a single tracking issue.
#
# WS5.1 (v3.8.49 quality plan) — two modes:
# push to release/v* (code paths) → --quick (fast HARD gates, ~5-8min). Catches the
# captain's direct pushes (sync-back — the one ungated write path) AND the merged
# COMBINATION right after every PR merge, attributing the offending push range in
# the issue. Base-red MTTD drops from ≤24h to ≤~15min after the offending push.
# schedule → full --with-build --full-ci (the deep sweep incl. build+suites): 3×/day for
# the release branch, 1×/day (05:23) for main, whose SHA only moves on a release.
#
# It is NOT a required status check and never touches a contributor PR — it only
# reports. Ratchet drift (eslint warnings / cognitive-complexity / file-size) is
# expected mid-cycle and is reported but never raises the alarm on its own; only
# real defects (typecheck / lint errors / unit / vitest / db-rules / public-creds /
# package-artifact) flip the issue open.
on:
push:
branches: ["release/v*", "main"]
paths:
- "src/**"
- "open-sse/**"
- "bin/**"
- "electron/**"
- "scripts/**"
- "tests/**"
- "config/**"
- ".github/workflows/**"
- ".github/actions/**"
- "package.json"
- "package-lock.json"
- "tsconfig*.json"
schedule:
- cron: "23 5 * * *" # full sweep — off-peak, distinct from other nightlies
- cron: "23 12 * * *" # full sweep — midday (WS5.1: 3×/day instead of 1×); release only
- cron: "23 18 * * *" # full sweep — evening; release only (main-green runs at 05:23 only)
workflow_dispatch:
inputs:
branch:
description: "Release branch to validate (default: highest release/vX.Y.Z)"
required: false
type: string
permissions:
contents: read
issues: write
concurrency:
# push storms during merge campaigns collapse to the newest commit per branch;
# scheduled full sweeps keep their own single lane. A started run is never cancelled:
# with cancel-in-progress on push, ~10 pushes/hour cancelled 97 of 100 push runs in a
# day (2026-10-18) after 2-18 min of work each, so the per-merge verdict almost never
# landed. GitHub keeps one running + one pending run per group, and a newer push still
# replaces the pending one, so the storm still collapses — without throwing work away.
group: release-green-${{ github.event_name }}-${{ github.ref }}
cancel-in-progress: false
env:
OMNIROUTE_SKIP_SYSTEM_TRUST: "1"
jobs:
# Schedule/dispatch only: the commit the hosted suites and the slot validation share.
# Resolved once so a push landing mid-sweep cannot split the lanes across two commits.
resolve-target:
name: Resolve sweep target
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
target: ${{ steps.resolve.outputs.target }}
sha: ${{ steps.resolve.outputs.sha }}
node-version: ${{ steps.runtime.outputs.node-version }}
steps:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
id: runtime
with:
node-version: "24"
package-manager-cache: false
- name: Resolve the active release branch and its tip
id: resolve
env:
GH_TOKEN: ${{ github.token }}
INPUT_BRANCH: ${{ github.event.inputs.branch }}
run: |
set -euo pipefail
if [ -n "${INPUT_BRANCH:-}" ]; then
TARGET="$INPUT_BRANCH"
else
TARGET=$(gh api "repos/$GITHUB_REPOSITORY/branches?per_page=100" --paginate \
--jq '.[].name' | grep -E '^release/v[0-9]+\.[0-9]+\.[0-9]+$' | sort -t/ -k2 -V | tail -1)
fi
if ! printf '%s' "$TARGET" | grep -qE '^release/v[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "Refusing non-canonical branch name: $TARGET"; exit 1
fi
SHA=$(gh api "repos/$GITHUB_REPOSITORY/branches/$TARGET" --jq '.commit.sha')
if ! printf '%s' "$SHA" | grep -qE '^[0-9a-f]{40}$'; then echo "No tip for $TARGET"; exit 1; fi
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
echo "sha=$SHA" >> "$GITHUB_OUTPUT"
echo "Sweep target: $TARGET @ $SHA"
# The full sweep's unit, integration and vitest lanes, on hosted runners with ci.yml's own
# shards and commands. On the 8-core omni-release slot they took ~4h15 per sweep and failed
# timing tests on CPU starvation (2026-10-19/20); hosted, a shard takes ~13 min. The shard
# counts must match ci.yml (tests/unit/validate-release-green.test.ts pins it).
suites:
name: Hosted suite (${{ matrix.name }})
needs: resolve-target
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- { name: unit-1, script: "test:unit:ci:shard", shard: "1/8" }
- { name: unit-2, script: "test:unit:ci:shard", shard: "2/8" }
- { name: unit-3, script: "test:unit:ci:shard", shard: "3/8" }
- { name: unit-4, script: "test:unit:ci:shard", shard: "4/8" }
- { name: unit-5, script: "test:unit:ci:shard", shard: "5/8" }
- { name: unit-6, script: "test:unit:ci:shard", shard: "6/8" }
- { name: unit-7, script: "test:unit:ci:shard", shard: "7/8" }
- { name: unit-8, script: "test:unit:ci:shard", shard: "8/8" }
- { name: integration-1, script: "test:integration:ci", shard: "1/2" }
- { name: integration-2, script: "test:integration:ci", shard: "2/2" }
- { name: vitest, script: "test:vitest", shard: "" }
env:
JWT_SECRET: ci-nightly-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-nightly-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.resolve-target.outputs.sha }}
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ needs.resolve-target.outputs.node-version }}
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Run the suite and record its result
env:
NAME: ${{ matrix.name }}
SUITE: ${{ matrix.script }}
TEST_SHARD: ${{ matrix.shard }}
NODE_OPTIONS: --max-old-space-size=8192
run: |
set +e
if [[ "$NAME" == integration-* ]]; then
# as ci.yml's test-integration job
export DATA_DIR="/tmp/omniroute-ci-${NAME#integration-}"
export INITIAL_PASSWORD=ci-test-password-for-integration
fi
(
if [ "$NAME" = "vitest" ]; then
npm run test:vitest && npm run test:vitest:ui
else
npm run "$SUITE"
fi
) 2>&1 | tee suite.log
code=${PIPESTATUS[0]}
node scripts/ci/release-green-suite.mjs "$NAME" "$code" suite.log suite-results \
"$GITHUB_WORKFLOW_SHA" "$SUITE" "$TEST_SHARD" || exit "$?"
exit "$code"
- name: Upload the suite result
if: always()
uses: actions/upload-artifact@v7
with:
name: release-green-suite-${{ github.run_attempt }}-${{ matrix.name }}
path: suite-results/
if-no-files-found: ignore
retention-days: 7
release-green:
name: Validate active release branch
# On a push, only run for release/* pushes — a push to main is handled by the
# main-green job below. Schedule/dispatch always run (they validate the highest release).
# On push the two jobs above are skipped; !cancelled() keeps this job from being skipped
# with them, and on schedule/dispatch it still reports when a suite job failed.
needs: [resolve-target, suites]
if: ${{ !cancelled() && (github.event_name != 'push' || startsWith(github.ref_name, 'release/')) && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
# Dynamic runner: with USE_VPS_RUNNER=true (release window / on-demand pre-flight)
# this runs on the dedicated VPS runner — clean env (no operator OMNIROUTE_API_KEY,
# no local noauth CLIs => zero machine-specific false positives) and no contention.
# Nightly cron normally finds the var false (VM off) and falls back to hosted.
# Own slot (docs/ops/RUNNER_BOX.md): `omni-release` is omniroute-113-6 only, so the
# validation no longer queues on the single `omni-build` slot (the 2026-10-18 05:29
# sweep waited 6 h for it). That slot is capped at 24 GB, so the validation's build
# runs on webpack (~14-16 GB); Turbopack fidelity stays with ci.yml's Build on
# `omni-build` and with the npm publish.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && fromJSON('["self-hosted","omni-release"]')) || 'ubuntu-latest' }}
env:
OMNIROUTE_USE_TURBOPACK: "0"
JWT_SECRET: ci-nightly-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-nightly-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- name: Resolve active release branch
id: branch
env:
INPUT_BRANCH: ${{ github.event.inputs.branch }}
EVENT_NAME: ${{ github.event_name }}
PUSHED_REF: ${{ github.ref_name }}
SWEEP_TARGET: ${{ needs.resolve-target.outputs.target }}
run: |
set -euo pipefail
if [ -n "${SWEEP_TARGET:-}" ]; then
# schedule/dispatch: the branch the hosted suites tested
TARGET="$SWEEP_TARGET"
elif [ -n "${INPUT_BRANCH:-}" ]; then
TARGET="$INPUT_BRANCH"
elif [ "$EVENT_NAME" = "push" ]; then
# validate exactly what was pushed, not the highest branch
TARGET="$PUSHED_REF"
else
# highest release/vX.Y.Z by semver among remote branches
TARGET=$(git for-each-ref --format='%(refname:short)' 'refs/remotes/origin/release/v*' \
| sed 's#origin/##' \
| sort -t/ -k2 -V \
| tail -1)
fi
if [ -z "$TARGET" ]; then echo "No release/v* branch found"; exit 1; fi
# Strict format guard — reject anything that isn't release/vX.Y.Z (blocks
# ref/command injection via the workflow_dispatch input).
if ! printf '%s' "$TARGET" | grep -qE '^release/v[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "Refusing non-canonical branch name: $TARGET"; exit 1
fi
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
echo "Active release branch: $TARGET"
- name: Checkout the release branch
env:
TARGET: ${{ steps.branch.outputs.target }}
EVENT_NAME: ${{ github.event_name }}
PUSH_SHA: ${{ github.sha }}
SWEEP_SHA: ${{ needs.resolve-target.outputs.sha }}
run: |
set -euo pipefail
if [ "$EVENT_NAME" = "push" ]; then
git checkout --detach "$PUSH_SHA"
elif [ -n "${SWEEP_SHA:-}" ]; then
# the exact commit the hosted suites tested
git checkout --detach "$SWEEP_SHA"
else
git checkout --detach "origin/$TARGET"
fi
git log -1 --oneline
- name: Record validated revision
id: revision
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- uses: actions/setup-node@v7
with:
node-version: ${{ needs.resolve-target.outputs.node-version || '24' }}
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Collect the hosted suite results
if: github.event_name != 'push'
continue-on-error: true
uses: actions/download-artifact@v8
with:
# A partial re-run cannot reuse receipts from an earlier attempt;
# rerun all suite jobs for a new complete observation of the same tip.
pattern: release-green-suite-${{ github.run_attempt }}-*
path: suite-results
merge-multiple: true
# Use the immutable workflow revision, not the target checkout (which may
# predate this installer). Both scanners are required even for --quick.
- name: Prepare pinned workflow scanners
id: workflow_scanners
env:
WORKFLOW_SHA: ${{ github.workflow_sha }}
run: |
set -euo pipefail
installer=$(mktemp "${RUNNER_TEMP:?}/workflow-scanners-installer.XXXXXX")
git show "${WORKFLOW_SHA}:scripts/ci/install-workflow-scanners.sh" > "$installer"
bash "$installer"
- name: Release-green validation (full)
id: validate
env:
EVENT_NAME: ${{ github.event_name }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
run: |
set +e
# --hermetic: scrub live-test trigger vars (self-hosted runner may carry
# operator env; hosted ignores the unknown flag before #6300 lands).
# push → --quick: fast HARD gates only (~5-8min), per-merge signal.
# schedule/dispatch → --with-build --full-ci: ALSO run every static gate from
# ci.yml's gate jobs (lint, quality-gate, quality-extended, docs-sync-strict,
# pr-test-policy) + build + full suites. PRs into release/** only get the
# fast-gates, so these accrue silently and explode in layers on the release PR
# (v3.8.46: 11 static base-reds leaked).
if [ "$EVENT_NAME" = "push" ]; then
MODE="--quick"
else
# unit/integration/vitest ran in the hosted `suites` jobs; a missing result fails
mkdir -p suite-results
MODE="--with-build --full-ci --suites-from suite-results"
fi
echo "[release-green] mode: $MODE (event: $EVENT_NAME)"
# MODE is an intentional flag list, so word-splitting is wanted here
# shellcheck disable=SC2086
node scripts/quality/validate-release-green.mjs --json --hermetic $MODE \
--suites-workflow-sha "$GITHUB_WORKFLOW_SHA" \
1> release-green.json 2> release-green.log
validation_exit=$?
node scripts/ci/release-green-result.mjs release-green.json "$validation_exit" "$VALIDATED_SHA" "$EVENT_NAME" >> release-green.log
echo "------- report -------"
cat release-green.log
- name: Open / update tracking issue on HARD failure
if: steps.validate.outputs.exit != '0'
env:
GH_TOKEN: ${{ github.token }}
TARGET: ${{ steps.branch.outputs.target }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
EVENT_NAME: ${{ github.event_name }}
BEFORE_SHA: ${{ github.event.before }}
AFTER_SHA: ${{ github.event.after }}
run: |
set -euo pipefail
TITLE="🔴 Release branch not green: ${TARGET}"
{
echo "The **release-green** validation found HARD failures on \`${TARGET}\`."
echo "The required validation failed or its evidence was incomplete. Compare the"
echo "signature on the exact base before attributing a defect to a contributor."
echo ""
echo "**Run:** ${RUN_URL} (mode: ${EVENT_NAME})"
# This is an observed range, not proof of causality. Compare with the base.
if [ "$EVENT_NAME" = "push" ] && [ -n "${BEFORE_SHA:-}" ] && \
git cat-file -e "$BEFORE_SHA" 2>/dev/null; then
echo ""
echo "**Observed push range** (\`${BEFORE_SHA:0:9}..${AFTER_SHA:0:9}\`):"
echo '```'
git log --no-decorate --oneline "${BEFORE_SHA}..${AFTER_SHA}" | head -20
echo '```'
fi
echo ""
echo '```'
if grep -q '──────── verdict ────────' release-green.log; then
sed -n '/──────── verdict ────────/,$p' release-green.log
else
tail -40 release-green.log
fi
echo '```'
echo ""
echo "_Ratchet drift (eslint warnings / cognitive-complexity / file-size) listed above is expected mid-cycle and is rebaselined at release — it is NOT a contributor concern and did not, on its own, open this issue._"
} > issue-body.md
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title $TITLE" --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ -n "$EXISTING" ]; then
gh issue comment "$EXISTING" --repo "$GITHUB_REPOSITORY" --body-file issue-body.md
echo "Updated existing issue #$EXISTING"
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --label base-red --body-file issue-body.md
fi
- name: Close tracking issue when the branch is green again
if: steps.validate.outputs.exit == '0' && github.event_name != 'push'
env:
GH_TOKEN: ${{ github.token }}
TARGET: ${{ steps.branch.outputs.target }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
CURRENT_SHA=$(git ls-remote origin "refs/heads/$TARGET" | cut -f1)
if [ "$CURRENT_SHA" != "$VALIDATED_SHA" ]; then
echo "Branch advanced; retaining the tracking issue."
exit 0
fi
# The open/update step above is the UPWARD half of the loop; without this
# step a stale "not green" issue outlives the fix and every base-green check
# (`AGENTS.md` → "Base-green check") keeps stamping new PRs as base-red inherited.
TITLE="🔴 Release branch not green: ${TARGET}"
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title $TITLE" --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ -n "$EXISTING" ]; then
gh issue close "$EXISTING" --repo "$GITHUB_REPOSITORY" --reason completed \
--comment "✅ \`${TARGET}\` is release-green again at \`${VALIDATED_SHA}\` — ${RUN_URL}. Auto-closed after full validation of the current branch."
echo "Closed issue #$EXISTING"
fi
# Best-effort: the verdict above is already recorded (issue open/closed,
# step summary). The artifact upload has raced job teardown on the shared
# runner three runs in a row (403 "job is completed" after the job was
# done), turning a finished verdict into a red run — a false base-red
# that every PR gate reads. Never let the upload outvote the verdict.
- name: Upload report artifact
if: always()
continue-on-error: true
uses: actions/upload-artifact@v7
with:
name: release-green-report
path: |
release-green.json
release-green.log
suite-results/
_artifacts/release-green/
if-no-files-found: error
retention-days: 14
- name: Enforce validation verdict
if: always()
env:
VALIDATION_EXIT: ${{ steps.validate.outputs.exit }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
EVENT_NAME: ${{ github.event_name }}
run: node scripts/ci/release-green-result.mjs release-green.json "$VALIDATION_EXIT" "$VALIDATED_SHA" "$EVENT_NAME"
# main's own sweep target, resolved once so the hosted suites and the slot validation
# cannot split across two commits. Same 05:23-only schedule as main-green.
resolve-main:
name: Resolve main sweep target
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || (github.repository == 'cheaper-inference/OmniRoute' && github.event.schedule == '23 5 * * *')) }}
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
sha: ${{ steps.resolve.outputs.sha }}
steps:
- name: Resolve the main tip
id: resolve
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
SHA=$(gh api "repos/$GITHUB_REPOSITORY/branches/main" --jq '.commit.sha')
if ! printf '%s' "$SHA" | grep -qE '^[0-9a-f]{40}$'; then echo "No tip for main"; exit 1; fi
echo "sha=$SHA" >> "$GITHUB_OUTPUT"
# Same reasons as `suites`: the 8-core root slot cannot run these lanes meaningfully.
# The matrix must match main's ci.yml shard counts; a mismatch fails closed as missing receipts.
main-suites:
name: Hosted main suite (${{ matrix.name }})
needs: [resolve-target, resolve-main]
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || (github.repository == 'cheaper-inference/OmniRoute' && github.event.schedule == '23 5 * * *')) }}
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- { name: unit-1, script: "test:unit:ci:shard", shard: "1/8" }
- { name: unit-2, script: "test:unit:ci:shard", shard: "2/8" }
- { name: unit-3, script: "test:unit:ci:shard", shard: "3/8" }
- { name: unit-4, script: "test:unit:ci:shard", shard: "4/8" }
- { name: unit-5, script: "test:unit:ci:shard", shard: "5/8" }
- { name: unit-6, script: "test:unit:ci:shard", shard: "6/8" }
- { name: unit-7, script: "test:unit:ci:shard", shard: "7/8" }
- { name: unit-8, script: "test:unit:ci:shard", shard: "8/8" }
- { name: integration-1, script: "test:integration:ci", shard: "1/2" }
- { name: integration-2, script: "test:integration:ci", shard: "2/2" }
- { name: vitest, script: "test:vitest", shard: "" }
env:
JWT_SECRET: ci-nightly-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-nightly-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.resolve-main.outputs.sha }}
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ needs.resolve-target.outputs.node-version }}
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Run the suite and record its result
env:
NAME: ${{ matrix.name }}
SUITE: ${{ matrix.script }}
TEST_SHARD: ${{ matrix.shard }}
NODE_OPTIONS: --max-old-space-size=8192
run: |
set +e
if [[ "$NAME" == integration-* ]]; then
# as ci.yml's test-integration job
export DATA_DIR="/tmp/omniroute-ci-${NAME#integration-}"
export INITIAL_PASSWORD=ci-test-password-for-integration
fi
(
if [ "$NAME" = "vitest" ]; then
npm run test:vitest && npm run test:vitest:ui
else
npm run "$SUITE"
fi
) 2>&1 | tee suite.log
code=${PIPESTATUS[0]}
node scripts/ci/release-green-suite.mjs "$NAME" "$code" suite.log suite-results \
"$GITHUB_WORKFLOW_SHA" "$SUITE" "$TEST_SHARD" || exit "$?"
exit "$code"
- name: Upload the suite result
if: always()
uses: actions/upload-artifact@v7
with:
name: main-green-suite-${{ github.run_attempt }}-${{ matrix.name }}
path: suite-results/
if-no-files-found: ignore
retention-days: 7
# Companion arm for `main`. Under the parallel-cycle model, main only receives merged
# work at the release squash — so a gate/infra fix that lands only on release leaves
# main red the whole cycle, and repo-wide gates (CodeQL alert count, ratchet baselines)
# turn EVERY PR into main red on a check unrelated to its diff. This detects that and
# opens a "🔴 main not green" tracking issue. The PREVENTION is the companion-PR reflex
# (Hard Rule #21 area / _shared/merge-gates.md §8); this is the automated backstop.
main-green:
name: Validate main branch
# On a push, only run for a push to main — a push to release/* is handled by
# release-green above. Dispatch always runs. On schedule, only the 05:23 cron sweeps
# main: main's SHA only moves on a release or hotfix, so the midday and evening sweeps
# re-validated the same commit and held the single `omni-release` slot for ~2 h each
# (2026-10-19: 08:04–10:01 right after the 2 h20 release sweep, while a `--quick` push
# run waited ~4 h in the group). The release branch keeps all three sweeps.
# On push the three jobs above are skipped; !cancelled() keeps this job from being skipped
# with them, and on schedule/dispatch it still reports when a suite job failed.
needs: [resolve-target, resolve-main, main-suites]
if: ${{ !cancelled() && (github.event_name != 'push' || github.ref_name == 'main') && (github.event_name != 'schedule' || (github.repository == 'cheaper-inference/OmniRoute' && github.event.schedule == '23 5 * * *')) }}
# Own slot (docs/ops/RUNNER_BOX.md): `omni-release` is omniroute-113-6 only, so the
# validation no longer queues on the single `omni-build` slot (the 2026-10-18 05:29
# sweep waited 6 h for it). That slot is capped at 24 GB, so the validation's build
# runs on webpack (~14-16 GB); Turbopack fidelity stays with ci.yml's Build on
# `omni-build` and with the npm publish.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && fromJSON('["self-hosted","omni-release"]')) || 'ubuntu-latest' }}
env:
OMNIROUTE_USE_TURBOPACK: "0"
JWT_SECRET: ci-nightly-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-nightly-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.event_name == 'push' && github.sha || needs.resolve-main.outputs.sha || 'main' }}
fetch-depth: 0
persist-credentials: false
- name: Record validated revision
id: revision
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
# hostedSuiteIdentity compares nodeVersion exactly, so match the hosted suites' runtime.
- uses: actions/setup-node@v7
with:
node-version: ${{ needs.resolve-target.outputs.node-version || '24' }}
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Collect the hosted suite results
if: github.event_name != 'push'
continue-on-error: true
uses: actions/download-artifact@v8
with:
# A partial re-run cannot reuse receipts from an earlier attempt;
# rerun all suite jobs for a new complete observation of the same tip.
pattern: main-green-suite-${{ github.run_attempt }}-*
path: suite-results
merge-multiple: true
# main can predate the installer: obtain tooling from the workflow SHA.
- name: Prepare pinned workflow scanners
id: workflow_scanners
env:
WORKFLOW_SHA: ${{ github.workflow_sha }}
run: |
set -euo pipefail
installer=$(mktemp "${RUNNER_TEMP:?}/workflow-scanners-installer.XXXXXX")
git show "${WORKFLOW_SHA}:scripts/ci/install-workflow-scanners.sh" > "$installer"
bash "$installer"
- name: Main-green validation
id: validate
env:
EVENT_NAME: ${{ github.event_name }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
run: |
set +e
# push (a merge into main) → --quick fast HARD gates; schedule/dispatch → full sweep.
if [ "$EVENT_NAME" = "push" ]; then
MODE="--quick"
else
# unit/integration/vitest ran in the hosted `main-suites` jobs; a missing result fails
mkdir -p suite-results
MODE="--with-build --full-ci --suites-from suite-results"
fi
echo "[main-green] mode: $MODE (event: $EVENT_NAME)"
# MODE is an intentional flag list, so word-splitting is wanted here
# shellcheck disable=SC2086
node scripts/quality/validate-release-green.mjs --json --hermetic $MODE \
--suites-workflow-sha "$GITHUB_WORKFLOW_SHA" \
1> main-green.json 2> main-green.log
validation_exit=$?
node scripts/ci/release-green-result.mjs main-green.json "$validation_exit" "$VALIDATED_SHA" "$EVENT_NAME" >> main-green.log
echo "------- report -------"
cat main-green.log
- name: Open / update tracking issue on HARD failure
if: steps.validate.outputs.exit != '0'
env:
GH_TOKEN: ${{ github.token }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
EVENT_NAME: ${{ github.event_name }}
run: |
set -euo pipefail
TITLE="🔴 main branch not green"
{
echo "The **main-green** validation found HARD failures on \`main\`."
echo ""
echo "Because \`main\` only receives merged work at the release squash, a gate/infra"
echo "fix that landed only on the release branch leaves \`main\` broken for the whole"
echo "cycle — and repo-wide gates (CodeQL alert count, ratchet baselines) then turn"
echo "**every open PR into main** red on a check unrelated to its diff. The fix is a"
echo "companion PR \`--base main\` carrying the release-side fix (see"
echo "\`_shared/merge-gates.md\` §8), NOT chasing each contributor PR."
echo ""
echo "**Run:** ${RUN_URL} (mode: ${EVENT_NAME})"
echo ""
echo '```'
if grep -q '──────── verdict ────────' main-green.log; then
sed -n '/──────── verdict ────────/,$p' main-green.log
else
tail -40 main-green.log
fi
echo '```'
echo ""
echo "_Ratchet drift (eslint warnings / cognitive-complexity / file-size) is expected mid-cycle and did NOT, on its own, open this issue._"
} > issue-body.md
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title $TITLE" --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ -n "$EXISTING" ]; then
gh issue comment "$EXISTING" --repo "$GITHUB_REPOSITORY" --body-file issue-body.md
echo "Updated existing issue #$EXISTING"
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --label base-red --body-file issue-body.md
fi
- name: Close tracking issue when the branch is green again
if: steps.validate.outputs.exit == '0' && github.event_name != 'push'
env:
GH_TOKEN: ${{ github.token }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
CURRENT_SHA=$(git ls-remote origin refs/heads/main | cut -f1)
if [ "$CURRENT_SHA" != "$VALIDATED_SHA" ]; then
echo "Branch advanced; retaining the tracking issue."
exit 0
fi
# The open/update step above is the UPWARD half of the loop; without this
# step a stale "not green" issue outlives the fix and every base-green check
# (`AGENTS.md` → "Base-green check") keeps stamping new PRs as base-red inherited.
TITLE="🔴 main branch not green"
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title $TITLE" --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ -n "$EXISTING" ]; then
gh issue close "$EXISTING" --repo "$GITHUB_REPOSITORY" --reason completed \
--comment "✅ \`main\` is main-green again at \`${VALIDATED_SHA}\` — ${RUN_URL}. Auto-closed after full validation of the current branch."
echo "Closed issue #$EXISTING"
fi
# Same best-effort contract as the release-green report upload above.
- name: Upload report artifact
if: always()
continue-on-error: true
uses: actions/upload-artifact@v7
with:
name: main-green-report
path: |
main-green.json
main-green.log
_artifacts/release-green/
if-no-files-found: error
retention-days: 14
- name: Enforce validation verdict
if: always()
env:
VALIDATION_EXIT: ${{ steps.validate.outputs.exit }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
EVENT_NAME: ${{ github.event_name }}
run: node scripts/ci/release-green-result.mjs main-green.json "$VALIDATION_EXIT" "$VALIDATED_SHA" "$EVENT_NAME"
# ── Banking lane (#8584) ──────────────────────────────────────────────────
# The ratchet is asymmetric: RAISING a cap is a ten-second manual JSON edit made
# under merge pressure, LOWERING one requires someone to run `--update` and commit
# — which no workflow does. Grep `.github/workflows/` for `--update`: only
# wiki-sync.yml (unrelated) and ci.yml's check-quality-ratchet.mjs --require-tighten
# (a different script, a different metric). So a cap outlives the code that earned
# it and every completed decomposition silently becomes a growth allowance for
# whoever touches the file next. Measured on 2026-07-25: 18 frozen files already at
# or under the 800-line new-file cap, up to 132x (schemas.ts, 19 lines / 2523 cap),
# and 31 unfulfilled "tighten via --update next cycle" notes honoured exactly once
# (-1 unit) in six weeks.
#
# This job closes that loop by making the DOWNWARD direction as automatic as the
# upward one is easy. It measures the active release branch, runs the shrink-only
# `--update` paths, and opens ONE always-current PR with the result. It never
# pushes to release/* — a human still merges, so a bad measurement cannot land
# unreviewed. verify-ratchet-bank.mjs is the hard guarantee that the automation can
# only ever write in the shrink direction; if anything was raised, added, or a
# rebaseline note was touched, the job aborts and opens nothing.
#
# Schedule/dispatch only, deliberately NOT on push: banking has no latency
# requirement (a shrink banked within 8h is fine) and a per-merge run would rebuild
# the PR branch repeatedly during merge campaigns while paying for a full ESLint
# walk each time. Detection stays on push (release-green above); banking is batched.
bank-ratchet-shrinks:
name: Bank ratchet shrinks
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Resolve active release branch
id: branch
env:
INPUT_BRANCH: ${{ github.event.inputs.branch }}
run: |
set -euo pipefail
if [ -n "${INPUT_BRANCH:-}" ]; then
TARGET="$INPUT_BRANCH"
else
TARGET=$(git for-each-ref --format='%(refname:short)' 'refs/remotes/origin/release/v*' \
| sed 's#origin/##' \
| sort -t/ -k2 -V \
| tail -1)
fi
if [ -z "$TARGET" ]; then echo "No release/v* branch found"; exit 1; fi
# Same strict guard as the validation job — blocks ref/command injection
# through the workflow_dispatch input.
if ! printf '%s' "$TARGET" | grep -qE '^release/v[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "Refusing non-canonical branch name: $TARGET"; exit 1
fi
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
echo "bank_branch=chore/bank-ratchet-${TARGET#release/}" >> "$GITHUB_OUTPUT"
- name: Checkout the release branch
env:
TARGET: ${{ steps.branch.outputs.target }}
run: |
set -euo pipefail
git checkout "$TARGET"
git log -1 --oneline
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Ratchet the baselines down
run: |
# Both --update paths are shrink-only by construction (file-size writes only
# on `improvements`, complexity-ratchets only when `.improved`), and both exit
# non-zero while the branch is over baseline — which is exactly when there is
# nothing to bank. Their exit code is not the signal; the verifier below is.
# Velocity phase (quality-baseline.json `_policy`, relax-baselines.mjs): the caps
# were raised on purpose, so banking the measured shrink would silently undo the
# 20% headroom every night. Pause the downward ratchet until the phase closes.
if node -e 'process.exit(require("./config/quality/quality-baseline.json")._policy?.phase === "velocity" ? 0 : 1)'; then
echo "Velocity phase active — ratchet banking paused (see docs/architecture/QUALITY_GATES.md → Velocity phase)."
exit 0
fi
set +e
node scripts/check/check-file-size.mjs --update
node scripts/check/check-complexity-ratchets.mjs --update
exit 0
- name: Verify the write only went downward
id: verify
run: |
set -euo pipefail
# Exits 1 if ANYTHING was raised/added or a rebaseline note was touched.
# `set -e` then aborts the job before a commit exists — no PR is opened.
node scripts/quality/verify-ratchet-bank.mjs > bank-summary.md
if [ -n "$(git status --porcelain config/quality/)" ]; then
echo "changed=true" >> "$GITHUB_OUTPUT"
else
echo "changed=false" >> "$GITHUB_OUTPUT"
echo "Nothing to bank — baselines already match the code."
fi
- name: Open / update the banking PR
if: steps.verify.outputs.changed == 'true'
env:
GH_TOKEN: ${{ github.token }}
TARGET: ${{ steps.branch.outputs.target }}
BANK_BRANCH: ${{ steps.branch.outputs.bank_branch }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git checkout -B "$BANK_BRANCH"
git add config/quality/
git commit -m "chore(quality): bank ratchet shrinks measured on ${TARGET}"
git push --force origin "$BANK_BRANCH"
{
echo "Automated banking of quality-ratchet **shrinks** already present in"
echo "\`${TARGET}\` — the downward half of the ratchet, which nothing else runs (#8584)."
echo ""
echo "Produced by \`check:file-size --update\` + \`check:complexity-ratchets --update\`,"
echo "then verified by \`scripts/quality/verify-ratchet-bank.mjs\`: **nothing was raised,"
echo "nothing was added, no rebaseline note was touched** — the job aborts without"
echo "opening a PR if any of those is violated."
echo ""
echo "No product code changes. Merging retires growth allowances that the code no"
echo "longer needs; not merging leaves them available to whoever edits those files next."
echo ""
cat bank-summary.md
echo ""
echo "**Run:** ${RUN_URL}"
} > pr-body.md
EXISTING=$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$BANK_BRANCH" \
--state open --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ -n "$EXISTING" ]; then
gh pr edit "$EXISTING" --repo "$GITHUB_REPOSITORY" --body-file pr-body.md
echo "Updated existing PR #$EXISTING"
else
gh pr create --repo "$GITHUB_REPOSITORY" --base "$TARGET" --head "$BANK_BRANCH" \
--title "chore(quality): bank ratchet shrinks (${TARGET})" --body-file pr-body.md
fi
# ── Baseline headroom (velocity phase, 2026-08-30 → v4.0) ──────────────────────
# The ratchets only speak when a baseline is crossed. With every baseline loosened by
# 20% (scripts/quality/relax-baselines.mjs) the question is how fast the budget is
# being consumed — this job measures each gate the way CI does and publishes the
# headroom table in the run summary and retained artifacts. Keep recurring reports
# out of the issue queue; the existing quality gates still enforce their budgets.
baseline-headroom:
name: Baseline headroom
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
timeout-minutes: 60
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 1
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Measure headroom on ${{ github.ref_name }}
run: |
set -euo pipefail
node scripts/quality/baseline-headroom.mjs \
--json reports/quality/headroom.json --md reports/quality/headroom.md
cat reports/quality/headroom.md >> "$GITHUB_STEP_SUMMARY"
- name: Upload headroom report
if: always()
uses: actions/upload-artifact@v7
with:
name: baseline-headroom-${{ github.run_id }}
path: reports/quality/headroom.*
retention-days: 90

View File

@@ -1,245 +0,0 @@
name: Nightly Resilience
on:
schedule:
- cron: "41 4 * * *"
workflow_dispatch:
permissions:
contents: read
jobs:
heap:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Heap-growth gate
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- run: npm run test:heap
chaos:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Resilience chaos (fault injection)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- run: npm run test:chaos
k6-soak:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: k6 load/soak
# #11965: this job runs a backend-only `next build`; the hosted 7 GB runner cannot build
# release/v3.8.51 (VM shutdown ~7 min in), so it targets the box's light pool (`omni-light`:
# two listeners, jobs ≤ ~6 GB). Falls back to hosted when USE_VPS_RUNNER is off.
# #16853: on hosted it died in `npm run build:cli` 8 nights out of 8 ("The runner has
# received a shutdown signal").
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
# Fresh runtime state per run (same contract as nightly-llm-security.yml). The
# omni-light runner keeps a persistent $HOME, so a server booted without DATA_DIR
# lands on $HOME/.omniroute, where a database left by older runs can sit far behind
# the tip's migrations: the mass-migration guard (#3416) refuses to migrate it and
# the server never becomes healthy. A DATA_DIR under $RUNNER_TEMP is a new database
# every run, so every migration applies and nothing on the box is touched.
- name: Prepare isolated runtime state
id: runtime
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-k6-soak.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Build CLI bundle
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
OMNIROUTE_BUILD_BACKEND_ONLY: "1"
OMNIROUTE_USE_TURBOPACK: "0"
run: npm run build:cli
# Own port: this box also hosts the deployed server on 20128. A test server that
# dies on EADDRINUSE must NOT let the soak fall through to whatever else answers
# there, and a soak against nothing must not go green — the health wait fails the
# job (same contract as nightly-llm-security.yml). Auto-backups stay off: one
# pre-migration backup per boot piles up under the runner's home.
- name: Start OmniRoute (background)
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
PORT: "21776"
DISABLE_SQLITE_AUTO_BACKUP: "true"
run: |
node dist/server.js > server.log 2>&1 &
echo $! > server.pid
for i in $(seq 1 60); do
if curl -sf http://localhost:21776/api/monitoring/health >/dev/null; then echo "server up"; exit 0; fi
sleep 2
done
echo "::error::Test server did not come up on 21776 in 120s — see server.log. Refusing to run the soak against an unknown target."
tail -40 server.log || true
exit 1
- name: Install k6
uses: grafana/setup-k6-action@v1
- name: Run k6 soak
run: k6 run tests/load/k6-soak.js
env:
BASE_URL: http://localhost:21776
SOAK_DURATION: "3m"
SOAK_VUS: "10"
- name: Stop server
if: always()
run: kill "$(cat server.pid)" || true
a11y-build:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: A11y build (production artefact, omni-build)
# #16853: the a11y suite needs a production build of the FULL dashboard, and that build
# does not fit the light pool the a11y job runs on (Turbopack reaches ~40 GB RSS on the
# `.113`, #16169; webpack needs a >= 10 GB V8 heap for this tree). Build it once on the
# build pool — same runner class and Turbopack policy as ci.yml's `build` job — and hand
# the artefact to the a11y job, which only boots it. Falls back to hosted (webpack) when
# the VPS build runner is off, like ci.yml.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true') && fromJSON('["self-hosted","omni-build"]') || 'ubuntu-latest' }}
timeout-minutes: 60
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: "24"
cache: npm
# Page-data collection imports server modules that open the database: keep it in a
# fresh DATA_DIR, never the self-hosted runner's persistent $HOME (same contract as
# the k6 job above and nightly-llm-security.yml).
- name: Prepare isolated runtime state
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-a11y-build.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Build Next.js (production)
run: npm run build
env:
OMNIROUTE_USE_TURBOPACK: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true') && '1' || '0' }}
# Same archive contract as ci.yml's build -> test-e2e hand-off: tar keeps the paths
# relative to the checkout (.build/next/...), the build cache stays out.
- name: Archive the build for the a11y job
run: |
tar -czf "$RUNNER_TEMP/a11y-build.tar.gz" \
--exclude='.build/next/cache' \
.build/next
- name: Upload the build for the a11y job
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: a11y-next-build
path: ${{ runner.temp }}/a11y-build.tar.gz
retention-days: 1
a11y:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: A11y axe (nightly, freeze-and-alert)
needs: a11y-build
# Boots the production build made by `a11y-build` (no self-build here: #16853) and runs
# the axe suite against it. Hosted, always: on the light pool the 1.2 GB artefact took
# 1,416 s to download and the 30-minute timeout cancelled the job before axe ran (run
# 39156364797, 2026-10-18), after it had already queued 80 min behind lint-guard jobs.
# Hosted runners pull the same class of artefact in seconds (the per-PR E2E shards), a
# standalone server fits them, and a fresh VM has no port or $HOME left by other jobs.
# REQUIRE_AXE=1 makes the suite run the real axe analysis (the 4 page tests are gated to
# nightly so per-PR e2e stays fast) and makes the meta-test fail loudly if
# @axe-core/playwright ever goes missing.
runs-on: ubuntu-latest
timeout-minutes: 30
env:
JWT_SECRET: ci-test-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-test-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
REQUIRE_AXE: "1"
# Own a port the rest of the box cannot steal. This job ran on the default
# 20128 and failed 9 of 10 nights two ways: "http://localhost:20128/
# api/monitoring/health is already used" when the deployed server (or a
# concurrent runner job) answered first (runs 35688196787, 35562389397),
# and a 900 s webServer timeout under listener contention (run
# 35819784314). DASHBOARD_PORT drives playwright.config's readiness URL,
# PORT drives the server the webServer script boots — both set, same value.
DASHBOARD_PORT: "21777"
PORT: "21777"
# The webServer only boots the downloaded standalone build (same switch the per-PR
# test-e2e shards use), so its window covers a boot, not a build.
OMNIROUTE_PLAYWRIGHT_SKIP_BUILD: "1"
OMNIROUTE_PLAYWRIGHT_WEB_SERVER_TIMEOUT: "600000"
# Send the server's stdout to the job log: the 2026-10-18 failure was a 30-minute
# silent wait because Playwright discards webServer stdout by default.
OMNIROUTE_PLAYWRIGHT_WEB_SERVER_STDOUT: "pipe"
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
# The server this job boots must not open the runner's persistent $HOME/.omniroute:
# a database left there by older runs sits behind the tip's migrations and the
# mass-migration guard (#3416) keeps the server from ever becoming healthy.
- name: Prepare isolated runtime state
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-a11y.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Cache Playwright browsers
uses: actions/cache@v6.1.0
with:
path: ~/.cache/ms-playwright
key: playwright-chromium-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: playwright-chromium-${{ runner.os }}-
- run: npx playwright install --with-deps chromium
- name: Download the production build
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: a11y-next-build
path: next-build-artifact
- name: Extract the production build
run: tar -xzf next-build-artifact/a11y-build.tar.gz
- name: Run axe a11y suite (prebuilt standalone server)
run: npx playwright test tests/e2e/a11y.spec.ts

View File

@@ -1,111 +0,0 @@
name: Nightly Schemathesis
on:
schedule:
- cron: "23 4 * * *"
workflow_dispatch:
permissions:
contents: read
jobs:
schemathesis:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Schemathesis — OpenAPI contract fuzz (advisory)
# #11965: this job runs a backend-only `next build`; the hosted 7 GB runner cannot build
# release/v3.8.51 (VM shutdown ~7 min in), so it targets the box's light pool (`omni-light`:
# two listeners, jobs ≤ ~6 GB). Falls back to hosted when USE_VPS_RUNNER is off.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
# 2026-10-17: the webpack backend-only build alone took >25 min on the busy .113 and the
# old 30-minute cap cancelled the job before the probes started (run 38982564979).
timeout-minutes: 120
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with: { node-version: "24", cache: npm }
- name: Prepare isolated runtime state
id: runtime
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-schemathesis.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Build CLI bundle
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
OMNIROUTE_BUILD_BACKEND_ONLY: "1"
OMNIROUTE_USE_TURBOPACK: "0"
run: npm run build:cli
- name: Start OmniRoute (background)
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
HOSTNAME: "127.0.0.1"
PORT: "21780"
run: |
# A persistent runner can already host another deployment. Never fuzz it.
if (echo > /dev/tcp/127.0.0.1/"$PORT") 2>/dev/null; then
echo "::error::Port $PORT is already occupied; refusing to probe another server."
exit 1
fi
node dist/server.js > server.log 2>&1 &
server_pid=$!
echo "$server_pid" > "$DATA_DIR/server.pid"
for _ in $(seq 1 30); do
if ! kill -0 "$server_pid" 2>/dev/null; then
echo "::error::OmniRoute exited before becoming ready; see server.log."
exit 1
fi
if curl --max-time 2 -sf "http://127.0.0.1:$PORT/api/monitoring/health" >/dev/null && kill -0 "$server_pid" 2>/dev/null; then
echo "server up"
exit 0
fi
sleep 2
done
echo "::error::OmniRoute did not become healthy after 30 attempts; see server.log."
exit 1
- uses: actions/setup-python@v7
with: { python-version: "3.12" }
- name: Install schemathesis
run: pip install schemathesis
- name: Schemathesis contract fuzz (advisory)
# Advisory gate: never fails the job. `continue-on-error` covers a crash of the
# step itself; `|| true` covers schemathesis exiting non-zero when it finds spec
# violations / upstream 500s — both are expected here (most /v1 endpoints proxy an
# upstream that has no provider configured in CI). The point of the nightly is to
# PROVE the contract is fuzzable and surface regressions, not to gate the build.
continue-on-error: true
run: |
schemathesis run docs/openapi.yaml \
--url http://127.0.0.1:21780 \
--max-examples 20 \
--workers 4 \
--checks all \
--max-response-time 30 \
--request-timeout 30 \
--suppress-health-check all \
--report junit \
--report-junit-path schemathesis-report/junit.xml \
--no-color \
|| true
- name: Stop server
if: always() && steps.runtime.outcome == 'success'
run: |
if [ -n "$DATA_DIR" ] && [ -f "$DATA_DIR/server.pid" ]; then
kill "$(cat "$DATA_DIR/server.pid")" || true
fi
- name: Upload schemathesis report
if: always()
uses: actions/upload-artifact@v7
with:
name: schemathesis-report
path: |
schemathesis-report/
server.log
if-no-files-found: warn
retention-days: 14

View File

@@ -1,176 +0,0 @@
name: Nightly v4 build (dormant)
# DORMANT until the 3.9.0 LTS cut creates `develop` (docs/ops/RELEASE_STRATEGY.md →
# channel `nightly`). The first job checks `git ls-remote --heads origin develop`
# and ends the run green and silent while the branch does not exist.
#
# When develop exists: compute `<core>-nightly.<YYYYMMDD>.<sha7>` with
# scripts/release/compute-nightly-version.mjs, build the release bundle, validate
# the pack artifact and keep the tarball as a workflow artifact. Publishing to npm
# under the `nightly` dist-tag happens ONLY when the repository variable
# `NIGHTLY_PUBLISH` is exactly 'true' — and additionally requires npm Trusted
# Publishing to accept this workflow file (npmjs.com → package settings), since
# today it is configured for npm-publish.yml only.
on:
schedule:
- cron: "23 4 * * *" # 04:23 UTC daily
workflow_dispatch:
permissions:
contents: read
concurrency:
group: nightly-v4-build
cancel-in-progress: false
env:
NIGHTLY_NODE_VERSION: "24"
jobs:
detect:
name: Detect develop
# Upstream-only for scheduled runs (check-workflows scheduled-guard).
if: (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
runs-on: ubuntu-latest
permissions: {}
outputs:
exists: ${{ steps.develop.outputs.exists }}
steps:
- name: Check that develop exists
id: develop
env:
REPO_URL: ${{ github.server_url }}/${{ github.repository }}.git
run: |
set -euo pipefail
if [ -n "$(git ls-remote --heads "$REPO_URL" develop)" ]; then
echo "exists=true" >> "$GITHUB_OUTPUT"
else
echo "exists=false" >> "$GITHUB_OUTPUT"
echo "develop does not exist yet — nightly v4 build is dormant, nothing to do."
fi
build:
name: Build nightly
needs: detect
if: (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') && needs.detect.outputs.exists == 'true'
# Same dynamic-runner rule as npm-publish.yml: a full `next build` outgrew the
# 16 GB hosted runner during v3.8.49. Never runs on pull_request.
runs-on: ${{ vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && fromJSON('["self-hosted","omni-build"]') || 'ubuntu-latest' }}
permissions:
contents: read
outputs:
version: ${{ steps.version.outputs.version }}
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
steps:
- name: Checkout develop
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: develop
fetch-depth: 0
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: ${{ env.NIGHTLY_NODE_VERSION }}
package-manager-cache: false
- name: Compute nightly version
id: version
run: |
set -euo pipefail
# The schedule's GITHUB_SHA is the default branch, not develop — use HEAD.
HEAD_SHA=$(git rev-parse HEAD)
VERSION=$(node scripts/release/compute-nightly-version.mjs --sha "$HEAD_SHA")
# Defense in depth: the computed version must resolve to the nightly channel.
TAG=$(node scripts/release/dist-tag.mjs --version "$VERSION" --requested auto < /dev/null)
if [ "$TAG" != "nightly" ]; then
echo "Computed $VERSION resolves to dist-tag '$TAG', expected 'nightly'" >&2
exit 1
fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "📦 omniroute@$VERSION (dist-tag=nightly)"
- name: Install dependencies
uses: ./.github/actions/npm-ci-retry
with:
cache: "false" # a publishable artifact never restores node_modules from cache
- name: Stamp the nightly version
env:
VERSION: ${{ steps.version.outputs.version }}
run: npm version "$VERSION" --no-git-tag-version --allow-same-version
- name: Build release bundle
run: npm run build:release
- name: Validate npm package artifact
env:
# The provenance guard checks ancestry against origin/main by default; a
# nightly is cut from develop.
OMNIROUTE_RELEASE_REF: origin/develop
run: npm run check:pack-artifact
- name: Pack the tarball
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
set -euo pipefail
npm pack --ignore-scripts
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "expected $TARBALL after npm pack" >&2; ls -la ./*.tgz || true; exit 1; }
- name: Upload nightly tarball
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: npm-nightly-tarball
path: omniroute-${{ steps.version.outputs.version }}.tgz
retention-days: 7
if-no-files-found: error
publish:
name: Publish nightly to npm
needs: build
if: (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') && vars.NIGHTLY_PUBLISH == 'true'
runs-on: ubuntu-latest # Trusted Publishing (OIDC) requires a GitHub-hosted runner
permissions:
contents: read
id-token: write # npm provenance + Trusted Publishing
steps:
- name: Download nightly tarball
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: npm-nightly-tarball
path: .
- name: Setup Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: ${{ env.NIGHTLY_NODE_VERSION }}
registry-url: https://registry.npmjs.org
package-manager-cache: false
- name: Ensure npm supports Trusted Publishing
run: |
set -euo pipefail
if ! node -e "const [a,b]=process.argv[1].split('.').map(Number); process.exit(a>11||(a===11&&b>=15)?0:1)" "$(npm --version)"; then
# Pinned exact version (supply-chain: never float @latest in a publish job).
npm install -g --ignore-scripts npm@11.15.0
fi
npm --version
- name: Publish with --tag nightly
env:
VERSION: ${{ needs.build.outputs.version }}
run: |
set -euo pipefail
case "$VERSION" in
*-nightly.*) ;;
*) echo "Refusing to publish non-nightly version '$VERSION' from the nightly workflow" >&2; exit 1 ;;
esac
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "tarball $TARBALL did not arrive from the build job" >&2; exit 1; }
npm publish "$TARBALL" --provenance --access public --tag nightly --ignore-scripts
echo "✅ Published omniroute@$VERSION (dist-tag=nightly)"

View File

@@ -1,666 +1,42 @@
name: Publish to npm
on:
# 'released' (not 'published') so editing/re-publishing old releases does NOT
# re-trigger this workflow. Pairs with the semver guard below as defense in
# depth against accidental dist-tag clobbering by old releases.
release:
types: [released]
workflow_dispatch:
inputs:
version:
description: "Version to publish (e.g. 2.9.5 or 3.0.0-rc.15)"
required: true
type: string
tag:
description: "npm dist-tag (auto / latest / next / nightly / lts / historic)"
required: false
default: "auto"
type: choice
options:
- auto
- latest
- next
- nightly
- lts
- historic
publish_mode:
description: "auto = publish through npm Trusted Publishing (OIDC, no token, no 2FA prompt — the default); staged = npm stage publish (owner approves with 2FA); direct = legacy token publish (emergency fallback only)"
required: false
default: "auto"
type: choice
options:
- auto
- staged
- direct
workflow_call:
inputs:
version:
description: "Version to publish (without v prefix)"
required: true
type: string
tag:
description: "npm dist-tag (auto / latest / next / nightly / lts / historic)"
required: false
default: "auto"
type: string
secrets:
NPM_TOKEN:
required: true
types: [published]
# Least-privilege default: read-only at the top level; each publish job grants the
# id-token (npm provenance) / packages (GitHub Packages) writes it needs (Scorecard
# TokenPermissions).
permissions:
contents: read
env:
NPM_PUBLISH_NODE_VERSION: "24"
id-token: write
jobs:
publish:
# Same dynamic-runner rule as ci.yml's `build`/`test-unit`: `build:cli` falls back to a
# full `next build`, whose working set outgrew the 16 GB hosted runner during the
# v3.8.49 cycle — the publish died with "The runner has received a shutdown signal"
# mid-"Creating an optimized production build" while v3.8.48 had still fit in 16min.
# This job never runs on `pull_request`, so the fork-safety clause is always true here;
# it is kept verbatim so the expression stays greppable against ci.yml.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && fromJSON('["self-hosted","omni-build"]') || 'ubuntu-latest' }}
outputs:
version: ${{ steps.resolve.outputs.version }}
tag: ${{ steps.resolve.outputs.tag }}
skip: ${{ steps.resolve.outputs.skip }}
permissions:
actions: read # find + download the CI run's next-build artifact for this SHA
contents: write # gh release upload (attach SBOM to the GitHub Release)
id-token: write # npm provenance (GitHub Packages step)
packages: write # publish to npm.pkg.github.com
runs-on: ubuntu-latest
environment: NPM_TOKEN
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
# Need full tag history to compare against highest semver when
# deciding whether this release should claim dist-tag `latest`.
fetch-depth: 0
uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v7
uses: actions/setup-node@v6
with:
node-version: ${{ env.NPM_PUBLISH_NODE_VERSION }}
node-version: 22
registry-url: https://registry.npmjs.org
- name: Install dependencies (skip scripts to avoid heavy build)
run: npm install --ignore-scripts --no-audit --no-fund
- name: Install dependencies
run: npm ci
- name: Resolve version, dist-tag and skip flag
id: resolve
env:
EVENT_NAME: ${{ github.event_name }}
REF_NAME: ${{ github.ref_name }}
INPUT_VERSION: ${{ inputs.version }}
INPUT_TAG: ${{ inputs.tag }}
run: |
set -euo pipefail
# 1) Resolve VERSION from the trigger (all inputs come via env).
VERSION="${INPUT_VERSION:-}"
if [ -z "$VERSION" ] && [ "$EVENT_NAME" = "release" ]; then
VERSION="$REF_NAME"
fi
VERSION="${VERSION#v}"
if ! printf '%s' "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+([.-][A-Za-z0-9.-]+)?$'; then
echo "Refusing to publish unsafe VERSION value: $VERSION" >&2
exit 1
fi
# 2) Resolve dist-tag via scripts/release/dist-tag.mjs (single source of the
# channel rules in docs/ops/RELEASE_STRATEGY.md; tests/unit/
# compute-nightly-version.test.ts pins every decision):
# - explicit 'latest'/'next'/'nightly'/'lts'/'historic' is honored
# - 'auto' (or empty): `-nightly.*` → 'nightly' (never 'latest');
# rc/beta/alpha/pre/next and any other pre-release → 'next';
# stable versions → 'latest' only if VERSION is the highest stable
# `v*` tag; a stable of an OLDER major than the highest stable tag
# (3.9.x after the 4.0 GA) → 'lts' only if it is the highest of the
# older majors; anything else → 'historic' (never clobbers a channel).
# Values reach the script as quoted argv and stdin — never interpolated.
REQUESTED_TAG="${INPUT_TAG:-auto}"
test -f scripts/release/dist-tag.mjs || {
echo "scripts/release/dist-tag.mjs is missing from this checkout — refusing to guess a dist-tag." >&2
exit 1
}
git fetch --tags --quiet || true
TAG=$(git tag -l 'v[0-9]*' | node scripts/release/dist-tag.mjs --version "$VERSION" --requested "$REQUESTED_TAG")
if [ "$REQUESTED_TAG" = "auto" ] && [ "$TAG" = "historic" ]; then
echo "Version $VERSION is not the highest stable tag of its channel. Using dist-tag 'historic' to avoid clobbering @latest/@lts."
fi
# 3) Skip-if-already-published. NOTE: do NOT pass `--silent` to
# `npm view` — it suppresses stdout and breaks the grep, which
# caused old releases (3.2.8) to be re-published and steal
# dist-tag `latest`. See incident notes in CHANGELOG.
PUBLISHED="$(npm view "omniroute@${VERSION}" version 2>/dev/null || true)"
SKIP="false"
if [ "$PUBLISHED" = "$VERSION" ]; then
echo "⚠️ omniroute@${VERSION} is already on npm — skipping publish."
SKIP="true"
fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "skip=$SKIP" >> "$GITHUB_OUTPUT"
echo "📦 Resolved omniroute@$VERSION dist-tag=$TAG skip=$SKIP"
- name: Sync package.json version
if: steps.resolve.outputs.skip != 'true'
env:
VERSION: ${{ steps.resolve.outputs.version }}
run: |
npm version "$VERSION" --no-git-tag-version --allow-same-version
# Fast path: CI already built the standalone tree for THIS commit and uploaded it as
# `next-build`. `build:cli` (scripts/build/prepublish.ts) only shells out to a full
# `next build` when `.build/next/standalone/server.js` is missing — restoring the
# artifact turns the heaviest step of the publish into a download. Matching on
# `head_sha` is the tree-equality guarantee: same commit, same tree.
# Best-effort by design (retention is 1 day): every miss falls through to the build
# step below, which is why the dynamic runner above matters as the backstop.
#
# The `head_repository.full_name == env.REPO` clause is a supply-chain guard, not a
# filter refinement. This artifact becomes the published npm tarball. `pull_request`
# runs from forks execute in THIS repository's context and upload their own
# `next-build` built from fork-controlled source, and the runs API returns them for a
# matching `head_sha` — 57 such runs exist in this repo today. Without the clause,
# anything that made a fork's head commit coincide with the publish commit could put
# attacker-built bytes on npm. Requiring the run to originate from this repository
# excludes every fork run while keeping the fast path intact (verified: the same
# single run is selected either way for the current tip).
# CodeQL: actions/artifact-poisoning/critical.
- name: Reuse CI's next-build artifact (skips the heavy rebuild)
if: steps.resolve.outputs.skip != 'true'
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
HEAD_SHA: ${{ github.sha }}
REPO: ${{ github.repository }}
run: |
set -uo pipefail
# The question is "which run HAS the artifact", not "which run passed" (gap 16).
# Requiring `conclusion == "success"` on the whole run discarded a perfectly good tree
# whenever any unrelated shard went red — one flaky test then pushed the publish into
# the 40-minute build this step exists to avoid. The artifact is only uploaded if the
# Build job itself succeeded, so its PRESENCE is the accurate signal; the run's overall
# conclusion is noise from jobs that have nothing to do with the tree.
#
# `head_repository.full_name == env.REPO` stays, and it is not a filter refinement:
# this tree becomes the published npm tarball, and fork `pull_request` runs execute in
# THIS repository's context uploading their own next-build. That clause is the
# supply-chain guard (CodeQL actions/artifact-poisoning).
CANDIDATES=$(gh api "repos/$REPO/actions/runs?head_sha=$HEAD_SHA&per_page=100" \
--jq '[.workflow_runs[]
| select(.name == "CI"
and .head_repository.full_name == env.REPO)]
| sort_by(.run_started_at) | reverse | .[0:5] | .[].id') || CANDIDATES=""
if [ -z "$CANDIDATES" ]; then
echo "::notice::no CI run from this repository for $HEAD_SHA — falling back to a full build"
exit 0
fi
RUN=""
# $RUNNER_TEMP, never /tmp: on the .113 pool /tmp is a 12 GB tmpfs (RAM). Parking
# this 1.3 GB artefact there took 27–32 min of the 76-min publish job — the
# same bytes upload from disk in 2 min. RUNNER_TEMP is per-runner and on disk.
for candidate in $CANDIDATES; do
if gh run download "$candidate" --repo "$REPO" --name next-build --dir "$RUNNER_TEMP/next-build" 2>/dev/null; then
RUN="$candidate"
break
fi
echo " run $candidate carries no usable next-build — trying the next"
done
if [ -z "$RUN" ]; then
echo "::notice::none of the candidate runs still carries next-build (1-day retention) — falling back to a full build"
exit 0
fi
tar -xzf "$RUNNER_TEMP/next-build/e2e-build.tar.gz" -C .
rm -rf "$RUNNER_TEMP/next-build"
if [ -f .build/next/standalone/server.js ]; then
echo "✅ standalone tree restored from CI run $RUN — build:cli will skip next build"
else
echo "::notice::extract did not yield .build/next/standalone — falling back to a full build"
rm -rf .build
fi
- name: Build CLI bundle (standalone app)
if: steps.resolve.outputs.skip != 'true'
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
- name: Build standalone app
run: npm run build:cli
# `build:cli` assembles dist/ but does NOT write dist/BUILD_SHA — only
# `build:release` does, by calling write-build-sha.mjs. The #10427 provenance
# guard inside check:pack-artifact rejects an artifact with no SHA (and rejects
# it even under OMNIROUTE_ALLOW_CANARY_BUILD=1: what cannot be identified cannot
# be vouched for). Without this step the build+validate pair in this job is
# structurally incompatible and fails 100% of the time — the same gap that was
# fixed in ci.yml's Package Artifact job.
- name: Stamp dist/BUILD_SHA for the provenance guard (#10427)
if: steps.resolve.outputs.skip != 'true'
env:
OMNIROUTE_BUILD_SHA: ${{ github.sha }}
- name: Sync version from release tag
run: |
export OMNIROUTE_BUILD_SHA="${OMNIROUTE_BUILD_SHA:0:7}"
node scripts/build/write-build-sha.mjs
VERSION="${GITHUB_REF_NAME}"
# Remove 'v' prefix if present (v0.1.0 -> 0.1.0)
VERSION="${VERSION#v}"
npm version "$VERSION" --no-git-tag-version --allow-same-version
echo "Publishing version: $VERSION"
# The guard checks ancestry against origin/main by default, which is correct
# here (a release tag is cut from main), but the ref has to exist locally for
# `git merge-base` to resolve it.
- name: Fetch main for the provenance probe
if: steps.resolve.outputs.skip != 'true'
run: git fetch --no-tags --depth=50 origin +refs/heads/main:refs/remotes/origin/main
- name: Validate npm package artifact
if: steps.resolve.outputs.skip != 'true'
run: npm run check:pack-artifact
- name: Generate CycloneDX SBOM (npm)
if: steps.resolve.outputs.skip != 'true'
run: npx @cyclonedx/cyclonedx-npm --ignore-npm-errors --output-format JSON --output-file sbom-npm.cdx.json
- name: Upload SBOM (npm) as workflow artifact
if: steps.resolve.outputs.skip != 'true'
uses: actions/upload-artifact@v7
with:
name: sbom-npm
path: sbom-npm.cdx.json
if-no-files-found: error
- name: Attach SBOM to GitHub Release
# Not only on the `release` event: the v3.8.50 package shipped through a
# workflow_dispatch (staged publish, 11 attempts) and this step was skipped, so the
# GitHub Release carried no SBOM until it was attached by hand from the run's
# `sbom-npm` artifact. Attach whenever a release for the published tag exists.
if: steps.resolve.outputs.skip != 'true' && (github.event_name == 'release' || github.event_name == 'workflow_dispatch')
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: ${{ github.event_name == 'release' && github.ref_name || format('v{0}', inputs.version) }}
run: |
if ! gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
echo "::notice::no GitHub Release for $TAG yet — SBOM stays on the sbom-npm workflow artifact"
exit 0
fi
gh release upload "$TAG" sbom-npm.cdx.json --repo "$GITHUB_REPOSITORY" --clobber
# WS1.2/WS1.3 (#7065 class): the artifact that is about to be published must
# BOOT. build:cli already assembled dist/ above; this packs+installs+boots the
# real tarball and fails the publish before anything reaches the registry.
- name: Boot-smoke the tarball before ANY publish
if: steps.resolve.outputs.skip != 'true'
run: npm run check:pack-boot
# The boot-smoke above proves a CLEAN install boots. It does not prove the path that
# actually broke us: installing over an existing version, where ~110 SQLite migrations
# run against a populated database. v3.8.48 shipped as a hotfix because the published
# 3.8.47 crashed on boot, and the v3.8.49 upgrade path was first exercised end-to-end
# by hand on a real 3.8.48 box (VPS .16) — after publishing, which is exactly backwards.
# Runs BEFORE `npm stage publish` so a broken upgrade never reaches the registry at all;
# a staged package that is never approved simply expires, with no `npm deprecate` needed.
- name: Prove clean-install AND upgrade-over-previous both boot
if: steps.resolve.outputs.skip != 'true'
# 60, not 30. This gate was added in #8953 and the 2026-08-27 v3.8.50 publish
# was the FIRST run to ever reach it — every earlier attempt died upstream, so
# its budget had never been measured against a real run. It then blew the limit
# on its debut: `npm pack` alone took 24m37s, leaving 5 minutes for two installs
# and two boots. 30 was a guess; 60 is sized to the one measurement we have.
timeout-minutes: 60
run: npm run check:install-upgrade
# WS1.3 (D2, v3.8.49 plan): STAGED publishing by default — `npm stage publish`
# parks the exact bytes on the registry WITHOUT making them installable; the
# owner then verifies and approves with 2FA (`npm stage approve`), moving the
# human gate to AFTER the proof instead of before it. Requires npm >= 11.15
# (staged publishing GA 2026-05-22). publish_mode=direct is the emergency
# fallback (legacy immediate publish) via workflow_dispatch.
- name: Ensure npm supports staged publishing
if: steps.resolve.outputs.skip != 'true' && (github.event_name != 'workflow_dispatch' || inputs.publish_mode != 'direct')
run: |
set -euo pipefail
CUR=$(npm --version)
if ! node -e "const [a,b]='$(npm --version)'.split('.').map(Number); process.exit(a>11||(a===11&&b>=15)?0:1)"; then
# Pinned exact version (supply-chain: never float @latest in the publish
# job); bump deliberately when a newer npm is required.
echo "npm $CUR < 11.15 — installing pinned npm 11.15.0 for staged publishing"
npm install -g --ignore-scripts npm@11.15.0
fi
npm --version
# The registry upload itself moved to the `stage-npm` job below: npm REFUSES
# `--provenance` from a self-hosted runner (422 "Unsupported GitHub Actions
# runner environment"), and the heavy verification above cannot move to a
# hosted one (16 GB is not enough for build:cli's next-build fallback — see
# this job's runs-on comment). So this job proves the bytes and hands them
# over; a tiny hosted job does the upload.
- name: Pack the verified tarball for the upload job
if: steps.resolve.outputs.skip != 'true'
env:
VERSION: ${{ steps.resolve.outputs.version }}
run: |
set -euo pipefail
# --ignore-scripts: prepublishOnly would re-run build:cli-api && build:cli,
# rebuilding bytes this job has already built, validated and boot-smoked.
npm pack --ignore-scripts
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "expected $TARBALL to exist after npm pack" >&2; ls -la ./*.tgz || true; exit 1; }
echo "packed $TARBALL ($(du -h "$TARBALL" | cut -f1))"
- name: Hand the tarball to the hosted publish job
if: steps.resolve.outputs.skip != 'true'
uses: actions/upload-artifact@v7
with:
name: npm-tarball
path: omniroute-${{ steps.resolve.outputs.version }}.tgz
retention-days: 1
if-no-files-found: error
- name: Publish to GitHub Packages
if: steps.resolve.outputs.skip != 'true'
env:
VERSION: ${{ steps.resolve.outputs.version }}
TAG: ${{ steps.resolve.outputs.tag }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
echo "Configuring for GitHub Packages..."
echo "//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}" > .npmrc
npm pkg set name="@cheaper-inference/omniroute"
npm publish --registry=https://npm.pkg.github.com --tag "$TAG" \
|| echo "⚠️ omniroute@${VERSION} might already be published on GitHub Packages."
echo "✅ Action finished for GitHub Packages"
# npm REFUSES `--provenance` from a self-hosted runner:
# 422 Unprocessable Entity - Error verifying sigstore provenance bundle:
# Unsupported GitHub Actions runner environment: "self-hosted".
# Only "github-hosted" runners are supported when publishing with provenance.
# v3.8.49 published fine because it predates USE_VPS_RUNNER being turned on
# (2026-08-02); v3.8.50 was the first release after it, so this had been latent
# for four weeks. Dropping --provenance was not an option: 3.8.49 carries a
# SLSA attestation and 3.8.50 must not regress that.
# The `publish` job cannot simply move to a hosted runner either — 16 GB is not
# enough for build:cli's next-build fallback. So it keeps proving the bytes and
# this job, which needs no memory at all, performs the upload.
stage-npm:
needs: publish
if: needs.publish.outputs.skip != 'true'
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # npm provenance — the whole reason this job is separate
steps:
- name: Download the tarball the publish job proved
uses: actions/download-artifact@v8
with:
name: npm-tarball
path: .
- name: Setup Node.js
uses: actions/setup-node@v7
with:
node-version: ${{ env.NPM_PUBLISH_NODE_VERSION }}
registry-url: https://registry.npmjs.org
- name: Ensure npm supports staged publishing
run: |
set -euo pipefail
CUR=$(npm --version)
if ! node -e "const [a,b]='$(npm --version)'.split('.').map(Number); process.exit(a>11||(a===11&&b>=15)?0:1)"; then
# Pinned exact version (supply-chain: never float @latest in a publish
# job); bump deliberately when a newer npm is required.
echo "npm $CUR < 11.15 — installing pinned npm 11.15.0 for staged publishing"
npm install -g --ignore-scripts npm@11.15.0
fi
npm --version
# Trusted Publishing (OIDC): npm mints a short-lived credential for THIS run from
# GitHub's id-token — no NPM_TOKEN secret, no 2FA prompt, provenance included, and
# it is the bypass npm sanctions now that tokens which skip 2FA are being retired
# (gh.io/npm-gat-bypass2fa-deprecation). Requires the package's Trusted Publisher to
# be configured on npmjs.com (owner: cheaper-inference/OmniRoute, workflow
# npm-publish.yml) and a github-hosted runner — which is why this job exists.
# Without that configuration `npm publish` fails with ENEEDAUTH: re-dispatch with
# publish_mode=staged or direct. Automatic publishing was the flow up to v3.8.48;
# v3.8.49 moved to staged (WS1.3) to keep a leaked token from publishing alone —
# OIDC gives the same guarantee without the manual approve.
- name: Publish to npm (Trusted Publishing / OIDC — automatic)
if: github.event_name != 'workflow_dispatch' || inputs.publish_mode == 'auto'
env:
VERSION: ${{ needs.publish.outputs.version }}
TAG: ${{ needs.publish.outputs.tag }}
run: |
set -euo pipefail
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "tarball $TARBALL did not arrive from the publish job" >&2; ls -la; exit 1; }
# Deliberately NO NODE_AUTH_TOKEN in this step: npm >= 11.5 detects the GitHub
# OIDC token itself. Always pass --tag explicitly (defense in depth: an older
# VERSION can never claim `@latest`).
npm publish "$TARBALL" --provenance --access public --tag "$TAG" --ignore-scripts
echo "✅ Published omniroute@$VERSION (dist-tag=$TAG) via Trusted Publishing"
- name: Publish to npm (staged — owner approves with 2FA)
# Only on an explicit request now: Trusted Publishing below is the default.
if: github.event_name == 'workflow_dispatch' && inputs.publish_mode == 'staged'
env:
VERSION: ${{ needs.publish.outputs.version }}
TAG: ${{ needs.publish.outputs.tag }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
set -euo pipefail
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "tarball $TARBALL did not arrive from the publish job" >&2; ls -la; exit 1; }
# Always pass --tag explicitly. Defense in depth: even if VERSION is
# accidentally an older release, the historic tag will NOT claim `@latest`.
# --ignore-scripts: publishing a built tarball must never re-run
# prepublishOnly (build:cli-api && build:cli) on this small runner.
npm stage publish "$TARBALL" --provenance --access public --tag "$TAG" --ignore-scripts
{
echo "## 📦 omniroute@$VERSION STAGED (not yet installable)"
echo ""
echo "The exact bytes are parked on the registry. To release them:"
echo '```'
echo "npm stage list omniroute # find the stage id"
echo "npm stage approve <id> # owner 2FA — THE publish"
echo '```'
echo "To verify the staged bytes first: npm stage download <id> → run"
echo "scripts/check/check-pack-boot.mjs against them (see RELEASE_CHECKLIST)."
echo "To discard: npm stage reject <id>."
} >> "$GITHUB_STEP_SUMMARY"
echo "✅ Staged omniroute@$VERSION (dist-tag=$TAG) — awaiting owner 'npm stage approve'"
- name: Publish to npm (DIRECT — emergency fallback)
if: github.event_name == 'workflow_dispatch' && inputs.publish_mode == 'direct'
env:
VERSION: ${{ needs.publish.outputs.version }}
TAG: ${{ needs.publish.outputs.tag }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
set -euo pipefail
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "tarball $TARBALL did not arrive from the publish job" >&2; ls -la; exit 1; }
npm publish "$TARBALL" --provenance --access public --tag "$TAG" --ignore-scripts
echo "✅ Published omniroute@$VERSION (dist-tag=$TAG) [DIRECT mode]"
publish-opencode-plugin:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # npm provenance
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
fetch-depth: 0
# Full history needed for auto-bump: git diff against previous release tag
- name: Setup Node.js
uses: actions/setup-node@v7
with:
node-version: ${{ env.NPM_PUBLISH_NODE_VERSION }}
registry-url: https://registry.npmjs.org
- name: Auto-bump plugin version if plugin changed since last release
id: bump
working-directory: "@omniroute/opencode-plugin"
env:
CURRENT_TAG: ${{ github.ref_name }}
run: |
set -euo pipefail
PKG_VERSION=$(node -p "require('./package.json').version")
PKG_NAME=$(node -p "require('./package.json').name")
# 1) Skip if current version is not yet published (no bump needed)
PUBLISHED="$(npm view "${PKG_NAME}@${PKG_VERSION}" version 2>/dev/null || true)"
if [ "$PUBLISHED" != "$PKG_VERSION" ]; then
echo "✅ ${PKG_NAME}@${PKG_VERSION} is new — no bump needed."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 2) Find the previous release tag (exclude the current one)
PREV_TAG=$(git tag -l 'v*' --sort=-version:refname \
| grep -v "^${CURRENT_TAG}$" | head -1 || echo "")
if [ -z "$PREV_TAG" ]; then
echo "No previous tag to compare — skipping bump."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 3) Check if plugin dir actually changed since that tag
if git diff --quiet "$PREV_TAG" -- "@omniroute/opencode-plugin/"; then
echo "⏭️ No plugin changes since $PREV_TAG — nothing to publish."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 4) Auto-bump patch version
npm version patch --no-git-tag-version --allow-same-version
NEW_VERSION=$(node -p "require('./package.json').version")
echo "bumped=true" >> "$GITHUB_OUTPUT"
echo "📦 Auto-bumped ${PKG_NAME} from ${PKG_VERSION} to ${NEW_VERSION}"
- name: Install plugin dependencies
working-directory: "@omniroute/opencode-plugin"
run: npm install --no-audit --no-fund
- name: Build plugin
working-directory: "@omniroute/opencode-plugin"
run: npm run clean && npm run build
- name: Test plugin
working-directory: "@omniroute/opencode-plugin"
run: npm test
- name: Publish @omniroute/opencode-plugin to npm
working-directory: "@omniroute/opencode-plugin"
- name: Publish to npm
run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
set -euo pipefail
PKG_VERSION=$(node -p "require('./package.json').version")
PKG_NAME=$(node -p "require('./package.json').name")
# Same hardened skip-check as the main job (no --silent flag).
PUBLISHED="$(npm view "${PKG_NAME}@${PKG_VERSION}" version 2>/dev/null || true)"
if [ "$PUBLISHED" = "$PKG_VERSION" ]; then
echo "⚠️ ${PKG_NAME}@${PKG_VERSION} is already published on npm — skipping."
exit 0
fi
npm publish --provenance --access public --ignore-scripts
echo "✅ Published ${PKG_NAME}@${PKG_VERSION}"
publish-opencode-plugin-v2:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # npm provenance
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
fetch-depth: 0
# Full history needed for auto-bump: git diff against previous release tag
- name: Setup Node.js
uses: actions/setup-node@v7
with:
node-version: ${{ env.NPM_PUBLISH_NODE_VERSION }}
registry-url: https://registry.npmjs.org
- name: Auto-bump plugin-v2 version if plugin-v2 changed since last release
id: bump
working-directory: "@omniroute/opencode-plugin-v2"
env:
CURRENT_TAG: ${{ github.ref_name }}
run: |
set -euo pipefail
PKG_VERSION=$(node -p "require('./package.json').version")
PKG_NAME=$(node -p "require('./package.json').name")
# 1) Skip if current version is not yet published (no bump needed)
PUBLISHED="$(npm view "${PKG_NAME}@${PKG_VERSION}" version 2>/dev/null || true)"
if [ "$PUBLISHED" != "$PKG_VERSION" ]; then
echo "✅ ${PKG_NAME}@${PKG_VERSION} is new — no bump needed."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 2) Find the previous release tag (exclude the current one)
PREV_TAG=$(git tag -l 'v*' --sort=-version:refname \
| grep -v "^${CURRENT_TAG}$" | head -1 || echo "")
if [ -z "$PREV_TAG" ]; then
echo "No previous tag to compare — skipping bump."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 3) Check if plugin-v2 dir actually changed since that tag
if git diff --quiet "$PREV_TAG" -- "@omniroute/opencode-plugin-v2/"; then
echo "⏭️ No plugin-v2 changes since $PREV_TAG — nothing to publish."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 4) Auto-bump patch version
npm version patch --no-git-tag-version --allow-same-version
NEW_VERSION=$(node -p "require('./package.json').version")
echo "bumped=true" >> "$GITHUB_OUTPUT"
echo "📦 Auto-bumped ${PKG_NAME} from ${PKG_VERSION} to ${NEW_VERSION}"
- name: Install plugin-v2 dependencies
working-directory: "@omniroute/opencode-plugin-v2"
run: npm install --no-audit --no-fund
- name: Build plugin-v2
working-directory: "@omniroute/opencode-plugin-v2"
run: npm run clean && npm run build
- name: Test plugin-v2
working-directory: "@omniroute/opencode-plugin-v2"
run: npm test
- name: Publish @omniroute/opencode-plugin-v2 to npm
working-directory: "@omniroute/opencode-plugin-v2"
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
set -euo pipefail
PKG_VERSION=$(node -p "require('./package.json').version")
PKG_NAME=$(node -p "require('./package.json').name")
# Same hardened skip-check as the main job (no --silent flag).
PUBLISHED="$(npm view "${PKG_NAME}@${PKG_VERSION}" version 2>/dev/null || true)"
if [ "$PUBLISHED" = "$PKG_VERSION" ]; then
echo "⚠️ ${PKG_NAME}@${PKG_VERSION} is already published on npm — skipping."
exit 0
fi
npm publish --provenance --access public --ignore-scripts
echo "✅ Published ${PKG_NAME}@${PKG_VERSION}"

View File

@@ -1,90 +0,0 @@
name: opencode-plugin CI
on:
push:
branches: [main, "release/**"]
paths:
- "@omniroute/opencode-plugin/**"
- "@omniroute/opencode-plugin-v2/**"
pull_request:
branches: [main, "release/**"]
paths:
- "@omniroute/opencode-plugin/**"
- "@omniroute/opencode-plugin-v2/**"
types: [opened, synchronize, reopened, ready_for_review]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
defaults:
run:
working-directory: "@omniroute/opencode-plugin"
jobs:
test:
name: Test (Node ${{ matrix.node }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node: ["22", "24"]
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ matrix.node }}
cache: npm
cache-dependency-path: "@omniroute/opencode-plugin/package-lock.json"
- run: npm install --no-audit --no-fund
- run: npm run build
- run: npm test
test-v2:
name: Test v2 (Node ${{ matrix.node }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node: ["22", "24"]
defaults:
run:
working-directory: "@omniroute/opencode-plugin-v2"
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ matrix.node }}
cache: npm
cache-dependency-path: "@omniroute/opencode-plugin-v2/package-lock.json"
- run: npm ci --no-audit --no-fund
- run: npm run build
- run: npm test
build:
name: Build
runs-on: ubuntu-latest
needs: [test, test-v2]
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "22"
- name: Build plugin-v2 artifact
working-directory: "@omniroute/opencode-plugin-v2"
run: npm ci --no-audit --no-fund && npm run build
- uses: actions/upload-artifact@v7
with:
name: opencode-plugin-v2-dist
path: "@omniroute/opencode-plugin-v2/dist"
retention-days: 7

View File

@@ -1,65 +0,0 @@
name: opencode-provider CI
on:
push:
branches: [main, release/v3.8.0]
paths:
- "@omniroute/opencode-provider/**"
pull_request:
branches: [main, release/v3.8.0]
paths:
- "@omniroute/opencode-provider/**"
types: [opened, synchronize, reopened, ready_for_review]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
defaults:
run:
working-directory: "@omniroute/opencode-provider"
jobs:
test:
name: Test (Node ${{ matrix.node }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node: ["20", "22", "24"]
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ matrix.node }}
cache: npm
cache-dependency-path: "@omniroute/opencode-provider/package-lock.json"
- run: npm ci
- run: npm test
build:
name: Build
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "20"
cache: npm
cache-dependency-path: "@omniroute/opencode-provider/package-lock.json"
- run: npm ci
- run: npm run build
- uses: actions/upload-artifact@v7
with:
name: opencode-provider-dist
path: "@omniroute/opencode-provider/dist"
retention-days: 7

View File

@@ -1,252 +0,0 @@
name: Preview artifact (build once)
# PR preview artifact — #8084 slice (a), rehearsed in 3.8.58 (ROADMAP Phase 2).
#
# Builds ONE production-equivalent npm tarball from the exact PR head, validates
# THAT build (check:pack-artifact + check:pack-boot, which installs the packed
# tarball into a clean prefix and boots it with fake secrets on an isolated
# DATA_DIR), records its identity (head SHA + base SHA + lockfile hash +
# platform/arch/node ABI + build policy, scripts/release/artifact-identity.mjs),
# uploads tarball + identity + SHA256SUMS and attests the tarball's provenance.
# The uploaded bytes are what a preview install or a promotion consumes: there is
# no second source build anywhere downstream.
#
# Out of scope on purpose: publishing (nothing here talks to a registry), DB-clone
# migration rehearsal (#8084 reply 3 — its own subsystem) and live provider probes.
#
# Triggers: `workflow_dispatch` with a PR number, or adding the `preview-artifact`
# label to a PR. Fork PRs are never built: the label path checks
# head.repo.full_name in the job `if:`, the dispatch path re-checks it from the API
# before anything is checked out. This runs PR code (same-repository branches
# only), so the build job holds a read-only token and no OIDC permission; the
# OIDC/attestation permissions live in the separate `attest` job, which never
# checks out or executes repository code.
on:
workflow_dispatch:
inputs:
pr_number:
description: "Pull request number to build (same-repository PRs only)"
required: true
type: string
pull_request:
types: [labeled]
permissions:
contents: read # default for every job; each job narrows or extends below
concurrency:
group: preview-artifact-${{ github.event.pull_request.number || inputs.pr_number }}
cancel-in-progress: true
env:
PREVIEW_NODE_VERSION: "24"
jobs:
resolve:
name: Resolve PR head and base
if: >-
github.event_name == 'workflow_dispatch' ||
(github.event.label.name == 'preview-artifact' &&
github.event.pull_request.head.repo.full_name == github.repository)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
pull-requests: read # gh api repos/<repo>/pulls/<N> (head repo, state, SHAs)
outputs:
pr_number: ${{ steps.pr.outputs.pr_number }}
head_sha: ${{ steps.pr.outputs.head_sha }}
base_sha: ${{ steps.pr.outputs.base_sha }}
base_ref: ${{ steps.pr.outputs.base_ref }}
steps:
- name: Resolve the PR and refuse forks
id: pr
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
EVENT_PR: ${{ github.event.pull_request.number }}
INPUT_PR: ${{ inputs.pr_number }}
run: |
set -euo pipefail
PR="${EVENT_PR:-$INPUT_PR}"
if ! printf '%s' "$PR" | grep -qE '^[0-9]+$'; then
echo "::error::pr_number must be a positive integer"
exit 1
fi
DATA=$(gh api "repos/$REPO/pulls/$PR")
HEAD_REPO=$(jq -r '.head.repo.full_name // ""' <<<"$DATA")
STATE=$(jq -r '.state' <<<"$DATA")
HEAD_SHA=$(jq -r '.head.sha' <<<"$DATA")
BASE_REF=$(jq -r '.base.ref' <<<"$DATA")
if [ "$HEAD_REPO" != "$REPO" ]; then
echo "::error::PR #$PR comes from a fork ($HEAD_REPO) — preview artifacts are built for same-repository branches only"
exit 1
fi
if [ "$STATE" != "open" ]; then
echo "::error::PR #$PR is $STATE — preview artifacts are built for open PRs only"
exit 1
fi
# The base SHA recorded in the identity is the base branch tip at build time.
BASE_SHA=$(gh api "repos/$REPO/git/ref/heads/$BASE_REF" --jq '.object.sha')
{
echo "pr_number=$PR"
echo "head_sha=$HEAD_SHA"
echo "base_sha=$BASE_SHA"
echo "base_ref=$BASE_REF"
} >> "$GITHUB_OUTPUT"
echo "PR #$PR head=$HEAD_SHA base=$BASE_REF@$BASE_SHA"
build:
name: Build once, validate, upload
needs: resolve
# Same pool rule as npm-publish.yml: the hosted runner cannot hold `next build`
# for this tree any more (#11946). The fork clause is redundant here (resolve
# already refused forks) and is kept so the expression stays greppable.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && fromJSON('["self-hosted","omni-build"]') || 'ubuntu-latest' }}
timeout-minutes: 120
permissions:
contents: read # checkout + git fetch refs/pull/<N>/head — read-only, no OIDC
outputs:
artifact_name: ${{ steps.name.outputs.artifact_name }}
env:
# Fake, build-time-only values. No real secret is ever exposed to this job.
JWT_SECRET: preview-artifact-fake-jwt-secret-with-sufficient-length
API_KEY_SECRET: preview-artifact-fake-api-key-secret-0000000000000000
steps:
- name: Checkout the PR head
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ needs.resolve.outputs.head_sha }}
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: ${{ env.PREVIEW_NODE_VERSION }}
package-manager-cache: false
- name: Install dependencies (npm ci)
uses: ./.github/actions/npm-ci-retry
with:
# A promotable artifact is never built from a cached node_modules.
cache: "false"
- name: Build release bundle
run: npm run build:release
# check:pack-artifact's provenance guard (#10427) needs a ref the stamped head
# is an ancestor of. refs/pull/<N>/head exists in this repository for every PR.
- name: Fetch the PR head ref for the provenance guard
env:
PR_NUMBER: ${{ needs.resolve.outputs.pr_number }}
run: |
git fetch --no-tags --depth=50 origin \
"+refs/pull/$PR_NUMBER/head:refs/remotes/origin/pr-head"
- name: Validate the npm package artifact
env:
OMNIROUTE_RELEASE_REF: origin/pr-head
run: npm run check:pack-artifact
- name: Pack the tarball (the bytes that get uploaded)
id: pack
run: |
set -euo pipefail
OUT_DIR="$RUNNER_TEMP/preview-artifact"
mkdir -p "$OUT_DIR"
FILE=$(npm pack --json --pack-destination "$OUT_DIR" | jq -r '.[0].filename' | tr '/' '-')
test -f "$OUT_DIR/$FILE"
SHA=$(sha256sum "$OUT_DIR/$FILE" | cut -d' ' -f1)
{
echo "dir=$OUT_DIR"
echo "file=$FILE"
echo "sha256=$SHA"
} >> "$GITHUB_OUTPUT"
echo "packed $FILE sha256=$SHA"
# Packs the same tree again, installs it into a clean prefix and boots it with
# fake JWT/API-key secrets on an ephemeral DATA_DIR (the script also forces its
# own isolated values for the spawned server).
- name: Boot-smoke the packed tarball
env:
DATA_DIR: ${{ runner.temp }}/preview-artifact-data
run: npm run check:pack-boot
# Build once: the tree must not have changed while it was being validated, and
# `npm pack` must reproduce the uploaded bytes exactly — otherwise what booted
# and what gets uploaded are not provably the same artifact.
- name: Prove the validated bytes are the uploaded bytes
env:
OUT_DIR: ${{ steps.pack.outputs.dir }}
FILE: ${{ steps.pack.outputs.file }}
EXPECTED_SHA: ${{ steps.pack.outputs.sha256 }}
run: |
set -euo pipefail
RECHECK="$RUNNER_TEMP/preview-artifact-recheck"
mkdir -p "$RECHECK"
npm pack --pack-destination "$RECHECK" >/dev/null
ACTUAL=$(sha256sum "$RECHECK/$FILE" | cut -d' ' -f1)
if [ "$ACTUAL" != "$EXPECTED_SHA" ]; then
echo "::error::re-pack digest $ACTUAL != uploaded $EXPECTED_SHA — the artifact is not reproducible from the validated tree"
exit 1
fi
rm -rf "$RECHECK"
echo "re-pack reproduces $FILE byte for byte"
- name: Record the artifact identity
env:
HEAD_SHA: ${{ needs.resolve.outputs.head_sha }}
BASE_SHA: ${{ needs.resolve.outputs.base_sha }}
OUT_DIR: ${{ steps.pack.outputs.dir }}
FILE: ${{ steps.pack.outputs.file }}
run: |
set -euo pipefail
node scripts/release/artifact-identity.mjs \
--head "$HEAD_SHA" \
--base "$BASE_SHA" \
--lockfile package-lock.json \
--tarball "$OUT_DIR/$FILE" \
--out "$OUT_DIR/artifact-identity.json"
(cd "$OUT_DIR" && sha256sum "$FILE" artifact-identity.json > SHA256SUMS)
- name: Name the workflow artifact
id: name
env:
PR_NUMBER: ${{ needs.resolve.outputs.pr_number }}
HEAD_SHA: ${{ needs.resolve.outputs.head_sha }}
run: echo "artifact_name=preview-artifact-pr${PR_NUMBER}-${HEAD_SHA:0:7}" >> "$GITHUB_OUTPUT"
- name: Upload tarball + identity
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: ${{ steps.name.outputs.artifact_name }}
path: ${{ steps.pack.outputs.dir }}
if-no-files-found: error
retention-days: 14
attest:
name: Attest build provenance
needs: build
# GitHub-hosted on purpose: attestation signing uses the job's OIDC token, and
# this job never checks out or runs repository code.
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read # required by attest-build-provenance
id-token: write # Sigstore signing of the provenance statement
attestations: write # store the attestation on this repository
steps:
- name: Download the uploaded artifact
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: ${{ needs.build.outputs.artifact_name }}
path: preview-artifact
- name: Verify checksums
working-directory: preview-artifact
run: sha256sum -c SHA256SUMS
- name: Attest the tarball
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
with:
subject-path: preview-artifact/*.tgz

View File

@@ -1,558 +0,0 @@
name: Quality Gates
on:
push:
# release/** pushes are covered by the PR run of each change plus Release-Green on the
# merged combination (see ci.yml for the 2026-10-18 measurement); the per-push run here
# only ever queued hosted slots and was cancelled by the next merge.
branches: [main]
pull_request:
branches: [main, "release/**"]
types: [opened, synchronize, reopened, ready_for_review, converted_to_draft, edited]
merge_group:
types: [checks_requested]
workflow_dispatch:
# A description edit on a Mergify queue draft (Mergify writes its queue summary there, and
# the Blacksmith app appends its footer, ~4 edits in the first 30 s) gets its own group and
# skips the matrix: in the shared group it cancelled the candidate's real run, and Mergify
# dequeued the PR on the cancelled checks ("checks interrupted", #18853/#18858 on 2026-11-03).
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}${{ (github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.pull_request.user.login == 'mergify[bot]' && startsWith(github.head_ref, 'mergify/merge-queue/') && github.event.pull_request.head.repo.id == github.event.repository.id) && format('-queue-edit-{0}', github.run_id) || '' }}
cancel-in-progress: true
permissions:
contents: read
env:
# CI must never mutate the runner's OS trust store (2026-07-05: a cert-flow
# test installed a fake PEM on a persistent self-hosted runner and broke all
# system TLS). Belt-and-suspenders with tests/_setup/isolateDataDir.ts.
OMNIROUTE_SKIP_SYSTEM_TRUST: "1"
CI_NODE_VERSION: "24"
jobs:
# Same classifier as ci.yml (scripts/quality/classify-pr-changes.mjs) so PR→release
# path filters share existence reasons: code / docs / i18n / workflow.
changes:
name: Change Classification
if: ${{ !(github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.pull_request.user.login == 'mergify[bot]' && startsWith(github.head_ref, 'mergify/merge-queue/') && github.event.pull_request.head.repo.id == github.event.repository.id) }}
runs-on: ubuntu-latest
outputs:
code: ${{ steps.classify.outputs.code }}
docs: ${{ steps.classify.outputs.docs }}
i18n: ${{ steps.classify.outputs.i18n }}
workflow: ${{ steps.classify.outputs.workflow }}
testsOnly: ${{ steps.classify.outputs.testsOnly }}
# Exposure only (one-CI-policy step 1, RFC #8084): no job depends on it yet.
domains: ${{ steps.classify.outputs.domains }}
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
fetch-depth: 0
- uses: actions/setup-node@v7
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- name: Validate gate inventory
run: npm run check:gate-manifest
- name: Validate recurring free catalog evidence
env:
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
run: npm run check:free-catalog-evidence
- id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
if [ "$EVENT_NAME" != "pull_request" ]; then
{
echo "code=true"
echo "docs=true"
echo "i18n=true"
echo "workflow=true"
echo "testsOnly=false"
echo "domains=build,catalog,cli,core,db,docs,i18n,provider,routing,tests,ui,workflow"
} >> "$GITHUB_OUTPUT"
exit 0
fi
git diff --name-only "$BASE_SHA" "$HEAD_SHA" > changed-files.txt
node scripts/quality/classify-pr-changes.mjs changed-files.txt >> "$GITHUB_OUTPUT"
# Full build/package/boot authority lives in CI; no permanently skipped duplicate.
# Docs/OpenAPI contract gates only — existence reason is doc accuracy + route refs.
# Split out of fast-gates so pure-docs PRs skip typecheck/unit while still validating docs.
docs-gates:
name: Docs Gates (fast-path)
needs: changes
if: ${{ github.event_name != 'pull_request' || ((github.event.pull_request.draft == false || startsWith(github.head_ref, 'mergify/merge-queue/')) && (needs.changes.outputs.docs == 'true' || needs.changes.outputs.code == 'true')) }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- uses: ./.github/actions/npm-ci-retry
with:
# PR acceleration is not release-candidate provenance.
cache: ${{ github.event_name == 'pull_request' }}
# One walk of src/app/api for openapi-routes + docs-symbols (both still fail independently).
- run: npm run check:api-docs-refs
- name: Docs accuracy (fabricated-docs + i18n mirrors, strict)
run: npm run check:docs-all
fast-gates:
name: Fast Quality Gates
needs: changes
# Code surface only — pure docs/i18n PRs skip this bag (docs-gates covers docs).
if: ${{ github.event_name != 'pull_request' || ((github.event.pull_request.draft == false || startsWith(github.head_ref, 'mergify/merge-queue/')) && needs.changes.outputs.code == 'true') }}
# Dynamic runner (same rule as ci.yml): use the self-hosted VPS pool only when the
# release captain has USE_VPS_RUNNER=true AND this is not a fork PR (own-origin
# branches only — a fork PR must never execute on the LAN runner). Var unset/false
# or a fork PR falls back to ubuntu-latest, so this is inert until the flag flips.
# PINNED to hosted (gap 19). This job carried the USE_VPS_RUNNER expression, and that
# expression was DEAD CONFIGURATION: across 160 quality.yml runs the job never once landed on
# a self-hosted runner — every non-skipped sample is `GitHub Actions NNNN`. The classifier is
# not at fault: in the same window ci.yml's Build demonstrably ran on omniroute-113-7 and
# omniroute-113-6, so self-hosted runs are visible when they happen.
#
# And if it ever HAD fired it would have inherited the measured penalty, because this job's
# first two steps are exactly the bottleneck: actions/setup-node + npm ci took 20m06s on .113
# with 4 concurrent runners versus 16s hosted (npm cache restore saturating the link). Median
# here is 5.6 min hosted across 72 successful runs.
#
# With this pinned, USE_VPS_RUNNER governs ONLY build-like jobs — one variable, one coherent
# purpose. That is what gap 19 asked for; a second variable turned out to be unnecessary.
runs-on: ubuntu-latest
# tsx gates (known-symbols, route-guard-membership) import modules that open
# SQLite on load; provide DB env so a fresh CI DB initializes cleanly.
env:
JWT_SECRET: ci-lint-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-lint-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-node@v7
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- uses: ./.github/actions/npm-ci-retry
with:
# PR acceleration is not release-candidate provenance.
cache: ${{ github.event_name == 'pull_request' }}
- name: Restore ESLint file cache
if: github.event_name == 'pull_request'
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
with:
path: |
.eslintcache
.eslintcache-complexity
key: eslint-${{ runner.os }}-${{ hashFiles('eslint.config.mjs', 'eslint.complexity-ratchets.config.mjs', 'config/quality/eslint-suppressions.json', 'package-lock.json') }}
# No restore-keys fallback on purpose (#11600, P-II.1 of the v3.8.50 postmortem): a
# cache built under a different suppressions file / lint config / lockfile reports
# stale per-file verdicts, which is exactly how 215 pre-existing errors stayed
# invisible for a whole cycle. Exact key or a cold full lint (~13 min) — never a
# partial cache from another configuration.
# Security scanners — same hardened install as ci.yml quality-extended
# (gh release download = authenticated, 5000 req/hr; curl to api.github.com
# is rate-limited to 60/hr and silently no-ops when throttled). The blocking
# gates below SKIP (exit 0) when their binary is absent — only a measured
# regression vs config/quality/quality-baseline.json blocks.
- name: Install security scanners (gitleaks/osv/actionlint/zizmor/oasdiff)
continue-on-error: true
env:
GH_TOKEN: ${{ github.token }}
run: |
set +e
mkdir -p "$HOME/.local/bin"
# Ratchets compare scanner COUNTS across runs. Pin every auditor: a rule-set
# update must be an explicit PR that re-measures/rebaselines, never a random
# red (or green) caused by whatever "latest" served that morning.
GITLEAKS_VERSION=v8.30.1
OSV_SCANNER_VERSION=v2.3.8
ACTIONLINT_VERSION=v1.7.12
ZIZMOR_VERSION=1.25.2
OASDIFF_VERSION=v1.19.1
# gitleaks — pinned linux x64 tarball via gh (authed), extract binary
rm -rf /tmp/gl && mkdir -p /tmp/gl
gh release download "$GITLEAKS_VERSION" --repo gitleaks/gitleaks --pattern '*linux_x64.tar.gz' --dir /tmp/gl
tar -xzf /tmp/gl/*linux_x64.tar.gz -C "$HOME/.local/bin" gitleaks
# osv-scanner — pinned linux amd64 bare binary via gh (authed)
rm -rf /tmp/osv && mkdir -p /tmp/osv
gh release download "$OSV_SCANNER_VERSION" --repo google/osv-scanner --pattern '*linux_amd64' --dir /tmp/osv
install -m 0755 /tmp/osv/*linux_amd64 "$HOME/.local/bin/osv-scanner"
# actionlint — official installer from a pinned release tag (never main)
bash <(curl -fsSL "https://raw.githubusercontent.com/rhysd/actionlint/${ACTIONLINT_VERSION}/scripts/download-actionlint.bash") "${ACTIONLINT_VERSION#v}" "$HOME/.local/bin"
# zizmor — pinned PyPI package (same version as ci.yml quality-extended)
pipx install "zizmor==$ZIZMOR_VERSION" || pip install --user "zizmor==$ZIZMOR_VERSION"
# oasdiff — pinned linux amd64 tarball via gh (authed), extract binary
rm -rf /tmp/oasd && mkdir -p /tmp/oasd
gh release download "$OASDIFF_VERSION" --repo Tufin/oasdiff --pattern '*linux_amd64.tar.gz' --dir /tmp/oasd
tar -xzf /tmp/oasd/*linux_amd64.tar.gz -C "$HOME/.local/bin" oasdiff
# ALWAYS export the bin dir (even if any step above failed)
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
"$HOME/.local/bin/gitleaks" version || true
"$HOME/.local/bin/actionlint" -version || true
"$HOME/.local/bin/osv-scanner" --version || true
"$HOME/.local/bin/oasdiff" --version || true
zizmor --version || true
- name: Forgotten sibling tests (advisory)
env:
GITHUB_BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
node scripts/quality/build-test-impact-map.mjs
node scripts/check/check-forgotten-sibling-tests.mjs \
--summary-file forgotten-sibling-tests.md \
--json-file forgotten-sibling-tests.json
cat forgotten-sibling-tests.md >> "$GITHUB_STEP_SUMMARY"
- name: Upload forgotten sibling report
if: always()
uses: actions/upload-artifact@v7
with:
name: forgotten-sibling-tests
path: |
forgotten-sibling-tests.md
forgotten-sibling-tests.json
if-no-files-found: ignore
retention-days: 30
# Quality gates (all, non-fail-fast) — #8542: replaces 17 bare check:* steps,
# 6 G0 gates, 4 ratchet gates, and 3 typecheck steps with a single aggregation
# step. Each gate runs in a loop with ::group::; failures are collected and
# reported at the end. set -uo pipefail (NOT set -e) so one failing gate does
# not abort the job and mask every later gate. Release-added gates are folded
# in: open-sse typecheck (#8781) and file-size base-relative mode (#8522).
- name: Quality gates (all, non-fail-fast)
env:
# #8522: base-relative file-size mode on PR events — inherited drift (base
# already over frozen cap) must not red an innocent PR. Unset on
# workflow_dispatch (no PR base) → absolute comparison.
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
BASE_REF: ${{ github.base_ref && format('origin/{0}', github.base_ref) || '' }}
run: |
set -uo pipefail
gates=(
provider-consistency provider-asset-provenance fetch-targets deps file-size error-helper
migration-numbering public-creds db-rules known-symbols
route-guard-membership test-discovery test-runner-api
mutation-test-coverage any-budget:t11 build-scope pack-policy
complexity-ratchets model-lifecycle
lockfile duplication dead-code type-coverage compression-budget
# #8781: open-sse workspace typecheck gate — the workspace imports @/ which
# escapes to src/ via undeclared path aliases. See check-open-sse-typecheck.mjs.
open-sse-typecheck
# Hard Rule #16 — AI/bot attribution in PR commits, title or body (#14436). Reads the PR
# from GITHUB_EVENT_PATH; no-op on non-PR events. ci.yml only runs on PRs to main.
ai-attribution
)
# Ratchet-mode gates append --ratchet. `cycles` belongs here since #15281
# (69cb18dca8): check-cycles.mjs exits 1 on ANY cycle without --ratchet, and
# the frozen ceiling lives in quality-baseline.json → metrics.cycles — same
# `check:cycles:ratchet` semantics ci.yml runs (base-red #15306). `boundary`
# caps the open-sse → src edge count (measure-boundary.mjs --ratchet, ceiling
# quality-baseline.json → metrics.boundaryOpenSseToSrc) — same as ci.yml lint.
ratchet_gates=(
secrets vuln-ratchet workflows openapi-breaking cycles boundary
)
failed=()
for g in "${gates[@]}"; do
echo "::group::check:$g"
# #8522: file-size is base-relative on PR events (compare against
# max(frozen, base)) so inherited drift doesn't red an innocent PR;
# workflow_dispatch (no PR base) falls back to absolute comparison.
# New-code mode (Clean-as-You-Code, 2026-08-30): complexity-ratchets and
# dead-code compare the PR's files against the merge-base and block only on
# what the PR added; the global totals are advisory on PRs and re-frozen at
# release. See scripts/check/newCodeMode.mjs.
case "$g" in file-size|complexity-ratchets|dead-code) NEW_CODE=1 ;; *) NEW_CODE= ;; esac
if [ -n "$NEW_CODE" ] && [ -n "${PR_BASE_SHA:-}" ]; then
npm run "check:$g" -- --base-ref "$PR_BASE_SHA" || failed+=("$g")
else
npm run "check:$g" || failed+=("$g")
fi
echo "::endgroup::"
done
for g in "${ratchet_gates[@]}"; do
echo "::group::check:$g (ratchet)"
# boundary is base-relative on PR events, like file-size (#8522): the ceiling
# becomes max(baseline ceiling, edges on the PR base), so open-sse → src edges
# other merges added after the seed never red an innocent PR; only edges this
# PR adds block. workflow_dispatch (no PR base) keeps the absolute ceiling.
case "$g" in boundary) BASE_RELATIVE=1 ;; *) BASE_RELATIVE= ;; esac
if [ -n "$BASE_RELATIVE" ] && [ -n "${PR_BASE_SHA:-}" ]; then
npm run "check:$g" -- --ratchet --base-ref "$PR_BASE_SHA" || failed+=("$g")
else
npm run "check:$g" -- --ratchet || failed+=("$g")
fi
echo "::endgroup::"
done
echo "::group::typecheck:core"
npm run typecheck:core || failed+=("typecheck:core")
echo "::endgroup::"
echo "::group::check:dashboard-typecheck"
npm run check:dashboard-typecheck || failed+=("check:dashboard-typecheck")
echo "::endgroup::"
echo "::group::check:build-typecheck"
npm run check:build-typecheck || failed+=("check:build-typecheck")
echo "::endgroup::"
# #10134: TS7 zero-new-diagnostics ratchet — folded into this non-fail-fast
# loop (never a separate blocking step) so an earlier red gate cannot abort
# the job and mask it (#8542 mechanism). PR-only: the base-relative
# comparison needs the PR base SHA (empty on workflow_dispatch).
if [ -n "${PR_BASE_SHA:-}" ]; then
echo "::group::check:ts7-diagnostics-ratchet"
npm run check:ts7-diagnostics-ratchet -- --base-ref "$PR_BASE_SHA" || failed+=("ts7-diagnostics-ratchet")
echo "::endgroup::"
fi
if (( ${#failed[@]} )); then
printf '::error::%d gate(s) failed: %s\n' "${#failed[@]}" "${failed[*]}"
exit 1
fi
# WS4.2 (v3.8.49 plan): TypeScript 7 native-compiler SHADOW — advisory only.
# TS7 went GA 2026-07-08 with 8-12x type-check speedups; its Compiler API only
# arrives in 7.1, so typescript-eslint / type-coverage / Stryker stay on 6.x
# (the hybrid is the officially documented pattern). Isolated npx on purpose:
# installing an alias package could collide node_modules/.bin/tsc with 6.x.
# The full result stays advisory while #8484 has a backlog. The blocking
# base-relative ratchet (folded into the non-fail-fast gates step above)
# rejects only diagnostics added by the PR, so existing release debt does
# not block unrelated work.
- name: Typecheck (core) — TS7 native shadow (advisory)
continue-on-error: true
run: |
RC=0
START=$(date +%s)
npm exec --yes --package=typescript@7.0.2 -- tsc --pretty false -p tsconfig.typecheck-core.json || RC=$?
echo "[ts7-shadow] exit=$RC elapsed=$(( $(date +%s) - START ))s — the 6.x step above stays authoritative"
exit $RC
# TIA: build the impact map at runtime (gitignored, ~21MB) and run only the
# unit tests impacted by this PR's changed files. On hub/unmapped changes the
# selector returns __RUN_ALL__ — full-suite authority is ci.yml's `test-unit`
# 8-shard job (test:unit:ci:shard), NOT an unsharded re-run here. Stacking an
# unsharded test:unit:ci on top of it doubled wall time without extra coverage.
# (quality.yml had its own 4-shard `fast-unit` + `fast-vitest` for PR->release from
# 2026-06-23; ci.yml runs on those PRs since #14420 (2026-10-01), so both were an
# exact duplicate — ~62 runner-min and 5 hosted jobs per PR — and were removed.)
#
# BLOCKING for the *impacted subset* (flipped 2026-06-17). Fail-safe full
# coverage remains required via ci.yml `Unit Tests (N/8)` (test-unit).
- name: Impacted unit tests (TIA subset; blocking)
env:
GITHUB_BASE_REF: ${{ github.base_ref }}
run: |
git fetch --no-tags origin "$GITHUB_BASE_REF" || true
# The advisory sibling-test step generates the same map earlier in this job.
[ -f config/quality/test-impact-map.json ] || node scripts/quality/build-test-impact-map.mjs
SEL="$(node scripts/quality/select-impacted-tests.mjs)"
# Shadow evidence (#8084): persist every selection so TIA false negatives can
# be measured against ci.yml test-unit's full-suite verdict across releases BEFORE
# any gate authority moves off ordinary PRs. Artifact uploaded below.
printf '%s\n' "$SEL" > tia-selection.txt
if [ -z "$SEL" ]; then
echo "TIA selection: empty (no source/test changes)" >> "$GITHUB_STEP_SUMMARY"
echo "No source/test changes — skipping unit tests"; exit 0
fi
# CI runners are 4-vCPU; run at --test-concurrency=4 (matching the ci.yml unit
# job) rather than test:unit's local-tuned concurrency=20. Oversubscribing the
# runner makes timing-sensitive tests (db-backup, upstream-timeout, ...) flake,
# which must not happen on a blocking gate. DATA_DIR isolation keeps the parallel
# run race-free regardless of concurrency.
if echo "$SEL" | grep -q "__RUN_ALL__"; then
echo "TIA selection: __RUN_ALL__ (fail-safe) — full-suite authority stays with ci.yml test-unit" >> "$GITHUB_STEP_SUMMARY"
echo "Fail-safe: __RUN_ALL__ — deferring FULL unit suite to ci.yml test-unit (8-shard)."
echo "Not re-running unsharded test:unit:ci here (duplicate of test-unit coverage)."
exit 0
fi
echo "TIA selection: $(grep -c . tia-selection.txt) impacted test file(s) — full suite still runs in ci.yml test-unit (shadow-evidence phase, #8084)" >> "$GITHUB_STEP_SUMMARY"
echo "Running impacted tests:"; echo "$SEL"
mapfile -t FILES <<< "$SEL"
# Loader parity with test:unit:ci:shard (#6787): tests/unit/dashboard/** runs
# under `--import tsx` (CJS transform — required for ESM-only deep imports like
# @lobehub/icons/es/* reached via lobeProviderIcons.ts); everything else under
# `--import tsx/esm`. A single tsx/esm invocation false-reds every dashboard
# module-shape test the impact map selects ("Unexpected token 'export'").
DASH=(); REST=()
for f in "${FILES[@]}"; do
case "$f" in
tests/unit/dashboard/*) DASH+=("$f") ;;
*) REST+=("$f") ;;
esac
done
RC=0
if [ ${#REST[@]} -gt 0 ]; then
node --import tsx/esm --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 "${REST[@]}" || RC=$?
fi
if [ ${#DASH[@]} -gt 0 ]; then
node --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 "${DASH[@]}" || RC=$?
fi
exit $RC
# #8084 shadow evidence: keep the raw selection downloadable so TIA misses can be
# audited against ci.yml test-unit failures on the same commit (gate moves need this data).
- name: Upload TIA selection (shadow evidence)
if: always()
uses: actions/upload-artifact@v7
with:
name: tia-selection
path: tia-selection.txt
if-no-files-found: ignore
retention-days: 30
# ── Pacote 4 (plano mestre testes+CI, aprovado 2026-07-04) ─────────────────────────
# No-new-warnings por PR via ESLint bulk suppressions nativo (>=9.24). O baseline
# config/quality/eslint-suppressions.json congela as violações EXISTENTES por
# arquivo+regra; qualquer warning NOVO aparece e o --max-warnings 0 falha o job — o
# drift de +41/+88 warnings por ciclo passa a morrer no PR que o introduz, em vez de
# ser rebaselinado às cegas na release. Aperto do baseline (na reconciliação da
# release): npx eslint . --prune-suppressions --suppressions-location config/quality/eslint-suppressions.json
#
# Forks use hosted runners and the same required code-quality result. A base-red
# is maintainer work, but must not be reported as a passing candidate.
lint-guard:
name: No new ESLint warnings
needs: changes
if: ${{ github.event_name != 'pull_request' || ((github.event.pull_request.draft == false || startsWith(github.head_ref, 'mergify/merge-queue/')) && needs.changes.outputs.code == 'true') }}
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && github.event_name != 'merge_group' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
# 2026-08-30: a cold full lint with the eslint-plugin-react-hooks 7 compiler rules is
# killed on the 7 GB hosted runner without a message (status null → exit 1, the
# JSON never written); the box lints it in ~12 min with the heap below.
# G0 (trilho .50): security-events:read lets the CodeQL ratchet below read open
# code-scanning alerts via `gh api .../code-scanning/alerts` (same as ci.yml's
# quality-gate job). contents: read keeps checkout working.
permissions:
contents: read
security-events: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- uses: ./.github/actions/npm-ci-retry
with:
# PR acceleration is not release-candidate provenance.
cache: ${{ github.event_name == 'pull_request' }}
- name: Restore ESLint file cache
if: github.event_name == 'pull_request'
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
with:
path: |
.eslintcache
.eslintcache-complexity
key: eslint-${{ runner.os }}-${{ hashFiles('eslint.config.mjs', 'eslint.complexity-ratchets.config.mjs', 'config/quality/eslint-suppressions.json', 'package-lock.json') }}
# No restore-keys fallback on purpose (#11600, P-II.1 of the v3.8.50 postmortem): a
# cache built under a different suppressions file / lint config / lockfile reports
# stale per-file verdicts, which is exactly how 215 pre-existing errors stayed
# invisible for a whole cycle. Exact key or a cold full lint (~13 min) — never a
# partial cache from another configuration.
- name: ESLint (baseline congelado — warning novo = vermelho)
# lint:json writes the report; --max-warnings 0 keeps no-new-warnings policy.
run: npm run lint:json -- --max-warnings 0
env:
NODE_OPTIONS: --max-old-space-size=8192
# ── G0 (trilho .50): motor de ratchet também no trilho B ─────────────────────
# This job just wrote .artifacts/eslint-results.json — collect-metrics prefers
# that file, so the ratchet engine lands here at ZERO extra ESLint cost (one
# inventory, two consumers; same reason ci.yml chains lint → quality-gate).
# The coverage-report artifact does not exist on this rail, so both ratchet
# invocations run --allow-missing: coverage.* metrics skip gracefully while
# the deterministic ones (eslint / openapi-coverage / i18n-ui) stay BLOCKING.
# Coverage authority remains on the main rail (ci.yml test-coverage → quality-gate).
- run: npm run quality:collect
- name: Ratchet check (blocking)
run: node scripts/quality/check-quality-ratchet.mjs --allow-missing --summary .artifacts/quality-ratchet.md
- name: Require-tighten (blocking)
run: node scripts/quality/check-quality-ratchet.mjs --allow-missing --require-tighten
# CodeQL alerts ratchet — same semantics as ci.yml quality-gate: exits 1 ONLY
# on a real regression (open alerts > baseline in quality-baseline.json);
# a measurement failure (gh/auth/api) self-skips with exit 0.
- name: CodeQL alerts ratchet (blocking)
run: npm run check:codeql-ratchet
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Append ratchet summary
if: always()
run: cat .artifacts/quality-ratchet.md >> "$GITHUB_STEP_SUMMARY" || true
# Merge-integrity: pega no PR os dois vazamentos crônicos de merge que hoje só
# explodem na release-PR. (1) CHANGELOG-eat — o auto-resolve do merge come
# bullets vizinhos/seções inteiras (incidente #6193, 2026-07-05: 212 linhas /
# 130 bullets); o checkout de PR é refs/pull/N/merge, então comparar contra a
# base detecta o eat ANTES do merge. (2) SKILL.md gerado stale vs o catálogo de
# agent-skills (#6186 mergeou um id de catálogo sem rodar o gerador → 8 reds de
# integration invisíveis até a release).
#
# Merge integrity is required regardless of who owns the PR branch.
merge-integrity:
name: Merge integrity (changelog + generated skills)
# Always on non-draft PRs — CHANGELOG/skills can break on docs-only merges too.
if: ${{ github.event_name != 'pull_request' || (github.event.pull_request.draft == false || startsWith(github.head_ref, 'mergify/merge-queue/')) }}
runs-on: ubuntu-latest
env:
JWT_SECRET: ci-lint-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-lint-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v6
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- uses: ./.github/actions/npm-ci-retry
with:
# PR acceleration is not release-candidate provenance.
cache: ${{ github.event_name == 'pull_request' }}
- name: CHANGELOG integrity (nenhum bullet da base pode sumir no merge-result)
run: npm run check:changelog-integrity
- name: Agent-skills generator sync (SKILL.md gerado ≡ catálogo)
run: npm run check:agent-skills-sync
admission-verdict:
# A queue-draft edit run must not leave a check named "Gate / Quality" on the draft: Mergify
# read that skipped check as a finished non-success and dequeued the PR (#18961 on
# 2026-11-04) before the real run reported. Every other run keeps the exact name.
name: ${{ (github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.pull_request.user.login == 'mergify[bot]' && startsWith(github.head_ref, 'mergify/merge-queue/') && github.event.pull_request.head.repo.id == github.event.repository.id) && 'Gate / Quality (queue-draft edit)' || 'Gate / Quality' }}
# Runs on every candidate; only a Mergify queue-draft description edit skips it (see the
# workflow concurrency note): that draft is never what branch protection merges.
if: ${{ always() && !(github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.pull_request.user.login == 'mergify[bot]' && startsWith(github.head_ref, 'mergify/merge-queue/') && github.event.pull_request.head.repo.id == github.event.repository.id) }}
runs-on: ubuntu-latest
timeout-minutes: 5
needs:
- changes
- docs-gates
- fast-gates
- lint-guard
- merge-integrity
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: ${{ github.sha }}
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- name: Evaluate exact-candidate admission
env:
NEEDS_JSON: ${{ toJSON(needs) }}
run: node scripts/quality/admission-verdict.mjs quality
- name: Retain admission receipt
if: ${{ always() }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: quality-admission-${{ github.run_id }}-${{ github.run_attempt }}
path: .artifacts/quality-admission.json
if-no-files-found: error
retention-days: 14

View File

@@ -1,73 +0,0 @@
# Publica o export estável do catálogo consumido pelo OmniRoute Radar numa URL
# fixa (asset de release `radar-export-latest`), para o servidor privado do Radar
# (1 GB RAM, nunca clona/builda o OmniRoute) baixá-lo via `RADAR_EXPORT_URL` em
# vez de depender do snapshot gravado no deploy. Fonte: scripts/release/radar-export.mjs.
#
# A URL estável resultante (definir em RADAR_EXPORT_URL no .env do radar-server):
# https://github.com/cheaper-inference/OmniRoute/releases/download/radar-export-latest/export-omniroute.json
name: Radar Export
on:
workflow_dispatch: # o operador pode publicar sob demanda (de qualquer ref)
push:
# `main` e a release ativa (default branch) publicam no mesmo asset estável: o
# radar-server só consome o asset, então um merge de catálogo na release que ficasse
# à espera do cron semanal deixava o feed até 7 dias atrás do README (2026-09-14: a
# linha da Together removida em d6e62ae só saiu do feed com dispatch manual).
branches: [main, "release/**"]
paths:
- open-sse/config/freeModelCatalog.data.ts
- open-sse/config/freeModelCatalog.ts
- open-sse/config/providerRegistry.ts
- open-sse/config/providers/**
- scripts/release/radar-export.mjs
- .github/workflows/radar-export.yml
schedule:
# Diário 03:17 UTC — antes do `radar-feed.timer` do servidor (04:23 UTC), para o ciclo
# do dia já enxergar o export do dia; também mantém geradoEm/proveniência frescos.
- cron: "17 3 * * *"
permissions:
contents: read
concurrency:
group: radar-export-${{ github.ref }}
cancel-in-progress: true
env:
CI_NODE_VERSION: "24"
jobs:
publish-export:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
runs-on: ubuntu-latest
permissions:
contents: write # gh release upload — clobra o asset estável do export
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false # publish usa GH_TOKEN via gh release, não a credencial do checkout
- uses: actions/setup-node@v7
with:
node-version: ${{ env.CI_NODE_VERSION }}
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Generate catalog export with provenance
run: node --import tsx/esm scripts/release/radar-export.mjs "$RUNNER_TEMP/export-omniroute.json"
- name: Publish to the stable release asset
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
TAG="radar-export-latest"
# Cria o release estável na primeira vez; nas seguintes só re-anexa o asset.
if ! gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
gh release create "$TAG" \
--repo "$GITHUB_REPOSITORY" \
--title "Radar catalog export (rolling)" \
--notes "Export estável do catálogo OmniRoute para o Radar. Atualizado automaticamente; NÃO é um release de versão do produto." \
--latest=false
fi
gh release upload "$TAG" "$RUNNER_TEMP/export-omniroute.json" --repo "$GITHUB_REPOSITORY" --clobber

View File

@@ -1,44 +0,0 @@
name: Release acceptance
on:
push:
branches: ["release/v*"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: release-acceptance-${{ github.ref }}
cancel-in-progress: false
jobs:
acceptance:
name: Release acceptance
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: ".node-version"
cache: npm
- uses: ./.github/actions/npm-ci-retry
with:
cache: "false"
- name: Emit shadow acceptance report
run: |
node scripts/quality/validate-release-acceptance.mjs \
--plan tests/fixtures/release-acceptance/plan-lint.json \
--manifests tests/fixtures/release-acceptance/shadow-manifests \
--out release-acceptance-report.json
continue-on-error: true
- uses: actions/upload-artifact@v4
if: always()
with:
name: release-acceptance-report
path: release-acceptance-report.json
if-no-files-found: ignore
retention-days: 30

View File

@@ -1,52 +0,0 @@
name: OpenSSF Scorecard
on:
branch_protection_rule:
schedule:
- cron: "27 7 * * 1"
push:
# Scorecard only accepts the DEFAULT branch — here the active release/vX.Y.Z,
# not `main`. The job below guards on it so a push to any other branch skips.
branches: ["main", "release/**"]
permissions: read-all
# One analysis per ref at a time. The `push` trigger fires on every push to the active
# release branch (~10/hour) and the job guard below only skips INSIDE the run, so each
# push still queued a hosted run (20 queued on 2026-10-17 against the account's
# concurrent-job limit). Scorecard scores repository posture, not the commit: the
# newest push supersedes the older ones and the weekly schedule keeps its own ref.
concurrency:
group: scorecard-${{ github.ref }}
cancel-in-progress: true
jobs:
analysis:
if: ${{ (github.event_name != 'push' || github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
name: Scorecard analysis
runs-on: ubuntu-latest
permissions:
# security-events: write removed — Scorecard findings are advisory and no longer
# uploaded to the code-scanning Security tab (they are supply-chain/posture scores,
# not code vulnerabilities, and drowned out real CodeQL alerts). The run still
# produces the OpenSSF badge (publish_results) and a downloadable SARIF artifact.
id-token: write
contents: read
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Run analysis
uses: ossf/scorecard-action@v2.5.0
with:
results_file: results.sarif
results_format: sarif
publish_results: true
- name: Upload artifact
uses: actions/upload-artifact@v7
with:
name: SARIF file
path: results.sarif
retention-days: 5

View File

@@ -1,35 +0,0 @@
name: semgrep
on:
pull_request:
branches: ["main", "release/**"]
push:
branches: ["main"]
permissions:
contents: read
# Cancel superseded PR runs (same rule as quality.yml). No paths filter on purpose:
# p/secrets must keep scanning docs-only diffs too — credentials leak in .md files.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
semgrep:
runs-on: ubuntu-latest
container:
image: semgrep/semgrep
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run semgrep (advisory)
continue-on-error: true
run: |
semgrep scan --config p/owasp-top-ten --config p/secrets \
--sarif --output semgrep.sarif --metrics off || true
python -c "import json; d=json.load(open('semgrep.sarif')); print('semgrepFindings=%d' % len(d['runs'][0]['results']))" || echo "semgrepFindings=SKIP"
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: always()
with:
name: semgrep-sarif
path: semgrep.sarif
retention-days: 14

View File

@@ -1,61 +0,0 @@
name: Quarantined Tests (debt, not admission)
on:
schedule:
- cron: "17 5 * * *"
workflow_dispatch:
permissions:
contents: read
issues: read
concurrency:
group: quarantine-${{ github.ref }}
cancel-in-progress: false
jobs:
quarantine:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: .node-version
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Read current tracking issue states
id: inventory
env:
GH_TOKEN: ${{ github.token }}
run: |
node --input-type=module <<'JS'
import { readFileSync, mkdirSync, writeFileSync, appendFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
const inventory = JSON.parse(readFileSync('config/quality/vitest-exclusions.json', 'utf8'));
const states = {};
for (const issue of new Set(inventory.excluded.map(entry => entry.issue))) {
if (!/^#[1-9]\d*$/.test(issue)) throw new Error('Invalid issue reference');
const value = JSON.parse(execFileSync('gh', ['api', `repos/${process.env.GITHUB_REPOSITORY}/issues/${issue.slice(1)}`], { encoding: 'utf8' }));
states[issue] = value.state;
}
mkdirSync('.artifacts/quarantine', { recursive: true });
writeFileSync('.artifacts/quarantine/issue-states.json', JSON.stringify(states, null, 2));
appendFileSync(process.env.GITHUB_OUTPUT, `count=${inventory.excluded.length}\n`);
JS
- name: Validate inventory lifetime and tracker
run: node scripts/check/check-vitest-exclusions.mjs --issue-states .artifacts/quarantine/issue-states.json
- name: Execute quarantined tests
if: ${{ !cancelled() && steps.inventory.outputs.count != '' && steps.inventory.outputs.count != '0' }}
run: npx --no-install vitest run --config vitest.quarantine.config.ts --reporter=default --reporter=json --outputFile.json=.artifacts/quarantine/results.json
- name: Preserve measured failures and issue evidence
if: always()
uses: actions/upload-artifact@v7
with:
name: quarantine-${{ github.sha }}-${{ github.run_attempt }}
path: .artifacts/quarantine/
if-no-files-found: error
retention-days: 14

View File

@@ -1,200 +0,0 @@
name: UI Kit upstream watch
# The CI UI Kit is a vendored snapshot (packages/ui-kit, pinned in UPSTREAM.md), so nothing tells
# the team when Keak ships a new release: 0.0.66 sat in the tree while 0.0.76 was out. Once a day
# this compares the pinned version with the newest `v*` tag upstream. While we are behind it keeps
# ONE sync PR open against the highest release/vX.Y.Z branch (scripts/ci/ui-kit-sync-pr.sh). It
# never merges: every kit release still needs a visual check on the local VPS. When no PR can be
# opened (frozen release, no PR token, a maintainer closed it) ONE tracking issue says what to do.
#
# Secrets:
# UI_KIT_READ_TOKEN read-only token for the private keak-ai/cheaper-inference-ui-kit. When the
# check can't read upstream it reports "unknown": the run stays green but
# warns, and keeps ONE issue open until a later run can read upstream again.
# UI_KIT_SYNC_PR_TOKEN fine-grained token on this repository (Contents and Pull requests: write).
# This repository doesn't let GITHUB_TOKEN create PRs, and a PR it opened
# wouldn't trigger CI. Without this token only the branch is pushed.
on:
schedule:
- cron: "17 9 * * *" # daily 09:17 UTC
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ui-kit-upstream-watch
cancel-in-progress: true
jobs:
watch:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Compare the pinned kit with the latest upstream release
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: write # push chore/ui-kit-sync-latest
issues: write # the tracking issues
pull-requests: write # read the sync PR's state; opening it uses UI_KIT_SYNC_PR_TOKEN
steps:
- name: Resolve the target release branch
id: base
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
BASE=$(gh api "repos/$GITHUB_REPOSITORY/branches" --paginate --jq '.[].name' \
| grep -E '^release/v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1)
[ -n "$BASE" ] || { echo "no release/vX.Y.Z branch" >&2; exit 1; }
FREEZES=$(gh issue list --repo "$GITHUB_REPOSITORY" --label release-freeze --state open \
--json title --jq '.[].title')
# Titles read "release-freeze: v3.8.52 in progress"; v3.8.5 must not match v3.8.52.
VERSION="${BASE#release/}"
if printf '%s\n' "$FREEZES" | grep -qE "release-freeze: ${VERSION//./\\.}([^0-9.]|$)"; then
FROZEN=true
else
FROZEN=false
fi
RED=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "Release branch not green: $BASE in:title" --json number --jq '.[0].number // empty')
{
echo "branch=$BASE"
echo "frozen=$FROZEN"
echo "red=$RED"
} >> "$GITHUB_OUTPUT"
echo "target $BASE (frozen=$FROZEN, base-red=${RED:-none})"
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ steps.base.outputs.branch }}
persist-credentials: false
- name: Check upstream
id: check
env:
UI_KIT_READ_TOKEN: ${{ secrets.UI_KIT_READ_TOKEN }}
run: |
set -euo pipefail
node scripts/check/check-ui-kit-upstream.mjs --json > ui-kit-upstream.json
cat ui-kit-upstream.json
echo "state=$(node -p "require('./ui-kit-upstream.json').state")" >> "$GITHUB_OUTPUT"
- name: Warn about and track an unreadable upstream
env:
GH_TOKEN: ${{ github.token }}
STATE: ${{ steps.check.outputs.state }}
run: |
set -euo pipefail
if [ "$STATE" = "unknown" ]; then
DETAIL=$(node -p "require('./ui-kit-upstream.json').detail")
echo "::warning title=UI Kit upstream watch::$DETAIL"
echo "**UI Kit upstream watch:** state is \`unknown\`, so new kit releases aren't being tracked. $DETAIL" >> "$GITHUB_STEP_SUMMARY"
fi
# Triage may prefix an issue title ("fix: ..."), so match the end of the title. `in:title`
# is a looser phrase search, so it can't decide this on its own. No `|| echo ""` here: a
# failed lookup has to fail the step, not look like "no issue open" and open a duplicate.
NO_TOKEN_TITLE="UI Kit upstream watch can't run: UI_KIT_READ_TOKEN isn't set"
UNREADABLE_TITLE="UI Kit upstream watch can't read upstream"
OPEN=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title \"UI Kit upstream watch can't\"" --limit 100 --json number,title \
| jq -r --arg a "$NO_TOKEN_TITLE" --arg b "$UNREADABLE_TITLE" \
'.[] | select((.title | endswith($a)) or (.title | endswith($b))) | .number')
if [ "$STATE" != "unknown" ]; then
for NUMBER in $OPEN; do
gh issue close "$NUMBER" --repo "$GITHUB_REPOSITORY" --reason completed \
--comment "The watch can read upstream again (state: $STATE)."
done
elif [ -n "$OPEN" ]; then
echo "Already tracked in: $(echo "$OPEN" | sed 's/^/#/' | paste -sd ' ' -)" >> "$GITHUB_STEP_SUMMARY"
else
REASON=$(node -p "require('./ui-kit-upstream.json').reason")
REPO=$(node -p "require('./ui-kit-upstream.json').repo")
# Only a token that really is unset gets the title that says so.
TITLE="$UNREADABLE_TITLE"
if [ "$REASON" = "no-token" ]; then TITLE="$NO_TOKEN_TITLE"; fi
{
echo "$DETAIL"
echo
echo "Until this is fixed, nothing opens when \`$REPO\` gets a new release. \`npm run check:ui-kit-upstream\` still works locally with your git credentials."
echo
echo "The watch needs a read-only token for that repo in the \`UI_KIT_READ_TOKEN\` secret. This issue closes itself on the next run that can read upstream."
echo
echo "Run: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
} > access-body.md
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --body-file access-body.md
fi
- name: Open or update the sync PR
id: sync
if: ${{ steps.check.outputs.state == 'behind' && steps.base.outputs.frozen == 'false' }}
env:
GH_TOKEN: ${{ secrets.UI_KIT_SYNC_PR_TOKEN || github.token }}
HAS_PR_TOKEN: ${{ secrets.UI_KIT_SYNC_PR_TOKEN != '' }}
KIT_TOKEN: ${{ secrets.UI_KIT_READ_TOKEN }}
BASE: ${{ steps.base.outputs.branch }}
BASE_RED_ISSUE: ${{ steps.base.outputs.red }}
run: |
set -euo pipefail
gh auth setup-git
REPO="$GITHUB_REPOSITORY"
LATEST_VERSION=$(node -p "require('./ui-kit-upstream.json').latest.version")
LATEST_COMMIT=$(node -p "require('./ui-kit-upstream.json').latest.commit")
PINNED_COMMIT=$(node -p "require('./ui-kit-upstream.json').pinned.commit")
export REPO LATEST_VERSION LATEST_COMMIT PINNED_COMMIT
scripts/ci/ui-kit-sync-pr.sh
- name: Open, update or close the tracking issue
# Not on an empty state: a failed check says nothing about the pin, so it can't close the issue.
if: ${{ !cancelled() && (steps.check.outputs.state == 'behind' || steps.check.outputs.state == 'up-to-date') }}
env:
GH_TOKEN: ${{ github.token }}
STATE: ${{ steps.check.outputs.state }}
FROZEN: ${{ steps.base.outputs.frozen }}
BASE: ${{ steps.base.outputs.branch }}
DECISION: ${{ steps.sync.outputs.decision }}
BRANCH: ${{ steps.sync.outputs.branch }}
PR_URL: ${{ steps.sync.outputs.pr_url }}
run: |
set -euo pipefail
TITLE="UI kit: a newer upstream release is available"
# Triage may prefix an issue title, so match the end of it, as the step above does.
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title \"$TITLE\"" --limit 100 --json number,title \
| jq -r --arg title "$TITLE" '[.[] | select(.title | endswith($title))][0].number // empty')
if [ "$STATE" = "behind" ] && [ -z "$PR_URL" ]; then
PINNED=$(node -p "require('./ui-kit-upstream.json').pinned.version")
LATEST=$(node -p "require('./ui-kit-upstream.json').latest.version")
{
echo "The vendored kit is pinned at \`$PINNED\`; upstream released \`v$LATEST\`."
echo
if [ "$FROZEN" = "true" ]; then
echo "No sync PR was opened because \`$BASE\` is frozen."
elif [ "$DECISION" = "branch-only" ]; then
echo "\`$BRANCH\` is pushed with the sync, but no PR was opened: the \`UI_KIT_SYNC_PR_TOKEN\` secret isn't set. Open it from that branch against \`$BASE\`."
elif [ "$DECISION" = "hand-edited" ]; then
echo "The open sync PR on \`$BRANCH\` has commits pushed by hand, so the watch won't overwrite them with this release. Update that PR, or close it to let the watch open a new one."
elif [ "$DECISION" = "declined" ]; then
echo "The sync PR for this version was closed without merging, so it stays closed until a newer release."
else
echo "The sync step didn't finish; see $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID."
fi
echo
echo "To sync by hand from the main checkout:"
echo
echo '```'
echo 'git -C _references/cheaper-inference-ui-kit fetch --tags'
echo 'scripts/dev/sync-ui-kit.sh latest'
echo '```'
echo
echo "Then run the kit guards (\`tests/unit/*kit*\`, \`design-kit-bridge\`, \`ui-kit-snapshot-gate\`) and the dashboard typecheck."
} > body.md
# Edited in place: this runs daily, so a comment per run would only be noise.
if [ -n "$EXISTING" ]; then
gh issue edit "$EXISTING" --repo "$GITHUB_REPOSITORY" --body-file body.md
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --body-file body.md
fi
elif [ -n "$EXISTING" ]; then
if [ -n "$PR_URL" ]; then
COMMENT="The sync is now tracked in $PR_URL."
else
COMMENT="The pinned kit matches the latest upstream release."
fi
gh issue close "$EXISTING" --repo "$GITHUB_REPOSITORY" --reason completed --comment "$COMMENT"
fi

View File

@@ -1,53 +0,0 @@
name: Validate stable/v3 PR (dormant)
# DORMANT until the 3.9.0 LTS cut creates `stable/v3` (docs/ops/RELEASE_STRATEGY.md).
# The `branches:` filter means this never triggers while that branch does not exist.
#
# `stable/v3` only takes LTS-safe changes: a Conventional title starting with
# fix / docs / chore(i18n) / feat(providers), or anything the maintainer marks
# with the `lts` label. Everything else belongs on `develop` (v4).
#
# `pull_request` (not `pull_request_target`): nothing is checked out and no code
# from the PR runs — the title and labels arrive through env, never inlined into
# the script (zizmor template-injection).
on:
pull_request:
branches: [stable/v3]
types: [opened, edited, synchronize, reopened, labeled, unlabeled]
permissions:
contents: read
concurrency:
group: validate-stable-pr-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
validate:
name: LTS scope (stable/v3)
if: github.base_ref == 'stable/v3'
runs-on: ubuntu-latest
permissions: {}
steps:
- name: Check title scope or lts label
env:
PR_TITLE: ${{ github.event.pull_request.title }}
PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }}
run: |
set -euo pipefail
STRATEGY="docs/ops/RELEASE_STRATEGY.md"
case ",${PR_LABELS}," in
*,lts,*)
echo "✅ label 'lts' present — accepted for stable/v3."
exit 0
;;
esac
if printf '%s' "$PR_TITLE" | grep -qE '^((fix|docs)(\([A-Za-z0-9._/-]+\))?|chore\(i18n\)|feat\(providers\))!?: .+'; then
echo "✅ title scope accepted for stable/v3."
exit 0
fi
{
echo "::error title=Not an LTS change::stable/v3 only accepts fix:, docs:, chore(i18n): or feat(providers): titles, or a PR labelled 'lts'. Retarget this PR to develop, or ask a maintainer for the 'lts' label. See ${STRATEGY}."
}
exit 1

View File

@@ -1,69 +0,0 @@
name: Wiki Sync
# Keeps the GitHub wiki in sync with docs/ on every release that lands on main.
# The wiki has no native generator and historically drifts (it sat at "212+ providers /
# 14 strategies / 37 MCP tools" while code was at 226 / 15 / 87, and new docs like
# SUPPLY_CHAIN never appeared). This runs scripts/docs/sync-wiki.mjs, which:
# - ADDS any docs/ page missing from the wiki (curated; internal reports excluded),
# - syncs the four cover-page counts on Home.md.
# It does NOT overwrite existing wiki pages by default: several docs sources still carry
# stale counts (e.g. ARCHITECTURE.md says "177 providers" while the wiki cover is 226),
# so blind overwrite would regress the wiki. Full content parity (--update-existing) is
# gated on regenerating those sources first.
on:
push:
branches: [main]
paths:
- "docs/**"
- "README.md"
- "AGENTS.md"
- "src/shared/constants/routingStrategies.ts"
- "config/i18n.json"
- "open-sse/mcp-server/server.ts"
- "scripts/docs/sync-wiki.mjs"
workflow_dispatch:
permissions:
contents: write
concurrency:
group: wiki-sync
cancel-in-progress: false
jobs:
sync-wiki:
name: Sync wiki with docs
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v7
- name: Setup Node
uses: actions/setup-node@v7
with:
node-version: "24"
- name: Clone wiki
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
run: |
git clone "https://x-access-token:${GH_TOKEN}@github.com/${REPO}.wiki.git" wiki
- name: Sync wiki (add missing pages + cover counts)
run: node scripts/docs/sync-wiki.mjs --wiki-dir wiki
- name: Commit & push if changed
run: |
cd wiki
if [ -n "$(git status --porcelain)" ]; then
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add -A
git commit -m "docs(wiki): auto-sync pages + cover counts with docs"
git push
echo "Wiki updated."
else
echo "Wiki already in sync — nothing to push."
fi

310
.gitignore vendored
View File

@@ -1,67 +1,30 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# project-specific directories
/output/
.slim/deepwork/
.omnivscodeagent/
omnirouteCloud/
omnirouteSite/
_cache/
_ideia/
_mono_repo/
_references/
_tasks/
.agents/**
.claude/**
.gemini/**
.code-forge/**
.config/**
.data/**
.logs/**
.tests/**
.coverage/**
/coverage/
.dist/**
.next/**
.build/**
.out/**
# Stryker mutation testing — ephemeral sandbox + generated reports (never commit)
.stryker-tmp/
reports/mutation/
stryker-output-*.json
# Memory Bank and Cursor rules (local-only AI agent context)
memory-bank/
.cursor/rules/core.mdc
.cursor/rules/memory-bank.mdc
# Claude Code local state — runtime files only; shared commands at .claude/commands/ are tracked
.claude/scheduled_tasks.lock
.claude/scheduled_tasks/
.claude/sessions/
.claude/state.json
.claude/settings.local.json
# Root-level underscore-prefixed directories (private/draft — never commit)
/_*/
/_*
# Draft features documentation (internal only)
docs/new-features/
# dependencies
node_modules/
# Also ignore a root node_modules SYMLINK (worktree setups symlink it from the main
# checkout). The trailing-slash pattern above only matches a directory, so without this
# a symlink named node_modules could be staged by `git add -A` and committed.
/node_modules
*.map
.DS_Store
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# Serena AI assistant config (local-only tool, not project code)
.serena/
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
/app
cloud/*
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
@@ -71,15 +34,7 @@ yarn-error.log*
# env files (can opt-in for committing if needed)
.env*
# Local gitleaks artifacts (do not commit)
gitleaks-local.json
!.env.example
!.env.selfhost.example
!.env.homolog.example
!.env.devin-bridge.example
# Provider API keys (never commit)
*.api-key
.nvidia-api-key
# vercel
.vercel
@@ -89,16 +44,36 @@ gitleaks-local.json
next-env.d.ts
# data and logs
/data/
.data/
data/
logs/*
test_output.log
# analysis directories (generated, not tracked)
.analysis/
antigravity-manager-analysis/
.sisyphus/
.plans/
# docs (allow specific tracked files)
docs/*
!docs/ARCHITECTURE.md
!docs/CODEBASE_DOCUMENTATION.md
!docs/CONTRIBUTING.md
!docs/USER_GUIDE.md
!docs/API_REFERENCE.md
!docs/TROUBLESHOOTING.md
!docs/EXECUTION_CONTEXT_PROVIDER_SYNC.md
!docs/TASK_NEBIUS_BACKEND_ENABLEMENT.md
!docs/frontend-backend-provider-gap-report.md
!docs/openapi.yaml
!docs/PLANO-IMPLANTACAO.md
!docs/TASKS.md
!docs/FASE-*.md
!docs/adr/
!docs/cli-tools/
!docs/planning/
!docs/improvement-plans/
!docs/api/
!docs/VM_DEPLOYMENT_GUIDE.md
!docs/FEATURES.md
!docs/screenshots/
# open-sse tests
open-sse/test/*
@@ -107,200 +82,17 @@ open-sse/test/*
.github/instructions/codacy.instructions.md
# Playwright
.playwright-mcp/
test-results/
playwright-report/
blob-report/
/cloud/
.tmp/
cloud/
omnirouteCloud/
omnirouteSite/
# Security Analysis (standalone project with own git)
security-analysis/
# Deploy workflow (contains sensitive VPS credentials)
.agent/workflows/deploy.md
clipr/
app.log
*.tgz
.gh-discussions.json
deploy.sh
docker-compose.minimal.yml
# Docker Compose override (local-only, never commit)
docker-compose.override.yml
# Backup directories
app.__qa_backup/
.app-build-backup-*/
backup/
# Build intermediates (.build/) and shippable standalone (dist/).
# These are fully reproducible from source; never committed.
# Layer 1: Next.js now writes to .build/next (was .next); assembled bundle → dist/
# (Previously /app/ was the standalone output; renamed to /dist/ in Layer 1.)
/.build/
/dist/
/.next/
# Electron
electron/dist-electron/
electron/node_modules/
icon.iconset/
# VS Code Extension (independent Git repo)
vscode-extension/
# SQLite residual files
*.sqlite-shm
*.sqlite-wal
*.sqlite-journal
# IDEA
.idea/
# Local OpenCode agent config
.config/
# Empty/dangling files
typescript
/MAX
# Gemini Antigravity agent data
.gemini/
# Superpowers plans/specs (internal tooling, not project code)
docs/superpowers/
# Superpowers visual-companion brainstorm mockups (ephemeral)
.superpowers/
# TIA test-impact map — generated at runtime in CI (build-test-impact-map.mjs), never committed (~21MB)
config/quality/test-impact-map.json
# GitNexus local index
.gitnexus
.worktrees
# Consistent with .dockerignore / .npmignore
.omc/
audit-report.json
bun.lock
# Private environment variables for .http-client
http-client.private.env.json
# Note: _ideia/ (feature-triage drafts) is fully covered by the /_*/ rule above
# and kept as a separate local-only git repo. Never committed to OmniRoute.
# i18n audit artifact (generated by scripts/i18n/audit-dashboard-pages.mjs)
scripts/i18n/_audit.json
scripts/i18n/_pending-keys.json
# Private workflow / skill / command implementations
# These contain proprietary multi-phase logic and should not be committed
.agents/workflows/implement-features-ag.md
.agents/workflows/port-upstream-features-ag.md
.agents/workflows/port-upstream-issues-ag.md
.agents/skills/implement-features/
.claude/commands/implement-features-cc.md
.claude/commands/port-upstream-features-cc.md
.claude/commands/port-upstream-issues-cc.md
.claude/worktrees/
.codegraph/
# Test executable shims belong in the OS temporary directory, not the repository root
/.fakebin-*/
# Fumadocs generated source
.source/
# AI agent local settings and configs
.agents/
.antigravitycli/
/.claude/
# PR Reviews and local feedback files
pr_reviews*.json
/review/
#hidden local data directories (never commit)
.local-data/
.data-dev/
/.junie/
# internal setup prompts with personal credentials — never commit
CODEX-SETUP-PROMPT.md
# Quality ratchet — métricas efêmeras (baseline commitado em config/quality/; métricas não)
config/quality/quality-metrics.json
# Electron desktop build output unpacked into the repo root.
# `electron-builder` (squirrel-windows target) unpacks the packaged app — the
# entire Chromium runtime, ~24k files — directly into the repository root.
# Every rule below is ROOT-ANCHORED (leading `/`) on purpose: a bare `locales/`
# or `resources/` would also swallow tracked sources such as the CLI
# translations in `bin/cli/locales/*.json`.
/OmniRoute.exe
/Uninstall OmniRoute.exe
/uninstallerIcon.ico
/locales/
/resources/
/*.pak
/*.dll
/icudtl.dat
/snapshot_blob.bin
/v8_context_snapshot.bin
/vk_swiftshader_icd.json
/LICENSE.electron.txt
/LICENSES.chromium.html
# Runtime logs (diretório local, nunca versionado)
/logs/
-home-diegosouzapw-dev-automações-bots-yt-downloader-20260504 .txt
-home-diegosouzapw-dev-automações-bots-yt-downloader-20260410 .txt
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.omniroute.md
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.md
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.omniroute-mim.md
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.omniroute-mid.md
omniroute.md
# mise configuration
mise.toml
_artifacts/ # release-green artifacts
.claude-flow/
# ESLint file cache (npm run lint --cache / complexity ratchets)
.eslintcache
.eslintcache-complexity
/.eslintcache-*
# CI/local quality artifacts (eslint-results.json, quality-ratchet.md, etc.)
.artifacts/
/perf-audit*.md
/quality-ratchet/
# Homologation E2E suite (npm run homolog) — real-environment credentials + report output
.env.homolog
tests/homolog/.auth/
tests/homolog/ui/.auth/
homolog-report/
docker-compose.yml.bak
# _tasks e um repo git SEPARADO (ver AGENTS.md). A linha _tasks/ (com barra) NAO
# ignora um SYMLINK chamado _tasks; /_tasks (ancorado) cobre arquivo/symlink/dir na raiz
# e impede que um git add -A recapture o symlink (incidente 2026-08-08).
/_tasks
# CLI local cache/state
.playwright-cli
# Ad-hoc test sandboxes (never tracked — may contain local DBs)
/.sandbox/
.aider*
# check:install-upgrade work trees (~12 GB, disposable)
/.install-upgrade/
# run-translation.mjs writes the state atomically via a per-process temp file
/.i18n-state.json.*.tmp
# Scoped tsc incremental state written by the typecheck gates (typecheck:core / open-sse / api)
.tsbuildinfo-*

View File

@@ -1,107 +0,0 @@
# .gitleaks.toml — Configuração do gitleaks para OmniRoute
# Task 7.18 — PLANO-QUALITY-GATES-FASE7.md
#
# Estende as regras padrão do gitleaks com allowlists específicas do projeto.
#
# INSTRUÇÕES para allowlists:
# Findings legítimos (fixtures de teste, creds OAuth públicas já cobertas pelo
# check-public-creds.mjs, valores de exemplo em docs) devem ser registrados abaixo
# em [[allowlist]] com um comentário explicativo obrigatório.
#
# NÃO adicione uma entrada de allowlist sem justificativa. Cada entrada é revisada
# a cada release (stale-enforcement). Regra: se o finding é um valor real que o
# sistema usa em produção, é um verdadeiro positivo — não allowliste, corrija.
#
# Referência: docs/security/PUBLIC_CREDS.md (credenciais OAuth públicas conhecidas)
# CLAUDE.md Hard Rule #11 (resolvePublicCred obrigatório)
# Herdar TODAS as regras padrão do gitleaks. ATENÇÃO: um config customizado
# SEM [extend].useDefault = true (e sem [[rules]] próprias) resulta em ZERO
# regras — o gitleaks SUBSTITUI o ruleset padrão pelo arquivo, não o estende
# automaticamente. Sem esta seção, `gitleaks --config .gitleaks.toml` nunca
# detecta nada (todo finding vira 0), tornando o gate inerte. Com useDefault,
# a allowlist abaixo é aplicada POR CIMA das ~170 regras padrão.
[extend]
useDefault = true
# Para desabilitar uma regra específica, usar:
# [[rules]]
# id = "rule-id"
# [rules.allowlist]
# description = "..."
# ---------------------------------------------------------------------------
# Allowlist global do projeto
# Entradas aqui são ignoradas em TODAS as varreduras.
# ---------------------------------------------------------------------------
[allowlist]
description = "OmniRoute project-level allowlist — fixtures, test vectors, public OAuth creds"
# Paths a ignorar completamente (node_modules, builds, etc.)
paths = [
'''node_modules''',
'''\.next''',
'''dist''',
'''\.git''',
'''coverage''',
'''\.nyc_output''',
]
# Commits específicos a ignorar (ex: commit que introduziu fixtures de teste)
# commits = []
# Regexes de stopwords — linhas que contêm estes padrões são ignoradas.
# Usar apenas para falsos positivos comprovados com justificativa abaixo.
# stopwords = []
# Regexes de targets (paths de arquivos) que podem ser allowlistados por regra.
# Ver [[allowlist]] por-regra abaixo para granularidade.
# ---------------------------------------------------------------------------
# Allowlist por-regra (adicionar conforme necessário durante o stale review)
# ---------------------------------------------------------------------------
#
# Exemplo (REMOVER / SUBSTITUIR por entradas reais quando necessário):
#
# [[rules]]
# # Allowlistar fixtures de teste que contêm tokens OAuth de exemplo/inválidos
# # Adicionado: 2026-06-13 | Revisar em: v3.9.0 | Justificativa: valores não-reais de teste
# id = "github-fine-grained-pat"
# [rules.allowlist]
# description = "Test fixture PATs — valores sintéticos, não funcionais"
# paths = [
# '''tests/fixtures/''',
# '''tests/unit/''',
# ]
#
[[rules]]
# Falsos-positivos comprovados do generic-api-key — zerados em 2026-07-13 (WS6/D3,
# plano v3.8.49). Revisar em v3.9.0. Nenhum é credencial: dois são NOMES DE CAMPO
# de métricas de latência; o terceiro é o valor PÚBLICO de um beta header da API
# da Anthropic (documentado publicamente, não é segredo).
id = "generic-api-key"
[rules.allowlist]
description = "Field names + public Anthropic beta-header value (não são segredos)"
regexes = [
'''latencyP\d{2}Ms''',
'''interleaved-thinking-2025-05-14''',
# v3.8.49 pre-flight (2026-07-28). Nenhum dos dois e credencial:
# - chave de localStorage do banner de patrocinio (#8723; #10200 bumpou v1->v2,
# generalizado para -v\d+ no round 3 de base-reds #9985), so um identificador de UI;
# - x-api-key PUBLICO do Firefly web (documentado em open-sse/utils/publicCreds.ts:207);
# as duas ocorrencias sinalizadas estao em COMENTARIOS JSDoc, o runtime le de resolvePublicCred().
'''omniroute-kimi-sponsor-banner-dismissed-v\d+''',
# CheaperInference sponsor banner localStorage key (upstream #11196 /
# eb5797370). Same UI-identifier pattern as the kimi banner above, not a
# credential; the generic-api-key rule flags the long hyphenated string.
'''omniroute-cheaperinference-sponsor-banner-dismissed-v\d+''',
'''SunbreakWebUI1''',
# Uzbek dashboard catalog (#13727, src/i18n/messages/uz.json `outputTokenDesc`):
# "Yakunlash/javob tokenlari" = "completion/response tokens". The rule reads the
# `...TokenDesc` key as a token assignment and the translated words as its value.
'''Yakunlash/javob''',
# Feature-flag id from #13439 (src/shared/constants/featureFlagDefinitions.ts):
# `key: "PROTECTED_PRIORITY_INFRA_502_ENABLED"` is a flag name, not a credential.
'''PROTECTED_PRIORITY_INFRA_502_ENABLED''',
]

View File

@@ -1,4 +0,0 @@
#!/usr/bin/env sh
# Hard Rule #16 — no AI/bot Co-Authored-By trailers or AI-generation footers in commit metadata.
# Human co-authors stay. Incident record: #14436.
node scripts/check/check-ai-attribution.mjs --message-file "$1"

21
.husky/pre-commit Executable file → Normal file
View File

@@ -1,20 +1 @@
#!/usr/bin/env sh
set -eu
if ! command -v npx >/dev/null 2>&1; then
echo "npx not found in PATH — install the project's Node/npm toolchain before committing." >&2
exit 1
fi
# Cheap, deterministic local gates (re-enabled). Slower checks (i18n drift,
# openapi coverage/security-tiers, env-doc sync) run in CI to keep commits fast.
sh scripts/check/check-git-identity.sh
# The stash is shared by every worktree. Never let a local hook stash another
# session's changes, and never download a missing tool during a commit.
npx --no-install lint-staged --no-stash
node scripts/quality/gate-manifest.mjs
node scripts/check/check-docs-sync.mjs
npm run check:any-budget:t11
node scripts/check/check-tracked-artifacts.mjs
# vendored kit must stay byte-identical to the pinned upstream commit; skips with a warning where the private clone is absent
npm run --silent check:ui-kit-snapshot
npx lint-staged

View File

@@ -1,15 +0,0 @@
#!/usr/bin/env sh
# .husky/pre-push — intentionally light.
# any-budget + tracked-artifacts already run on pre-commit; re-running them on
# every push only doubles local wall time for the same existence reason (CI still
# enforces both). Keep this hook as a PATH/npm sanity check + reminder.
# Intentionally excludes test:unit / typecheck (slow; covered by CI).
if ! command -v npm >/dev/null 2>&1; then
echo "⚠️ npm not found in PATH — skipping pre-push hooks"
echo " Run 'npm run check:any-budget:t11 && npm run check:tracked-artifacts' manually before pushing."
exit 0
fi
# No-op success: real local gates live in pre-commit; CI owns the rest.
exit 0

File diff suppressed because it is too large Load Diff

View File

@@ -1,40 +0,0 @@
# .mailmap — canonical author identities for git log/shortlog/blame.
#
# Why this file exists: between 2026-08-13 and 2026-08-26 this checkout carried a
# `git config --local` whose user.name was one contributor's ("Xiangzhe" / @xz-dev)
# and whose user.email was ANOTHER contributor's (@backryun). Every commit produced
# on this machine in that window was therefore signed with @backryun's address —
# 237 commits, all in the -0300 timezone, while @backryun's own work commits from
# +0900 and continued normally throughout. The local override was removed on
# 2026-08-26; this file repairs the RECORD without rewriting published history
# (those commits live on release/v3.8.50 and release/v3.8.51, which other sessions
# and open PRs build on — a rewrite would force-push both and orphan the v3.8.50 tag).
#
# Format: Canonical Name <canonical@email> Commit Name <commit@email>
# --- Maintainer: several addresses used over the project's life ---
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diegosouza.pw@gmail.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diegosouza.pw@outlook.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diegosouzapw@users.noreply.github.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> Diego Rodrigues de Sa e Souza <8016841+diegosouzapw@users.noreply.github.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> Diego Souza <8016841+diegosouzapw@users.noreply.github.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diego.souza.pw@gmail.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <souzamiriamrodrigues790@gmail.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diego.souza@cdwasolutions.com.br>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diegosouzapw@devbox.local>
# --- The misattribution window: name Xiangzhe + @backryun's email, from -0300.
# These are maintainer/session commits, NOT @backryun's contributions.
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> Xiangzhe <bakryun0718@proton.me>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> Xiangzhe <diegosouza.pw@gmail.com>
# --- Xiangzhe (@xz-dev) — a distinct contributor; keep their own work intact ---
Xiangzhe <32761048+xz-dev@users.noreply.github.com> <xz-dev@users.noreply.github.com>
Xiangzhe <32761048+xz-dev@users.noreply.github.com> <xiangzhedev@gmail.com>
# --- @backryun's own alternate addresses (their real work, kept intact) ---
backryun <24198422+backryun@users.noreply.github.com> <bakryun0718@proton.me>
backryun <24198422+backryun@users.noreply.github.com> <backryun@daonlab.local>
backryun <24198422+backryun@users.noreply.github.com> <busan011@ormbiz.co.kr>
backryun <24198422+backryun@users.noreply.github.com> <backryun@users.noreply.github.com>

View File

@@ -1,14 +0,0 @@
{
"_comment": "Advisory markdown lint for docs/ + root *.md. Rules that conflict with the existing doc style (heavy inline HTML, long lines, centered headings) are disabled so the gate stays signal-not-noise. Run: npm run lint:md",
"default": true,
"MD013": false,
"MD033": false,
"MD041": false,
"MD024": { "siblings_only": true },
"MD026": false,
"MD036": false,
"MD040": false,
"MD029": false,
"MD007": { "indent": 2 },
"MD046": false
}

View File

@@ -1,122 +0,0 @@
# Mergify merge queue — WS3.4/D5 of the v3.8.49 quality/velocity master plan.
#
# WHY: ~85-100 active PR authors/month and 300+ PRs/week peaks, all merged by ONE
# identity. The manual merge-train validated batches by hand; this queue automates
# it with batching + automatic batch bisection (a red batch of N costs ~log2(N)
# revalidations instead of N). Mergify Open Source plan: free, unlimited, public repo.
#
# GOVERNANCE (non-negotiable, mirrors CLAUDE.md Hard Rules #21/#22 + the owner's
# pre-merge ⭐ gate):
# • A PR enters the queue ONLY via the `queue` label — applied by the owner (or a
# session acting for the owner) AFTER the pre-merge ⭐ report/decision. The label
# IS the merge approval; Mergify only executes it.
# • During a release-freeze (open issue labeled `release-freeze`), do NOT label PRs
# targeting the frozen branch — the freeze is a human-honored coordination signal
# the queue cannot see. Retarget to the active release/vX+1 first (Hard Rule #21).
# • Never label a PR another session is actively working (Hard Rule #22b).
# • Fallback path if Mergify misbehaves or the OSS plan changes: the manual
# merge-train runbook (docs/ops/MERGE_TRAIN.md) — remove labels, proceed by hand.
# Auto-enqueue (current Mergify model, 2026): auto_merge_conditions in
# merge_protections_settings — the rules-based queue action / autoqueue path is
# deprecated (EOL 2026-07-16). The owner-applied `queue` label IS the approval.
merge_protections_settings:
auto_merge_conditions:
- label = queue
queue_rules:
- name: release
# Any current or future release branch — the reason GitHub's native queue was
# rejected (no wildcard support on personal-account repos).
queue_conditions:
- base~=^release/v\d+\.\d+\.\d+$
- label=queue
- -draft
- -conflict
# A reviewed integration candidate must never be squashed by this queue,
# including when its second approval label is missing or its ref changed.
- -label=integration-reviewed
- -head~=^fix/relay-integration-candidate-
# "Everything that ran is green, nothing still running, AND the always-on
# anchor check succeeded" — robust to the path-filtered fast-gates (docs-only
# PRs skip code jobs; matrix shard names vary) while never fail-open: a PR with
# zero checks cannot vacuously merge, because `Merge integrity` runs on EVERY
# non-draft PR (quality.yml) and must be an affirmative success. Review approval
# is intentionally NOT a condition here: the owner-applied `queue` label IS the
# approval in this repo's single-maintainer model (see governance header).
merge_conditions:
# "Zero failures" — EXCEPT the advisory "Build (advisory)" job (quality.yml):
# continue-on-error by design, and its GH-hosted Turbopack build hangs
# recurrently mid-"Creating an optimized production build" (100% failure rate
# across every sampled PR since the job was added 2026-07-27, always killed by
# a runner timeout/shutdown signal, never a real compile error). Any OTHER
# failure still blocks (anti-fail-open kept). The prior dast-smoke exception
# (#7225) was dropped here: dast-smoke's hang (#7226) has been dormant for
# weeks (0 failures in the last 30 runs; 2 all-time, none since 2026-07-13) —
# carrying its tolerance forward would mask problems it no longer causes.
- or:
- "#check-failure=0"
- and:
- "#check-failure=1"
- check-failure=Build (advisory)
- "#check-pending=0"
- "#check-success>=1"
- check-success=Merge integrity (changelog + generated skills)
- check-success=Gate / CI
- check-success=Gate / Quality
# NO batching: 'Merge Queue Batch' requires a paid Mergify tier (live finding
# 2026-07-15 — the queue command fails with "Cannot use Merge Queue batch" on
# the free plan; #7220). Serial queue (1 PR at a time) still automates the train.
# Rail G11 (v3.8.54) asks for batch_size ~5: it stays BLOCKED on that tier —
# adding batch_size/batch_max_wait_time here would dequeue EVERY PR again. Do not
# re-add them unless the Mergify subscription is upgraded (owner decision).
#
# checks_timeout = 2 x p95 wall-clock of the quality.yml workflow (the fast-gates
# that run on PR -> release/**), measured over the last 100 successful runs
# (2026-09-28 .. 2026-10-08, createdAt -> updatedAt, so runner queueing counts):
# mean 34.5 min · p50 1.8 min · p90 101.0 min · p95 119.75 min · max 468.6 min
# (bimodal: path-filtered docs-only runs ~2 min vs full runs ~72 min median).
# 2 x 119.75 = 239.5 -> rounded up to 240 min. A PR whose checks are still
# pending past this is dequeued instead of blocking the serial queue forever.
# Re-measure with: gh run list --workflow quality.yml --status success
# --limit 100 --json createdAt,updatedAt (contract: tests/unit/mergify-queue-config.test.ts).
checks_timeout: 240 min
# Squash keeps the one-commit-per-PR history the CHANGELOG reconciliation expects.
merge_method: squash
# One already-composed PR, NOT Mergify's paid multi-PR batching feature.
# Activation requires this configuration to land on the default branch first.
# See docs/ops/RELAY_INTEGRATION_QUEUE.md for ownership, admission and readback.
- name: relay-integration
queue_conditions:
- base=release/v3.8.52
- head=fix/relay-integration-candidate-20261015
- author=diegosouzapw
- label=queue
- label=integration-reviewed
- -draft
- -conflict
merge_conditions:
- or:
- "#check-failure=0"
- and:
- "#check-failure=1"
- check-failure=Build (advisory)
- "#check-pending=0"
- "#check-success>=1"
- check-success=Merge integrity (changelog + generated skills)
- check-success=Gate / CI
- check-success=Gate / Quality
checks_timeout: 240 min
# Preserve the reviewed original PR heads; rebasing or squash would lose them.
update_method: merge
merge_method: merge
pull_request_rules:
- name: clean up the queue label after merge
conditions:
- merged
actions:
label:
remove:
- queue

View File

@@ -1 +0,0 @@
24

View File

@@ -3,25 +3,7 @@ data/
**/data/
**/db.json
# VS Code extension test runtime (large binary, not needed in npm package)
**/data/
**/db.json
# Source code (pre-built dist/ is published instead)
#
# NOTA (2026-08-05): as entradas `app/*` foram removidas — o diretorio `app/`
# foi renomeado para `dist/` na Layer 1 e nao existe mais. Elas sugeriam um
# layout que ja nao e o do projeto.
#
# NOTE (#3578 / #3821-review): package.json "files" is the source of truth for what
# ships. It now allowlists the backend source closure the MCP server needs at runtime
# (open-sse/, src/lib, src/server, ...) and OVERRIDES the broad src/ + open-sse/ excludes
# below — npm honors files[] over .npmignore for inclusion. These lines are kept only as
# intent/back-stop: if files[] is ever trimmed back to specific paths, they must NOT be
# allowed to re-hide the MCP closure (that would silently reintroduce the --mcp
# ERR_MODULE_NOT_FOUND #3578 fixed). The closure gate in
# tests/unit/mcp-published-files-closure-3578.test.ts asserts the real `npm pack` output
# in both directions (closure present + zero test files), catching such a regression.
# Source code (pre-built app/ is published instead)
src/
open-sse/
docs/
@@ -31,17 +13,6 @@ images/
logs/
scripts/
# Co-located tests must never ship even when their parent dir is allowlisted by files[].
# (Primary guard is the "!**/*.test.*" negations in package.json files[]; this is defense
# in depth for any nested dir the allowlist pulls in.)
**/__tests__/
**/*.test.ts
**/*.test.tsx
**/*.test.js
**/*.test.mjs
**/*.spec.ts
**/*.spec.tsx
# Config/dev files
*.md
!README.md
@@ -50,19 +21,14 @@ scripts/
.github/
.husky/
.vscode/
.agents/
.env*
eslint.config.mjs
prettier.config.mjs
postcss.config.mjs
next.config.mjs
tsconfig.json
tsconfig.typecheck-core.json
tsconfig.typecheck-noimplicit-core.json
playwright.config.ts
vitest.config.ts
next-env.d.ts
llm.txt
# Docker
docker-compose*.yml
@@ -70,54 +36,9 @@ Dockerfile
.dockerignore
# Misc
restart.sh
AGENTS.md
bun.lock
# Build artifacts (pre-built goes inside app/)
/.next/
/node_modules/
# Ignore large binary files and other build directories
*.tgz
*.AppImage
*.deb
*.rpm
electron/
# Subprojects
clipr/
omnirouteCloud/
omnirouteSite/
vscode-extension/
# Root-level underscore-prefixed directories (private/draft — never publish)
/_*/
# Consistent with .gitignore and .dockerignore
.claude/
.fakebin-*
.eslintcache*
_tasks/
.DS_Store
.idea/
.config/
.data/
.omnivscodeagent/
.omc/
*.sqlite-*
*.tsbuildinfo
security-analysis/
.analysis/
antigravity-manager-analysis/
.sisyphus/
.plans/
app.__qa_backup/
.app-build-backup-*/
.gitnexus
.worktrees
.next-playwright/
test-results/
playwright-report/
blob-report/
coverage/
@omniroute/
.next/
node_modules/

23
.npmrc
View File

@@ -1,23 +0,0 @@
# @lobehub/icons declares UI peers that are not needed by our deep icon imports.
# Keeping peer auto-install disabled prevents npm from pulling @lobehub/ui/mermaid
# back into the tree and reopening npm audit findings for unused packages.
legacy-peer-deps=true
# Network resilience: enlarge npm's fetch retry budget so a transient registry
# socket reset (ECONNRESET) mid-download retries instead of failing the job.
# npm defaults to only 2 retries with short timeouts; `npm ci` in
# electron-release.yml hit ECONNRESET during v3.8.41 publish. Applies to every
# CI workflow (electron / docker / unit) and local installs.
fetch-retries=5
fetch-retry-factor=4
fetch-retry-mintimeout=20000
fetch-retry-maxtimeout=120000
# onnxruntime-node bundles the CPU binaries (bin/napi-v6/...) inside the npm
# package, but its postinstall still tries to fetch the CUDA 12 binaries from
# NuGet on linux/x64 by default (~300MB). Skipping that keeps local/CI installs
# network-free and prevents npm's optional-dependency chain (@huggingface/
# transformers) from being dropped entirely whenever that download fails —
# which previously left `@huggingface/transformers` missing after `npm install`
# and broke startup with a crash in the transformers loader.
onnxruntime-node-install=skip

1
.nvmrc
View File

@@ -1 +0,0 @@
24

View File

@@ -1,37 +0,0 @@
# wasm-bindgen glue + embedded WASM_BASE64. Prettier rewrites the generated JS
# (quotes, wrapping) on any touch of this file; format tinycmsDomMocks.ts instead.
open-sse/executors/tinycmsSigner.ts
# Long reference tables are manually aligned; formatting the whole file causes noisy diffs.
docs/reference/ENVIRONMENT.md
# Generated by `npm run gen:provider-reference`; the generator aligns the tables and
# is their formatter of record. Without this, lint-staged reformats the file whenever
# it is staged and the next generator run reverts it — a diff ping-pong.
docs/reference/PROVIDER_REFERENCE.md
# Dense auto-generated free-tier budget rows (one object per line) — prettier multi-line expand blows past file-size cap 800.
open-sse/config/freeModelCatalog.data.ts
# Generated by scripts/skills/generate-agent-skills.mjs; the generator is their
# formatter of record and check:agent-skills-sync diffs its output byte-for-byte.
# Prettier reformats the frontmatter (blank line after ---), which makes the gate
# fail on any skill that happens to pass through lint-staged.
skills/*/SKILL.md
skills/*/references/*.md
# check:changelog-integrity compares release bullets against the base as exact
# strings. Prettier normalizes markdown emphasis inside them (*from* -> _from_)
# and re-wraps table rows, so any PR that stages CHANGELOG.md would "lose" base
# bullets and turn the merge-integrity job red. The changelog is generated and
# reconciled by scripts/release/*, which are its formatter of record.
CHANGELOG.md
docs/i18n/*/CHANGELOG.md
# Helm templates are Go text/template, not YAML: `{{- if ... }}` at the start of
# a line is a parse error for Prettier's YAML parser. Helm itself is the
# formatter of record here — `helm lint` and `helm template` validate them.
deploy/helm/*/templates/
# packages/ui-kit/ — vendored snapshot of the CI UI Kit; synced verbatim by scripts/dev/sync-ui-kit.sh, formatted upstream.
packages/ui-kit/src/**

View File

@@ -1,22 +0,0 @@
[
{
"name": "CLI entry (omniroute.mjs)",
"path": "bin/omniroute.mjs",
"limit": "15 KB"
},
{
"name": "MCP server entry (mcp-server.mjs)",
"path": "bin/mcp-server.mjs",
"limit": "5 KB"
},
{
"name": "Node runtime support (nodeRuntimeSupport.mjs)",
"path": "bin/nodeRuntimeSupport.mjs",
"limit": "8 KB"
},
{
"name": "Reset password entry (reset-password.mjs)",
"path": "bin/reset-password.mjs",
"limit": "6 KB"
}
]

View File

@@ -1,28 +0,0 @@
# .trivyignore — accepted-risk suppressions for the container image scan
#
# Policy (see docs/security/SUPPLY_CHAIN.md):
# - The Trivy steps in .github/workflows/docker-publish.yml run with
# `ignore-unfixed: true`, so vulnerabilities WITHOUT a published fix are
# already excluded from both the blocking CRITICAL gate and the advisory
# Security-tab upload. You do NOT need an entry here for an unfixable
# base-image OS CVE — it will not be reported.
# - This file is the single auditable home for the rare case where a *fixable*
# CVE must be temporarily accepted (e.g. the upstream fix is not yet in the
# pinned base tag, or the affected package/binary is provably unreachable
# from the proxy request surface and rebuilding now is not justified).
#
# Format — one CVE id per line, each with a justification comment and, where
# possible, an expiry, e.g.:
# # CVE-XXXX-YYYY — <why accepted>; revisit on next base-image bump (YYYY-MM-DD)
# CVE-XXXX-YYYY
#
# Keep this list SHORT and reviewed every release. Prefer fixing (rebuild on a
# patched base / bump the dep) over suppressing. Stale entries are debt.
# CVE-2026-118764 (minimatch 10.2.5, fix 11.0.1) and CVE-2026-118773 (glob 13.0.6, fix 14.0.2)
# live in the npm bundled in the image, and npm 12.2.1 (latest) still declares the
# vulnerable lines. Medium; OmniRoute calls npm with fixed subcommands, so request input
# does not reach npm as a glob. An overlay would cross majors outside npm's ranges.
# Accepted by the maintainer (#18765); revisit when npm ships the fixed lines (2026-12-02).
CVE-2026-118764
CVE-2026-118773

View File

@@ -1,15 +0,0 @@
# Advisory prose lint for OmniRoute docs (Vale — https://vale.sh).
# Warning-first: surfaces vague language, passive voice, and terminology drift without
# blocking CI. The Microsoft style is pulled by the CI step (vale sync / vale-action).
# Project terms live in the OmniRoute vocabulary so they never read as misspellings.
StylesPath = .vale/styles
MinAlertLevel = warning
Packages = Microsoft
Vocab = OmniRoute
[*.md]
BasedOnStyles = Vale, Microsoft
# Code-heavy reference docs and auto-generated catalogs are noisy under prose rules.
[docs/reference/PROVIDER_REFERENCE.md]
BasedOnStyles = Vale

View File

@@ -1,50 +0,0 @@
OmniRoute
combo
combos
[Cc]ombo
[Aa]uto-[Cc]ombo
MCP
A2A
ACP
RTK
Caveman
Troglodita
Qdrant
FTS5
SQLite
LowDB
OAuth
PKCE
SSE
JSON-RPC
LKGP
P2C
Antigravity
Codex
Kiro
Qoder
Pollinations
LongCat
Cerebras
DeepSeek
Groq
Cline
OpenCode
Termux
Electron
Fumadocs
Notion
Obsidian
WebDAV
IPv4
IPv6
SOCKS5
loopback
backoff
changelog
i18n
locale
locales
roadmap
[Ww]ildcard
upstream

122
.vscode/settings.json vendored
View File

@@ -1,5 +1,4 @@
{
"workbench.sideBar.location": "left",
"css.lint.unknownAtRules": "ignore",
"sonarlint.rules": {
"css:S4662": {
@@ -17,126 +16,5 @@
"javascript:S3776": {
"level": "off"
}
},
"git.ignoreLimitWarning": true,
// ─── Git: não adicionar os ~44 repos aninhados (9 worktrees + _references/* +
// _mono_repo/* + _ideia/_tasks/.agents) ao Source Control. Era a causa do
// "validando muito": um git status + watcher por repo. Só o repo raiz fica. ───
"git.autoRepositoryDetection": false,
"git.repositoryScanMaxDepth": 0,
"git.detectSubmodules": false,
"git.autofetch": false,
"git.autorefresh": true,
// ─── Performance: não seguir o symlink de node_modules criado pelas worktrees ───
// As worktrees em .worktrees/ apontam node_modules para o checkout principal;
// sem isto a busca atravessa o symlink mesmo com node_modules excluído.
"search.followSymlinks": false,
// ─── TypeScript server (monorepo grande: ~6,6k arquivos rastreados, Next.js 16) ───
"typescript.tsserver.maxTsServerMemory": 4096,
"typescript.disableAutomaticTypeAcquisition": true,
"typescript.tsc.autoDetect": "off",
"npm.autoDetect": "off",
// O tsserver tem o próprio watcher (independente de files.watcherExclude).
// excludeDirectories evita que ele vigie as árvores pesadas.
"typescript.tsserver.watchOptions": {
"excludeDirectories": [
"**/node_modules",
"**/.next",
"**/.build",
"**/dist",
"**/coverage",
"**/.worktrees",
"**/.claude/worktrees",
"**/electron",
"**/_references",
"**/_mono_repo",
"**/_tasks"
]
},
// Para esconder os diretórios gerados da árvore do Explorer, descomente:
// (MANTIDO comentado — o dono precisa ver _references/_mono_repo/_tasks na árvore.
// A performance é resolvida por watcherExclude + search.exclude + tsserver, sem
// precisar escondê-los do Explorer.)
// "files.exclude": {
// "**/.worktrees": true,
// "**/coverage": true,
// "**/dist": true,
// "**/.build": true,
// "**/.next": true,
// "**/_references": true,
// "**/_mono_repo": true,
// "**/_tasks": true,
// "**/omniroute-*.tgz": true
// },
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
"**/node_modules/**": true,
"**/.next/**": true,
"**/.build/**": true,
"**/dist/**": true,
"**/build/**": true,
"**/out/**": true,
"**/coverage/**": true,
"**/.coverage/**": true,
"**/.nyc_output/**": true,
"**/.cache/**": true,
"**/.turbo/**": true,
"**/.swc/**": true,
"**/.stryker-tmp/**": true,
"**/stryker-output-*/**": true,
"**/playwright-report/**": true,
"**/test-results/**": true,
"**/.worktrees/**": true,
"**/.claude/worktrees/**": true,
"**/electron/**": true,
"**/_references/**": true,
"**/_mono_repo/**": true,
"**/_tasks/**": true,
"**/logs/**": true,
"**/*.tgz": true,
"**/*.tsbuildinfo": true,
"**/OmniRoute-*/**": true,
"**/*-merge-*/**": true,
"**/*-worktree-*/**": true,
"**/*-issues-*/**": true,
"**/*-reorg*/**": true
},
"search.exclude": {
"**/node_modules": true,
"**/.next": true,
"**/.build": true,
"**/dist": true,
"**/build": true,
"**/out": true,
"**/coverage": true,
"**/.coverage": true,
"**/.nyc_output": true,
"**/.cache": true,
"**/.turbo": true,
"**/.swc": true,
"**/.stryker-tmp": true,
"**/stryker-output-*": true,
"**/playwright-report": true,
"**/test-results": true,
"**/.worktrees": true,
"**/.claude/worktrees": true,
"**/electron": true,
"**/_references": true,
"**/_mono_repo": true,
"**/_tasks": true,
"**/logs": true,
"**/*.tgz": true,
"**/*.tsbuildinfo": true,
"**/package-lock.json": true,
"**/OmniRoute-*": true,
"**/*-merge-*": true,
"**/*-worktree-*": true,
"**/*-issues-*": true,
"**/*-reorg*": true
}
}

View File

@@ -1,104 +0,0 @@
# .zizmor.yml — zizmor security audit configuration
# https://github.com/woodruffw/zizmor
#
# zizmor audits GitHub Actions workflows for security anti-patterns:
# • Unpinned third-party actions (supply-chain risk)
# • Script injection via ${{ github.* }} in run: steps
# • pull_request_target misuse (allows untrusted code to reach secrets)
# • Excessive permissions / overly broad GITHUB_TOKEN scopes
# • Cache poisoning via actions/cache with unguarded keys
# • … 20+ additional audits
#
# MOTIVATION (2026-03 incident): the trivy-action/LiteLLM supply-chain attack
# exploited exactly the kind of pull_request_target misconfiguration that zizmor
# detects statically. OmniRoute's npm/Docker/Electron publish workflows are high-
# value targets that warrant proactive audit.
#
# BASELINE STRATEGY: this file starts with an EMPTY ignores list. As zizmor is
# first run against the existing workflows, findings will be reviewed:
# • True positives → fix the workflow (preferred)
# • Accepted risk → add an entry below with a justification comment
# This enforces the same stale-enforcement discipline as other allowlists in
# this project: every ignore requires human sign-off and is subject to review
# at each release cycle.
#
# RATCHET: zizmorFindings metric in quality-baseline.json (direction: down)
# starts advisory; current baseline is frozen at first green run; new findings
# must be remediated or explicitly ignored here.
# ── Global settings ──────────────────────────────────────────────────────────
# Uncomment to pin to a specific minimum severity level.
# min-severity: low # low | medium | high | critical (default: low = all)
# ── Per-rule ignores ─────────────────────────────────────────────────────────
# zizmor ≥1.0 replaced the old top-level `ignores:` list with a `rules:` map
# keyed by audit id. Per-rule config lives under `rules.<audit-id>.ignore`,
# where each entry is `filename` or `filename:line` (line optional, column
# further-optional). See: https://docs.zizmor.sh/configuration/
#
# Format:
# rules:
# <zizmor-audit-id>: # e.g. "unpinned-uses", "template-injection"
# ignore:
# - <workflow-filename> # ignore this audit across the file
# - <workflow-filename>:<line> # or scope to a specific line
#
# Example (do not uncomment without real justification):
#
# rules:
# unpinned-uses:
# # actions/checkout@v6 is pinned at the major-version tag intentionally:
# # GitHub-managed first-party action; SHA pinning buys little against a
# # GitHub-side compromise and adds significant maintenance burden.
# ignore:
# - ci.yml
# Every entry below is an explicit, justified ignore (same stale-review
# discipline as the other allowlists in this project). New ignores require a
# per-rule entry with a justification comment.
rules:
dangerous-triggers:
# deploy-vps.yml uses `on: workflow_run` (after "Publish to Docker Hub").
# zizmor flags workflow_run as "almost always used insecurely", but this one
# is guarded and not exploitable:
# • The deploy job is gated on `github.event.workflow_run.conclusion ==
# 'success'` (deploy-vps.yml job `if:`, L15), so it only runs after a
# successful, trusted upstream run — never on a forked/PR-triggered
# failure.
# • It does NOT checkout or execute untrusted code: the deploy runs over SSH
# using repository secrets; there is no `actions/checkout` of an attacker
# ref in the privileged context.
# Accepted risk, re-review at the next release cycle (added 2026-06-15).
ignore:
- deploy-vps.yml
cache-poisoning:
# zizmor's cache-poisoning audit flags `actions/setup-node` (cache: npm) and
# `actions/cache` steps that populate a cache which a later artifact-publishing
# job could consume — the attack is: a fork PR seeds a poisoned cache that a
# trusted publish run then restores and ships. None of the four entries below
# are exploitable in that way:
#
# • electron-release.yml / npm-publish.yml — PUBLISH workflows that trigger
# ONLY on trusted events: `push: tags v*` + `workflow_dispatch` (electron)
# and `release: [released]` + `workflow_dispatch` + `workflow_call`
# (npm). They NEVER run on a `pull_request` from a fork, so an untrusted
# ref can never populate the npm/node_modules cache they restore. The
# cache key is `hashFiles('package-lock.json')` / `runner.os-node-…`, a
# first-party, lockfile-pinned key on trusted events.
#
# • opencode-plugin-ci.yml / opencode-provider-ci.yml — CI-only workflows
# (lint/test of the two opencode packages). They DO run on `pull_request`,
# but (a) they publish NO artifacts — there is no downstream publish job
# that restores their cache, and (b) GitHub Actions cache is branch-scoped:
# a fork-PR run writes to a PR-isolated cache that base-branch / release
# runs cannot read. The `cache: npm` here only speeds up `npm ci` within
# the same ephemeral CI run.
#
# Accepted risk (first-party caching on trusted/isolated events), re-review at
# the next release cycle (added 2026-06-16).
ignore:
- electron-release.yml
- npm-publish.yml
- opencode-plugin-ci.yml
- opencode-provider-ci.yml

View File

@@ -1,4 +0,0 @@
node_modules
dist
*.log
.DS_Store

View File

@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 OmniRoute contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,191 +0,0 @@
# @omniroute/opencode-plugin-v2
OpenCode v2 plugin (`define({ id, setup })`, Promise API) that publishes the live OmniRoute catalog — models from `/v1/models`, combos from `/api/combos` (least-common-denominator join), enrichment (names + pricing), and usable-provider filtering — into the v2 `catalog.transform`, with `key` + `env` auth via `integration.transform`.
Companion to `@omniroute/opencode-plugin` (OpenCode v1, same repo). The two packages are independent: this one carries its own catalog-mapping logic and the v1 plugin is left untouched.
## Install
```sh
npm install @omniroute/opencode-plugin-v2
```
`opencode.json`:
```json
{
"plugins": [
{
"package": "@omniroute/opencode-plugin-v2",
"options": {
"providerId": "omniroute",
"baseURL": "http://localhost:20128"
}
}
]
}
```
### Local `file://` install
OpenCode resolves a local plugin **directory** by probing the subpaths
`server.*` / `index.*` (then `tui`, `rpc`) at the package root — it never
reads `package.json` `main`/`exports`. A folder exposing only `dist/` is
therefore silently skipped (no `loading plugin`, no error).
This package ships a root `server.js` re-exporting `./dist/index.js` for
exactly that probe, so pointing OpenCode at a local checkout works:
```json
{
"plugins": [
{
"package": "file:///path/to/OmniRoute/@omniroute/opencode-plugin-v2",
"options": {
"providerId": "omniroute",
"baseURL": "http://localhost:20128"
}
}
]
}
```
Prerequisites when targeting a folder: run `npm run build` first (the root
`server.js` re-exports `./dist/index.js`), and keep the folder's root
`server.js` — `dist/` alone is not resolvable by the host.
## Credentials
The plugin needs a gateway key to read the catalog, and looks for one in this
order:
1. **The credential you connected in OpenCode.** The plugin registers an
integration, so `opencode auth` (or the Connect action in the model picker)
can store a key for it. Nothing is written to `opencode.json` — this is the
recommended route.
2. **`apiKey` in the plugin options**, when you want a per-project override.
Remember that this puts the key in a config file you may be committing.
3. **`OMNIROUTE_API_KEY` in the environment.**
If none of the three yields a key, the catalog is empty and the plugin says so
once at startup rather than leaving you with a silent empty model list.
### The management token is a different key
Combos, provider health and enrichment (display names, pricing, free-tier
budgets) come from the gateway's `/api/*` endpoints, which most deployments
gate behind a **management** token rather than the inference key. Set it
explicitly:
```json
"options": {
"baseURL": "http://localhost:20128",
"managementReadToken": "<management read token>"
}
```
The token can also come from the `OMNIROUTE_MANAGEMENT_API_KEY` environment
variable (the option wins when both are set). Resolution order:
`managementReadToken` option, then `OMNIROUTE_MANAGEMENT_API_KEY`, then the
`apiKey` fallback.
Left unset, `managementReadToken` falls back to `apiKey` for backwards
compatibility, and the plugin warns once at startup that the fallback is
active. When a gateway rejects that fallback, the catalog still
publishes — but with raw model ids instead of display names, no canonical
alias dedupe, no pricing and no combos. The plugin warns once per endpoint
when this happens, naming the endpoint and the consequence, so the degraded
catalog is never a mystery. Environment variables must reach the opencode
server process: when the host runs as a service, export the key where the
server reads it, not only in the shell that runs `opencode models`.
## Options
| Key | Default | Notes |
| --------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `providerId` | `"omniroute"` | Provider id and integration id; models publish under `<providerId>/…` |
| `baseURL` | required | OmniRoute gateway root (no `/v1` suffix needed) |
| `apiKey` | connected credential, then `OMNIROUTE_API_KEY` | Chat key for `/v1/*` — see [Credentials](#credentials) |
| `managementReadToken` | option, then `OMNIROUTE_MANAGEMENT_API_KEY`, then `apiKey` | Management key for `/api/*` (combos, providers, enrichment) — usually **not** the same key |
| `displayName` | `"OmniRoute"` | Provider display name |
| `timeoutMs` | `10000` | Per-endpoint fetch timeout |
| `modelCacheTtlMs` | `300000` | Catalog cache TTL and background refresh period (minimum 60000 ms): the served catalog follows the gateway within this window, with no service restart; disk snapshot warms cold starts |
| `timeouts` | per-endpoint override | `{ models, combos, enrichment }` in ms; falls back to `timeoutMs` (`autoCombos` still parses but is ignored — the virtual-entries route is no longer requested) |
| `enrichment` | `true` | Fetch names + pricing (`/api/pricing*`, `/api/free-tier/summary`) |
| `providerTag` | `true` | Prefix a display name with the upstream provider it routes to |
| `geminiSanitization` | `true` | Strip `$schema`/`additionalProperties` from tool schemas sent to Gemini models (`$ref` tools are forwarded untouched) |
| `usableOnly` | `false` | Filter to healthy provisioned providers (`/api/providers`) |
| `combosSource` | `"api"` | Combo source. `"api"` reads `/api/combos` and publishes a combo only when every member passes the filters; `"models"` skips that request and publishes the combo rows `/v1/models` serves. Any preset, `usableOnly`, `providersAllow` or visible/hidden list keeps `"api"` |
| `freeOnly` / `toolsOnly` / `visionOnly` | `false` / `false` / `false` | Filter to free-tier / tool-calling / image-input models; combos with a filtered member are dropped, never partial. Presets filter the pool before the default view ranks it, and a combo publishes only when every resolved member passes (dropped when a member fails or none resolves) |
| `freeSignals` | `["declared"]` | Extra signals that admit a model under `freeOnly`: `priced`, `named`, `provider-named` (see below) |
| `freeProviders` | none | Provider prefixes counted as free by `provider-named` |
| `showcasePerOwner` | `10` | Default-view entries kept per provider |
| `freshPerOwner` | `10` | Default-view fresh entries kept per provider |
| `freshWindowDays` | `90` | Freshness window in days for the fresh branch |
| `usageMemory` | `true` | Restore statically dropped entries named by 30-day usage analytics (needs a management token; inert without one) |
| `visibleModels` / `hiddenModels` | `[]` | Exact (`cc/keep-me`), suffix (`keep-me`), or branch (`prefix/*`) entries ; deny wins ; `"*"` publishes the full catalog and skips narrowing |
| `providersAllow` | `[]` | Provider allowlist by flat name, or branch claim (`prefix/*`) for exhaustive mode ; a branch claim names a branch, a flat entry names a provider prefix |
| `combos` | `true` | Set to `false` to hide every combo (no `/api/combos` request, no combo rows from `/v1/models`) ; models are unchanged |
| `apiFormat.allowAnthropic` | `false` | Route allowlisted ids to the Anthropic API block |
| `apiFormat.anthropicModels` | `[]` | Full model ids routed to Anthropic |
| `apiFormat.anthropicPrefixes` | v1 defaults | Deprecated, warns once — prefer `anthropicModels` |
| `logLevel` / `startupDebug` | `warn` / `false` | Logger verbosity |
`toolsOnly` is off by default, so the full catalog is published. Set
`toolsOnly: true` to hide models without tool calling from the host picker —
useful for agent sessions that call tools on almost every turn. It does not cap
the catalog size, and a very large catalog can still slow the host picker (see
[opencode#47615](https://github.com/anomalyco/opencode/issues/47615)).
Usage memory is on by default. Without a management token it stays inert
(a startup notice is logged) and nothing is restored — the picker stays filtered.
`"*"` publishes the full catalog and ignores showcase and fresh narrowing.
A visible branch keeps a combo when any member is in the branch ; `hiddenModels` removes the same combo the same way. Combos are filtered by members, not by combo id.
A visible entry pins its branch : the whole branch is published, including rows the default view would drop (retired rows, rows past the fresh and showcase caps) ; capability filters and `usableOnly` still apply.
## Inferred free models
`freeOnly` keeps the models the free-tier catalog classifies. That list can lag what the gateway serves, so `freeSignals` lets you opt into a few weaker signals. The default stays `["declared"]`; nothing changes unless you set it. Models admitted by an inferred signal are labelled `(free, inferred)`.
| Signal | Admits a model when |
| ---------------- | ----------------------------------------------------------------------------------------------- |
| `priced` | the pricing table lists `input` and `output` at `0` for its `<provider>/<model>` id |
| `named` | its id ends in `-free` or `:free` and the pricing table holds no price for it (any price field) |
| `provider-named` | its provider prefix ends in `-free`, or is listed in `freeProviders` |
```json
{ "freeOnly": true, "freeSignals": ["declared", "priced", "named"] }
```
What the signals do not do:
- A declared classification always wins. `one-time-initial` and `discontinued` entries are never promoted, and any price field other than zero (`input`, `output`, `cacheRead`, `cacheWrite`) vetoes every inferred signal.
- Bare ids (no provider prefix) are never inferred, and a price stored under a bare id is ignored.
- Router entries (an `auto` or `auto-*` segment after the provider prefix) carry a placeholder zero price, so `priced` skips them. Routers whose price depends on the routed target (`pareto-code`, `bodybuilder`) are not recognised and may be admitted by `priced`, `named` or `provider-named`.
- `freeProviders` matches the provider prefix as served or its alias/canonical twin, case-insensitively.
- With `provider-named` on, no overlay is needed, so the empty-overlay warning is not issued; with the other signals it still is when the overlay is fully empty.
- A zero price can also mean a trial credit or a quota the pricing table does not model. Treat `(free, inferred)` as "looks free", not as a contract.
## Tool calling on Gemini models
Gemini answers `400 INVALID_ARGUMENT` — for the whole request, not just the
offending tool — when a tool declaration carries `$schema` or
`additionalProperties`. Anything that emits standard JSON Schema therefore
breaks tool calling as soon as the chain routes to Gemini.
The plugin strips those keywords from tool schemas bound for a Gemini model of
this provider, and leaves every other request untouched. A tool carrying a
`$ref` is forwarded untouched instead of stripped: removing the reference
would widen the schema to "accept anything". Set
`"geminiSanitization": false` to turn it off.
## Migrating from the v1 plugin
The v2 plugin publishes provider id `X` bare. The v1 plugin published `opencode-X` (native-adapter gate). Sessions pinned to `opencode-X/...` must re-select the model under `X/...`.
## License
MIT

View File

@@ -1,9 +0,0 @@
# Release process — `@omniroute/opencode-plugin-v2`
## Publishing
One package, no ordering: bump `@omniroute/opencode-plugin-v2` (`npm version patch`) and publish it. The plugin carries its own copy of the mapping logic, so a release never has to be coordinated with another package.
## Migration note (`opencode-X` → `X`)
The v1 plugin published provider id `opencode-X` (native-adapter gate). The v2 plugin publishes `X` bare. Sessions pinned to `opencode-X/...` resolve `ModelUnavailableError` — users must re-select the model under `X/...`.

File diff suppressed because it is too large Load Diff

View File

@@ -1,72 +0,0 @@
{
"name": "@omniroute/opencode-plugin-v2",
"version": "0.1.0",
"description": "OmniRoute OpenCode plugin (v2 Promise API): catalog transform with models, combos, enrichment, and naming.",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist",
"server.js",
"README.md",
"LICENSE"
],
"scripts": {
"build": "tsup",
"clean": "rm -rf dist",
"test": "node --import tsx/esm --test tests/*.test.ts",
"prepublishOnly": "npm run clean && npm run build && npm test"
},
"dependencies": {
"zod": "^4.6.7"
},
"devDependencies": {
"@opencode/plugin": "2.0.12",
"@types/node": "^22.19.19",
"tsup": "^8.5.1",
"tsx": "^4.22.3",
"typescript": "^5.9.3"
},
"engines": {
"node": ">=22.22.3"
},
"license": "MIT",
"author": "OmniRoute contributors",
"repository": {
"type": "git",
"url": "https://github.com/cheaper-inference/OmniRoute.git",
"directory": "@omniroute/opencode-plugin-v2"
},
"homepage": "https://github.com/cheaper-inference/OmniRoute/tree/main/%40omniroute/opencode-plugin-v2#readme",
"bugs": {
"url": "https://github.com/cheaper-inference/OmniRoute/issues"
},
"keywords": [
"omniroute",
"opencode",
"opencode-plugin",
"opencode-v2",
"ai-sdk",
"openai-compatible",
"provider",
"catalog",
"combos",
"gemini"
],
"publishConfig": {
"access": "public"
},
"peerDependencies": {
"@opencode/plugin": ">=2.0.12 <3"
},
"overrides": {
"esbuild": "^0.28.1",
"zod": "$zod"
}
}

View File

@@ -1,10 +0,0 @@
// Root entrypoint for OpenCode host plugin loading.
//
// OpenCode 2.x local installs (`file://` directory in `opencode.json`) never
// read package.json `main`/`exports`: the config scan resolves only the
// subpaths ["server", ""] then ["tui"], ["rpc"] from the package directory.
// With only `dist/index.js` present the scan yields `{}` and the plugin is
// silently dropped (no `loading plugin`, no error). This stable re-export
// keeps `dist/` as the only build output while exposing the module the host
// actually probes for.
export { default } from "./dist/index.js";

View File

@@ -1,255 +0,0 @@
import { createHash } from "node:crypto";
import { homedir } from "node:os";
import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import type {
OmniRouteEnrichmentEntry,
OmniRouteEnrichmentMap,
OmniRouteProviderConnection,
OmniRouteRawCombo,
OmniRouteRawModelEntry,
} from "./shared/index.js";
import { isHttpUrl } from "./shared/index.js";
export const DEFAULT_MODEL_CACHE_TTL_MS = 300_000 as const;
/**
* Lower bound on the background refresh period. Keeps the loop from spinning
* on configurations that set a tiny TTL (the existing tests use 1 ms) and
* matches the v1 minimum.
*/
export const MIN_REFRESH_INTERVAL_MS = 60_000 as const;
/**
* Breather after a refresh whose models fetch came back empty (gateway down
* or refusing). Transforms inside the window serve last-known-good without
* re-firing the fetch suite. Short on purpose: it only guards the
* pathological case, normal TTL expiry still refetches every window.
*/
export const UNREACHABLE_COOLDOWN_MS = 15_000 as const;
export interface CatalogSnapshot {
models: OmniRouteRawModelEntry[];
combos: OmniRouteRawCombo[];
providers?: OmniRouteProviderConnection[];
enrichment?: OmniRouteEnrichmentMap;
fetchedAt: number;
}
export const SNAPSHOT_FORMAT_VERSION = 2 as const;
/**
* A raw snapshot entry is stale when it cannot be mapped to a publishable
* model: no string `id` (unroutable), or a pre-mapped `api` block missing a
* valid `npm` package (the runner would reject it as `Unsupported package`)
* or a usable `url` (the host would reach the AI SDK with no baseURL).
* Plain `/v1/models` entries carry no `api` block -- it is synthesized at
* publish time -- so only a present-but-invalid block drops the entry.
*/
export function isStaleSnapshotModel(entry: unknown): boolean {
if (!entry || typeof entry !== "object") return true;
const id = (entry as { id?: unknown }).id;
if (typeof id !== "string" || id.length === 0) return true;
const api = (entry as { api?: unknown }).api;
if (api === undefined) return false;
if (!api || typeof api !== "object") return true;
const npm = (api as { npm?: unknown }).npm;
if (typeof npm !== "string" || npm.length === 0) return true;
// Same requirement as `npm`, and the same predicate the options schema
// applies to `baseURL`: a pre-mapped block without a callable `url` publishes
// a model the host cannot route -- see `legacyApiToInfoApi`.
return !isHttpUrl((api as { url?: unknown }).url);
}
interface DiskSnapshotV2 {
v: 2;
identityFingerprint: string;
models: OmniRouteRawModelEntry[];
combos: OmniRouteRawCombo[];
providers?: OmniRouteProviderConnection[];
/**
* Display names, provider labels, pricing and free-tier budgets, as
* `[key, entry]` pairs (a Map does not survive JSON). Persisted because a
* cold start otherwise publishes raw model ids until the first refresh
* completes — which is the moment the snapshot exists to cover.
*/
enrichment?: [string, OmniRouteEnrichmentEntry][];
writtenAt: number;
}
/**
* Ceiling on what one snapshot may occupy on disk. A gateway with thousands of
* models makes this file grow without bound otherwise; past the cap the
* enrichment overlay is dropped first (it is rebuilt on the next refresh)
* rather than losing the catalog itself.
*/
const MAX_SNAPSHOT_BYTES = 32 * 1024 * 1024;
// Suffix for the temp file each write publishes via rename. Monotone per
// process: two writes for one provider (for example across a credential
// rotation) must not share a temp name. Built after the empty-models and
// size-cap guards, so only real attempts consume a value.
let snapshotWriteCounter = 0;
function trimTrailingSlashes(value: string): string {
let i = value.length;
while (i > 0 && value.charCodeAt(i - 1) === 0x2f) i -= 1;
return i === value.length ? value : value.slice(0, i);
}
function normalizeBaseURL(baseURL: string): string {
try {
const parsed = new URL(baseURL);
parsed.hash = "";
parsed.pathname = trimTrailingSlashes(parsed.pathname) || "/";
return parsed.toString();
} catch {
return trimTrailingSlashes(baseURL);
}
}
export function memoryCacheKey(baseURL: string, credentialId: string): string {
return `${baseURL}::${createHash("sha256").update(credentialId).digest("hex")}`;
}
export function snapshotIdentityFingerprint(
baseURL: string,
apiKey: string,
managementReadToken: string
): string {
return createHash("sha256")
.update(JSON.stringify([normalizeBaseURL(baseURL), apiKey, managementReadToken]))
.digest("hex");
}
export function diskSnapshotPath(providerId: string): string {
// OPENCODE_DATA_DIR is honoured verbatim when set: whoever controls the
// process environment already chooses where the process writes, so
// resolving it further would only surprise. The providerId segment stays
// bounded by the options schema (letters, digits, '.', '_' and '-'; never
// "." or ".."), keeping the file inside <dir>/plugins/.
const dir = process.env.OPENCODE_DATA_DIR ?? join(homedir(), ".local", "share", "opencode");
return join(dir, "plugins", `omniroute-${providerId}.json`);
}
export async function readDiskSnapshot(
providerId: string,
identityFingerprint: string,
logger?: { warn: (message: string) => void }
): Promise<CatalogSnapshot | undefined> {
try {
const body = await readFile(diskSnapshotPath(providerId), "utf8");
// A retired snapshot field survives JSON.parse as an unknown key and is
// never read back, so legacy snapshots load with it ignored.
const parsed = JSON.parse(body) as Partial<DiskSnapshotV2> & {
autoCombos?: unknown;
};
void (parsed as { autoCombos?: unknown }).autoCombos;
if (
!parsed ||
typeof parsed.v !== "number" ||
parsed.v !== SNAPSHOT_FORMAT_VERSION ||
typeof parsed.identityFingerprint !== "string" ||
parsed.identityFingerprint !== identityFingerprint
) {
return undefined;
}
if (
!Array.isArray(parsed.models) ||
parsed.models.length === 0 ||
!Array.isArray(parsed.combos)
) {
return undefined;
}
const stale = (parsed.models as unknown[]).filter(isStaleSnapshotModel).length;
const models = (parsed.models as OmniRouteRawModelEntry[]).filter(
(entry) => !isStaleSnapshotModel(entry)
);
if (stale > 0) {
logger?.warn(
`[omniroute-v2] dropping ${stale} stale snapshot entries with an unusable api block`
);
}
if (models.length === 0) return undefined;
return {
models,
combos: parsed.combos as OmniRouteRawCombo[],
providers: Array.isArray(parsed.providers)
? (parsed.providers as OmniRouteProviderConnection[])
: [],
// A snapshot written before this field existed, or one whose overlay was
// dropped for size, simply starts unenriched and recovers on the first
// refresh — the same state as before it was persisted at all.
enrichment: Array.isArray(parsed.enrichment)
? new Map(parsed.enrichment as [string, OmniRouteEnrichmentEntry][])
: undefined,
fetchedAt: typeof parsed.writtenAt === "number" ? parsed.writtenAt : Date.now(),
};
} catch {
return undefined;
}
}
export async function writeDiskSnapshot(
providerId: string,
snapshot: CatalogSnapshot,
identityFingerprint: string,
logger?: { warn: (message: string) => void }
): Promise<void> {
// Monotone per-process suffix: two writes for one provider (for example
// across a credential rotation) must not share a temp name. Declared here
// so the catch below can clean it up; assigned after the guards so only
// real attempts consume a counter value.
let tmp = "";
try {
if (snapshot.models.length === 0) return;
const file = diskSnapshotPath(providerId);
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
const envelope: DiskSnapshotV2 = {
v: 2,
identityFingerprint,
models: snapshot.models,
combos: snapshot.combos,
providers: snapshot.providers ?? [],
enrichment: snapshot.enrichment ? [...snapshot.enrichment.entries()] : undefined,
writtenAt: Date.now(),
};
let payload = JSON.stringify(envelope);
if (
Buffer.byteLength(payload, "utf8") > MAX_SNAPSHOT_BYTES &&
envelope.enrichment !== undefined
) {
delete envelope.enrichment;
payload = JSON.stringify(envelope);
}
if (Buffer.byteLength(payload, "utf8") > MAX_SNAPSHOT_BYTES) {
logger?.warn(
`[omniroute-v2] snapshot for ${providerId} exceeds the size cap, skipping disk write`
);
return;
}
tmp = `${file}.${process.pid}.${snapshotWriteCounter++}`;
await writeFile(tmp, payload, { encoding: "utf8", mode: 0o600 });
await rename(tmp, file);
} catch (err) {
// Best-effort: callers already hold the in-memory entry.
logger?.warn(
`[omniroute-v2] snapshot write failed for ${providerId}: ` +
`${err instanceof Error ? err.message : String(err)}, keeping the in-memory entry`
);
try {
await unlink(tmp);
} catch {
// Ignore: the temp file may not exist (mkdir failed first).
}
}
}
export async function clearDiskSnapshot(providerId: string): Promise<boolean> {
try {
await unlink(diskSnapshotPath(providerId));
return true;
} catch {
return false;
}
}

View File

@@ -1,251 +0,0 @@
import type { LegacyModel } from "./legacy-model.js";
import type { OmniRouteEnrichmentEntry, OmniRouteEnrichmentMap } from "./shared/enrich.js";
import { lookupEnrichment } from "./shared/enrich.js";
import type { OmniRouteRawCombo } from "./shared/combos-map.js";
import type { OmniRouteRawModelEntry } from "./shared/models-map.js";
import { isFreeOnlyFreeType } from "./shared/naming.js";
export interface CapabilityPresetFlags {
freeOnly?: boolean;
/** The caller's inferred-free verdict for this entry (see `inferFreeSignal`). */
freeInferred?: boolean;
toolsOnly?: boolean;
visionOnly?: boolean;
}
/**
* Single subtractive predicate for the capability presets. Reads the
* mapped+enriched entry: `freeOnly` needs the enrichment overlay entry
* (absent entry = not free = dropped), `toolsOnly`/`visionOnly` read the
* mapped capabilities (proven 1:1 with the raw signals). Applied after the
* allowlist at the model and combo collection points. Auto combos are not
* published (#15392), so there is no third point to filter.
*/
export function passesCapabilityPresets(
mapped: LegacyModel,
enrichment: OmniRouteEnrichmentEntry | undefined,
flags: CapabilityPresetFlags
): boolean {
if (
flags.freeOnly === true &&
!isFreeOnlyFreeType(enrichment?.freeType) &&
flags.freeInferred !== true
)
return false;
if (flags.toolsOnly === true && mapped.capabilities.toolcall !== true) return false;
if (
flags.visionOnly === true &&
!(mapped.capabilities.attachment === true || mapped.capabilities.input.image === true)
)
return false;
return true;
}
/**
* Raw-entry form of the preset predicate for the ranks-before-filters
* pool. Reads the same signals as `passesCapabilityPresets` without
* mapping the entry first: `freeOnly` uses `isFreeOnlyFreeType` on the
* overlay row the caller resolved, `toolsOnly` reads `capabilities.tool_calling`,
* `visionOnly`
* reads `capabilities.attachment ?? capabilities.vision` or an `image`
* input modality (same `?? ["text"]` default as the mapper). Neutral
* when no preset is on, so the default view is unchanged without one.
*/
export function passesRawPreset(
raw: OmniRouteRawModelEntry,
enrichment: OmniRouteEnrichmentEntry | undefined,
flags: CapabilityPresetFlags
): boolean {
if (
flags.freeOnly === true &&
!isFreeOnlyFreeType(enrichment?.freeType) &&
flags.freeInferred !== true
)
return false;
if (flags.toolsOnly === true && Boolean(raw.capabilities?.tool_calling ?? false) !== true)
return false;
if (
flags.visionOnly === true &&
!(
Boolean(raw.capabilities?.attachment ?? raw.capabilities?.vision ?? false) ||
new Set(raw.input_modalities ?? ["text"]).has("image")
)
)
return false;
return true;
}
/** True when any preset subtracts: the pool narrows, combos resolve per member. */
export function presetsActive(flags: CapabilityPresetFlags): boolean {
return flags.freeOnly === true || flags.toolsOnly === true || flags.visionOnly === true;
}
/**
* Narrow a raw pool to the entries that pass the presets. The showcase
* and the recent picks rank this narrowed pool instead of ranking
* everything and letting the preset empty the pick. Neutral when no
* preset is on, so the default view is unchanged without one.
*/
export function filterRawPoolByPreset(
entries: readonly OmniRouteRawModelEntry[],
enrichment: OmniRouteEnrichmentMap | undefined,
canonicalToAlias: Map<string, string>,
flags: CapabilityPresetFlags,
isFreeInferred?: (id: string, entry: OmniRouteEnrichmentEntry | undefined) => boolean
): OmniRouteRawModelEntry[] {
if (!presetsActive(flags)) return [...entries];
return entries.filter((entry) => {
if (!entry.id) return false;
const row = lookupEnrichment(entry.id, enrichment, canonicalToAlias);
return passesRawPreset(entry, row, {
...flags,
freeInferred: isFreeInferred?.(entry.id, row) ?? flags.freeInferred,
});
});
}
interface ComboPresetStep {
memberEntries: OmniRouteRawModelEntry[];
deferred: boolean;
failsPreset: boolean;
countable: boolean;
}
function readComboStepField(step: unknown, key: "kind" | "comboName" | "model"): unknown {
return (step as Record<string, unknown> | null | undefined)?.[key];
}
/**
* Fold one combo step list into member entries plus the preset verdict.
* A `combo-ref` step reads the child verdict from `presetByName` (kept
* for dropped combos too): a ref to an unknown name stays deferred, a
* ref to a dropped combo fails. Never looks up an enrichment row for
* the synthesized `combo-ref:<name>` id (there is none). An unknown
* model id fails under an active preset, stays neutral without one.
*/
export function foldComboPresetSteps(
combo: OmniRouteRawCombo,
rawModelById: ReadonlyMap<string, OmniRouteRawModelEntry>,
resolvedByName: ReadonlyMap<string, LegacyModel>,
presetByName: ReadonlyMap<string, boolean>,
enrichment: OmniRouteEnrichmentMap | undefined,
canonicalToAlias: Map<string, string>,
flags: CapabilityPresetFlags,
isFreeInferred?: (id: string, entry: OmniRouteEnrichmentEntry | undefined) => boolean
): ComboPresetStep {
const memberEntries: OmniRouteRawModelEntry[] = [];
const active = presetsActive(flags);
let deferred = false;
let failsPreset = false;
let countable = false;
const memberSteps = Array.isArray(combo.models) ? combo.models : [];
for (const step of memberSteps) {
const kind = readComboStepField(step, "kind");
if (kind === "combo-ref") {
const comboName = readComboStepField(step, "comboName");
if (typeof comboName !== "string" || comboName.length === 0) continue;
if (active && presetByName.get(comboName) === false) {
failsPreset = true;
break;
}
const nested = resolvedByName.get(comboName);
if (!nested) {
deferred = true;
break;
}
if (active) countable = true;
memberEntries.push(synthesizeNestedMember(comboName, nested));
continue;
}
const modelId = readComboStepField(step, "model");
if (typeof modelId !== "string" || modelId.length === 0) continue;
const member = rawModelById.get(modelId);
if (!member) {
if (active) failsPreset = true;
continue;
}
if (active) {
countable = true;
const memberRow = lookupEnrichment(member.id, enrichment, canonicalToAlias);
if (
!passesRawPreset(member, memberRow, {
...flags,
freeInferred: isFreeInferred?.(member.id, memberRow) ?? flags.freeInferred,
})
) {
failsPreset = true;
break;
}
}
memberEntries.push(member);
}
return { memberEntries, deferred, failsPreset, countable };
}
/**
* Record the preset verdict of a resolved combo (published or dropped)
* under its lookup name: `name` trimmed, else `id`. Under an active
* preset a combo with no countable member never passes, so it is
* dropped, never partial.
*/
export function recordComboPresetVerdict(
presetByName: Map<string, boolean>,
combo: OmniRouteRawCombo,
failsPreset: boolean,
countable: boolean,
flags: CapabilityPresetFlags
): boolean {
const comboName =
typeof combo.name === "string" && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
const passes = !presetsActive(flags) || (failsPreset !== true && countable);
presetByName.set(comboName, passes);
return passes;
}
/** Lookup name of a combo: `name` trimmed, else `id`. */
export function comboLookupName(combo: OmniRouteRawCombo): string {
return typeof combo.name === "string" && combo.name.trim().length > 0
? combo.name.trim()
: combo.id;
}
/**
* Synthesize a raw-model entry from an already-resolved nested combo so a
* parent combo's LCD folds the whole nested capability vector (context,
* output, modalities, capabilities) instead of only direct raw members.
* v1 parity (combo member synthesis at nested resolution time).
*/
export function synthesizeNestedMember(name: string, nested: LegacyModel): OmniRouteRawModelEntry {
const inputModalities: string[] = [];
if (nested.capabilities.input.text) inputModalities.push("text");
if (nested.capabilities.input.audio) inputModalities.push("audio");
if (nested.capabilities.input.image) inputModalities.push("image");
if (nested.capabilities.input.video) inputModalities.push("video");
if (nested.capabilities.input.pdf) inputModalities.push("pdf");
const outputModalities: string[] = [];
if (nested.capabilities.output.text) outputModalities.push("text");
if (nested.capabilities.output.audio) outputModalities.push("audio");
if (nested.capabilities.output.image) outputModalities.push("image");
if (nested.capabilities.output.video) outputModalities.push("video");
if (nested.capabilities.output.pdf) outputModalities.push("pdf");
return {
id: `combo-ref:${name}`,
context_length: nested.limit.context,
max_output_tokens: nested.limit.output,
...(nested.limit.input !== undefined ? { max_input_tokens: nested.limit.input } : {}),
owned_by: "combo",
input_modalities: inputModalities,
output_modalities: outputModalities,
capabilities: {
temperature: nested.capabilities.temperature,
// A raw entry carries plain flags; the mapped model widens them to
// `boolean | { field }` (custom reasoning/thinking field). Every
// non-false form means the capability is present, which is all the
// LCD fold reads.
reasoning: nested.capabilities.reasoning !== false,
thinking: nested.capabilities.interleaved !== false,
attachment: nested.capabilities.attachment,
tool_calling: nested.capabilities.toolcall,
},
};
}

View File

@@ -1,233 +0,0 @@
import type { OmniRouteRawModelEntry } from "./shared/index.js";
import { matchesModelFilter, type ModelListFilter } from "./model-filter.js";
/**
* Freshness window in days. The millisecond value below derives from it,
* so tuning the default means touching this line only.
*/
export const FRESH_WINDOW_DAYS = 90;
/**
* Default freshness window in milliseconds. Models curated with a
* `release_date` or `last_updated` inside this window publish without any
* other signal.
*/
export const FRESHNESS_WINDOW_MS = FRESH_WINDOW_DAYS * 24 * 3600 * 1000;
/** How many models each provider keeps in the default showcase. */
export const SHOWCASE_PER_OWNER = 10;
/** How many recent models each provider keeps in the default view. */
export const FRESH_PER_OWNER = 10;
/**
* Convert a freshness window in days to milliseconds. A non-finite or
* non-positive value cannot come through parsed options (the schema rejects
* it), only through direct calls: fall back to the default window instead
* of an unbounded (Infinity) or empty (0) one.
*/
export function freshWindowDaysToMs(days: number): number {
if (!Number.isFinite(days) || days <= 0) return FRESHNESS_WINDOW_MS;
return days * 24 * 3600 * 1000;
}
/**
* Fresh when the newest valid curatorial date (`release_date`, then
* `last_updated`) is inside the window. No fallback to `created`:
* gateway-assembled rows carry the build timestamp there (same value for
* the whole catalog), except openrouter rows which mix an upstream value
* — neither works as a uniform freshness date.
*/
export function isFreshModel(
entry: OmniRouteRawModelEntry,
nowMs: number,
windowMs: number = FRESHNESS_WINDOW_MS
): boolean {
if (!Number.isFinite(windowMs) || windowMs <= 0) windowMs = FRESHNESS_WINDOW_MS;
const candidates = [entry.release_date, entry.last_updated];
let newest = Number.NaN;
for (const raw of candidates) {
if (typeof raw !== "string" || raw.length === 0) continue;
const parsed = Date.parse(raw);
if (Number.isNaN(parsed)) continue;
if (Number.isNaN(newest) || parsed > newest) newest = parsed;
}
if (Number.isNaN(newest)) return false;
if (newest > nowMs) return false;
return nowMs - newest <= windowMs;
}
/**
* Owner group key: explicit `owned_by` first, then the id prefix before
* `/`, else `"unknown"`. Shared by the showcase ranking and the fresh cap
* so both count the same groups.
*/
export function ownerKeyOf(entry: OmniRouteRawModelEntry): string {
if (typeof entry.owned_by === "string" && entry.owned_by.length > 0) return entry.owned_by;
if (typeof entry.id === "string" && entry.id.includes("/"))
return entry.id.slice(0, entry.id.indexOf("/"));
return "unknown";
}
/**
* Recency order shared by the showcase ranking and the fresh cap: newest
* `release_date` first (unknown = oldest), then largest `context_length`.
*/
export function compareByRecency(a: OmniRouteRawModelEntry, b: OmniRouteRawModelEntry): number {
const aDate = typeof a.release_date === "string" ? Date.parse(a.release_date) : NaN;
const bDate = typeof b.release_date === "string" ? Date.parse(b.release_date) : NaN;
const aMs = Number.isNaN(aDate) ? 0 : aDate;
const bMs = Number.isNaN(bDate) ? 0 : bDate;
if (aMs !== bMs) return bMs - aMs;
const aCtx = typeof a.context_length === "number" ? a.context_length : 0;
const bCtx = typeof b.context_length === "number" ? b.context_length : 0;
return bCtx - aCtx;
}
/**
* Read the lifecycle hint the raw gateway row carries, if any. The typed
* entry has no `status` field, so this stays a defensive local read: only
* the exact `"deprecated"` string excludes, anything else (absent,
* mistyped, other value) keeps the entry.
*/
export function readEntryStatus(entry: OmniRouteRawModelEntry): unknown {
return (entry as { status?: unknown }).status;
}
/**
* Flat effort-variant ids the gateway publishes next to their base model
* (e.g. `owner/model-high` beside `owner/model`). Only these seven
* suffixes exclude; any other ending (provider literals) leaves the id
* alone. Returns the base id, or undefined when there is no such suffix.
*/
const FLAT_TIER_SUFFIXES = new Set(["high", "low", "max", "medium", "xhigh", "minimal", "none"]);
export function baseIdOf(id: string): string | undefined {
const slash = id.lastIndexOf("/");
const short = slash >= 0 ? id.slice(slash + 1) : id;
const dash = short.lastIndexOf("-");
if (dash <= 0) return undefined;
const suffix = short.slice(dash + 1).toLowerCase();
if (!FLAT_TIER_SUFFIXES.has(suffix)) return undefined;
const base = short.slice(0, dash);
if (base.length === 0) return undefined;
return slash >= 0 ? id.slice(0, slash + 1) + base : base;
}
/** True when the id is a flat effort-variant id (see `baseIdOf`). */
export function isFlatTierId(id: string): boolean {
return baseIdOf(id) !== undefined;
}
/**
* Pick the showcase ids: per `owned_by` group (prefix before `/`, else
* `"unknown"`), newest `release_date` first (unknown = oldest), then
* largest `context_length`. Providers surface at runtime; nothing is
* hardcoded here.
*/
export function selectShowcaseIds(
entries: readonly OmniRouteRawModelEntry[],
perOwner: number = SHOWCASE_PER_OWNER
): Set<string> {
const groups = new Map<string, OmniRouteRawModelEntry[]>();
for (const entry of entries) {
if (!entry || typeof entry.id !== "string" || entry.id.length === 0) continue;
const owner = ownerKeyOf(entry);
const list = groups.get(owner);
if (list) list.push(entry);
else groups.set(owner, [entry]);
}
const out = new Set<string>();
// A non-finite or non-positive size cannot come through parsed options
// (the schema rejects it), only through direct calls: fall back instead
// of publishing an unbounded group (Infinity) or an empty one (0).
const perOwnerCount = Number.isFinite(perOwner) && perOwner > 0 ? perOwner : SHOWCASE_PER_OWNER;
for (const list of groups.values()) {
const ranked = [...list].sort(compareByRecency);
for (const entry of ranked.slice(0, perOwnerCount)) out.add(entry.id);
}
return out;
}
/**
* Static pass: allowlisted (exact id or short suffix) first, then the
* default view — retired entries and flat effort-variant ids stay out,
* recent entries only up to the per-owner fresh cap, showcased ids pass.
* A pin always wins over every exclusion below.
*/
export function passesWhatServes(
entry: OmniRouteRawModelEntry,
showcased: ReadonlySet<string>,
visibleFilter: ModelListFilter | undefined,
nowMs: number = Date.now(),
freshKept?: ReadonlySet<string>,
windowMs: number = FRESHNESS_WINDOW_MS
): boolean {
if (visibleFilter !== undefined) {
if (matchesModelFilter(entry.id, visibleFilter)) return true;
}
// The raw gateway row may carry a lifecycle hint the typed entry does
// not declare (it already flows through the fetcher untouched).
if (readEntryStatus(entry) === "deprecated") return false;
if (isFlatTierId(entry.id)) return false;
if (isFreshModel(entry, nowMs, windowMs)) {
if (freshKept !== undefined) return freshKept.has(entry.id);
return true;
}
if (showcased.has(entry.id)) return true;
return false;
}
/**
* Rank recent entries per owner (same group key and order as the
* showcase) and keep up to `perOwner` ids per group. Only
* `isFreshModel`-true entries compete; pinned, retired and flat
* effort-variant ids never take a fresh slot.
*/
export function selectFreshKeptIds(
entries: readonly OmniRouteRawModelEntry[],
perOwner: number = FRESH_PER_OWNER,
nowMs: number = Date.now(),
visibleFilter?: ModelListFilter,
windowMs: number = FRESHNESS_WINDOW_MS
): Set<string> {
const perOwnerCount = Number.isFinite(perOwner) && perOwner > 0 ? perOwner : FRESH_PER_OWNER;
const groups = new Map<string, OmniRouteRawModelEntry[]>();
for (const entry of entries) {
if (!entry || typeof entry.id !== "string" || entry.id.length === 0) continue;
if (readEntryStatus(entry) === "deprecated") continue;
if (isFlatTierId(entry.id)) continue;
if (visibleFilter !== undefined) {
if (matchesModelFilter(entry.id, visibleFilter)) continue;
}
if (!isFreshModel(entry, nowMs, windowMs)) continue;
const owner = ownerKeyOf(entry);
const list = groups.get(owner);
if (list) list.push(entry);
else groups.set(owner, [entry]);
}
const out = new Set<string>();
for (const list of groups.values()) {
const ranked = [...list].sort(compareByRecency);
for (const entry of ranked.slice(0, perOwnerCount)) out.add(entry.id);
}
return out;
}
/**
* Whether a statically dropped entry stays dropped under the usage
* memory: retired entries, flat effort-variant ids and entries past the
* per-owner fresh cap are never restored. Pinned ids never reach this
* filter (they pass the static gate already).
*/
export function staysDropped(
entry: OmniRouteRawModelEntry,
freshKept: ReadonlySet<string>,
nowMs: number = Date.now(),
windowMs: number = FRESHNESS_WINDOW_MS
): boolean {
if (readEntryStatus(entry) === "deprecated") return true;
if (isFlatTierId(entry.id)) return true;
if (isFreshModel(entry, nowMs, windowMs) && !freshKept.has(entry.id)) return true;
return false;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,56 +0,0 @@
import { presetsActive } from "./capability-presets.js";
import type { OmniRouteRawModelEntry } from "./shared/models-map.js";
/**
* Where published combos come from.
*
* - `"api"` (default): `/api/combos`, folded over the member list, so a combo
* publishes only when every member passes the active filters (#16779).
* - `"models"` (opt-in): the combo rows `/v1/models` already serves with
* server-computed limits, without the extra `/api/combos` request.
*/
export type CombosSource = "api" | "models";
export interface CombosSourceOptions {
combosSource?: CombosSource;
visibleModels?: string[];
hiddenModels?: string[];
providersAllow?: string[];
usableOnly?: boolean;
freeOnly?: boolean;
toolsOnly?: boolean;
visionOnly?: boolean;
}
function narrows(list: string[] | undefined): boolean {
return Array.isArray(list) && list.some((id) => typeof id === "string" && id.length > 0);
}
/**
* True when this refresh may skip `/api/combos` and take combos from the
* `/v1/models` rows. Only when the option asks for it AND no filter needs the
* member list: a `/v1/models` combo row carries no members, so the capability
* presets, `usableOnly`, the provider allowlist and the visible/hidden lists
* (which all judge a combo by its members) keep the member-verified source.
* Any doubt resolves to the default source.
*/
export function usesModelsComboSource(opts: CombosSourceOptions): boolean {
if (opts.combosSource !== "models") return false;
if (presetsActive(opts)) return false;
if (opts.usableOnly === true) return false;
if (narrows(opts.providersAllow)) return false;
if (narrows(opts.hiddenModels)) return false;
if (narrows(opts.visibleModels) && opts.visibleModels?.includes("*") !== true) return false;
return true;
}
/**
* A user combo row as `/v1/models` serves it: `owned_by: "combo"`, excluding
* the built-in `auto` / `auto/*` virtual combos (never published by the
* `/api/combos` pass either, and the gateway never lets a user combo shadow
* one of those ids).
*/
export function isUserComboRow(entry: OmniRouteRawModelEntry): boolean {
if (entry.owned_by !== "combo") return false;
return entry.id !== "auto" && !entry.id.startsWith("auto/");
}

View File

@@ -1,28 +0,0 @@
/**
* The stable contract has no `ctx.catalog`: providers publish through
* `ctx.provider.transform` (`editor.add` with `info` + `models`) and narrow
* through `ctx.model.transform`. This guard therefore requires the provider
* and model transforms plus an options object, and nothing else.
*/
export function assertContext(ctx: unknown): void {
if (!isObject(ctx)) {
throw new Error("[omniroute-v2] contract breach: ctx must be an object");
}
if (!isTransformHolder(ctx.provider) || typeof ctx.provider.transform !== "function") {
throw new Error("[omniroute-v2] contract breach: ctx.provider.transform must be a function");
}
if (!isTransformHolder(ctx.model) || typeof ctx.model.transform !== "function") {
throw new Error("[omniroute-v2] contract breach: ctx.model.transform must be a function");
}
if (!isObject(ctx.options)) {
throw new Error("[omniroute-v2] contract breach: ctx.options must be an object");
}
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isTransformHolder(value: unknown): value is { transform: unknown } {
return isObject(value) && "transform" in value;
}

View File

@@ -1,122 +0,0 @@
import type { Logger } from "./shared/index.js";
/** Minimal stable context surface this module reads (provider transforms stay untyped here). */
export interface StableCredentialContext {
integration: {
connection?: {
active?: (integrationID: string) => Promise<unknown>;
resolve?: (connection: unknown) => Promise<unknown>;
};
};
}
type StableContext = StableCredentialContext;
/** Where a resolved key came from, so the failure message can name the fix. */
export type ApiKeyOrigin = "connection" | "option" | "env" | "missing";
export interface ResolvedApiKey {
key: string;
origin: ApiKeyOrigin;
}
const ENV_VAR = "OMNIROUTE_API_KEY";
/**
* `ctx.integration.connection` carries the stored credential. Probing the
* shape keeps the plugin loadable on a host that exposes `integration`
* without it.
*/
function connectionApi(
ctx: StableContext
): { active: (id: string) => Promise<unknown>; resolve: (c: unknown) => Promise<unknown> } | undefined {
const connection = (ctx.integration as unknown as Record<string, unknown>).connection as
| { active?: unknown; resolve?: unknown }
| undefined;
if (
connection === undefined ||
typeof connection.active !== "function" ||
typeof connection.resolve !== "function"
) {
return undefined;
}
return connection as {
active: (id: string) => Promise<unknown>;
resolve: (c: unknown) => Promise<unknown>;
};
}
/**
* Read the credential the user stored through the host's own auth flow.
*
* The plugin advertises `key` and `env` methods on its integration, so a user
* can connect it from the UI; without this lookup that connection would only
* feed inference and the catalog fetches would still need a key pasted into
* the config file.
*
* Returns `undefined` (never throws) when there is no connection or when the
* stored credential is an OAuth grant — this plugin authenticates the gateway
* with a bearer key, and an access token from an unrelated grant is not one.
*/
async function keyFromConnection(
ctx: unknown,
integrationID: string,
log: Logger
): Promise<string | undefined> {
const connection = connectionApi(ctx as StableCredentialContext);
if (connection === undefined) return undefined;
try {
const active = await connection.active(integrationID);
if (active === undefined) return undefined;
const credential = (await connection.resolve(active)) as
| { type?: unknown; key?: unknown }
| undefined;
if (credential === undefined) return undefined;
if (credential.type !== "key") {
log.warn(
`[omniroute-v2] ignoring the stored ${String(credential.type)} credential: this plugin authenticates with an API key`
);
return undefined;
}
return typeof credential.key === "string" && credential.key.length > 0
? credential.key
: undefined;
} catch (err) {
log.warn(
`[omniroute-v2] could not read the stored credential: ${err instanceof Error ? err.message : String(err)}`
);
return undefined;
}
}
/**
* Resolve the gateway key, preferring the credential the host holds over one
* written in config. A key in `opencode.json` still wins over the environment
* so an explicit per-project override keeps working.
*/
export async function resolveApiKey(
ctx: unknown,
integrationID: string,
optionKey: string | undefined,
log: Logger
): Promise<ResolvedApiKey> {
const stored = await keyFromConnection(ctx, integrationID, log);
if (stored !== undefined) return { key: stored, origin: "connection" };
if (optionKey !== undefined && optionKey.length > 0) return { key: optionKey, origin: "option" };
const fromEnv = process.env[ENV_VAR];
if (fromEnv !== undefined && fromEnv.length > 0) return { key: fromEnv, origin: "env" };
return { key: "", origin: "missing" };
}
/**
* A missing key produces an empty catalog and no error the user can see, so
* say it once, and name the three ways to supply one.
*/
export function warnIfMissing(resolved: ResolvedApiKey, integrationID: string, log: Logger): void {
if (resolved.origin !== "missing") return;
log.warn(
`[omniroute-v2] no API key for "${integrationID}": the catalog will be empty. ` +
`Connect the integration from opencode, set "apiKey" in the plugin options, ` +
`or export ${ENV_VAR}.`
);
}

View File

@@ -1,41 +0,0 @@
import type { Logger } from "./shared/index.js";
/** What the catalog loses when a given gateway source cannot be read. */
function consequenceOf(endpoint: string): string {
if (endpoint.includes("/api/providers")) {
return "the usable-provider filter is disabled for this refresh, so unprovisioned providers stay listed";
}
return "model names, provider tags, canonical dedupe and pricing are degraded";
}
/**
* A source the gateway refuses is not fatal — the catalog still publishes —
* but staying quiet about it is: the picker then shows raw ids, or lists
* providers that cannot serve, with nothing telling the user why. Say it once
* per endpoint so a refresh loop cannot spam the log.
*
* `usingFallbackToken` is true when no `managementReadToken` was configured and
* the inference key stands in for it, which is the usual reason a gateway
* answers 401/403 on `/api/*` — the advice differs from a token that was set
* and still got rejected.
*/
export function createSourceErrorReporter(
log: Logger,
usingFallbackToken: boolean
): (endpoint: string, reason: string) => void {
const warned = new Set<string>();
return (endpoint, reason) => {
if (warned.has(endpoint)) return;
warned.add(endpoint);
const unauthorized = reason.includes("401") || reason.includes("403");
const hint = !unauthorized
? ""
: usingFallbackToken
? ` These endpoints need a management token: set "managementReadToken" in the plugin options ` +
`(it currently falls back to "apiKey", which a gateway usually rejects here).`
: ` The configured "managementReadToken" was rejected — check it grants read access to /api/*.`;
log.warn(
`[omniroute-v2] gateway source ${endpoint} unavailable (${reason}): ${consequenceOf(endpoint)}.${hint}`
);
};
}

View File

@@ -1,43 +0,0 @@
import type { LanguageModelV3 } from "@ai-sdk/provider";
import { type Logger, isGeminiModelId, sanitizeToolInputSchemas } from "./shared/index.js";
type CallOptions = Parameters<LanguageModelV3["doGenerate"]>[0];
/**
* Gemini answers `400 INVALID_ARGUMENT` — for the entire request, not just the
* offending tool — when a tool declaration carries `$schema` or
* `additionalProperties`. Anything upstream that emits standard JSON Schema
* therefore breaks tool calling as soon as the chain routes to Gemini. A
* `$ref` is forwarded untouched instead: stripping it would widen the schema
* to "accept anything", which is worse than letting the gateway answer. The
* v1 plugin dealt with this by wrapping `fetch` and rewriting the JSON body; the
* v2 home for it is the language model, where the tools are still structured
* data and no re-parsing is needed.
*
* Returns the model untouched when it is not bound for Gemini, so the wrapper
* costs nothing on every other chain.
*/
export function sanitizeToolSchemasFor<T extends LanguageModelV3 | undefined>(
language: T,
modelId: string,
log: Logger
): T {
if (language === undefined) return language;
if (!isGeminiModelId(modelId)) return language;
const clean = (options: CallOptions): CallOptions => {
const tools = sanitizeToolInputSchemas(options.tools);
if (tools === undefined) return options;
log.debug(
`[omniroute-v2] stripped Gemini-incompatible schema keywords from ${tools.length} tool declaration(s) for ${modelId}`
);
return { ...options, tools } as CallOptions;
};
// Prototype-linked so every other member of the model — including accessors
// and anything a future SDK version adds — keeps working untouched.
const wrapped: LanguageModelV3 = Object.create(language as object) as LanguageModelV3;
wrapped.doGenerate = (options) => language.doGenerate(clean(options));
wrapped.doStream = (options) => language.doStream(clean(options));
return wrapped as T;
}

View File

@@ -1,692 +0,0 @@
import { Plugin } from "@opencode/plugin";
import {
optionalTierFingerprint,
catalogContentFingerprint,
createLogger,
setHostSink,
defaultOmniRouteCombosFetcher,
defaultOmniRouteEnrichmentFetcher,
defaultOmniRouteModelsFetcher,
defaultOmniRouteProvidersFetcher,
type LogLevel,
type OmniRouteEnrichmentMap,
type OmniRouteProviderConnection,
} from "./shared/index.js";
import type { OmniRouteRawCombo, OmniRouteRawModelEntry } from "./shared/index.js";
import { buildProviderPayload, collectCatalog } from "./catalog.js";
import { usesModelsComboSource } from "./combos-source.js";
import {
UNREACHABLE_COOLDOWN_MS,
MIN_REFRESH_INTERVAL_MS,
memoryCacheKey,
readDiskSnapshot,
snapshotIdentityFingerprint,
writeDiskSnapshot,
type CatalogSnapshot,
} from "./cache.js";
import { startRefreshLoop } from "./refresh-loop.js";
import { assertContext } from "./compat.js";
import { type ApiKeyOrigin, resolveApiKey, warnIfMissing } from "./credentials.js";
import { createSourceErrorReporter } from "./enrichment-report.js";
import { sanitizeToolSchemasFor } from "./gemini-language.js";
import {
MANAGEMENT_TOKEN_ENV_VAR,
PLUGIN_ID,
parsePluginOptions,
resolveTimeouts,
toResolvedOptions,
} from "./options.js";
/**
* A fetch result that says whether it succeeded. Returning a bare `[]` on
* failure makes an outage indistinguishable from a gateway that legitimately
* has no combos — and the difference decides whether the last known value
* should be kept or dropped.
*/
type SourceResult<T> = { ok: true; value: T } | { ok: false };
/** Warn-once guard for the usage-memory startup notice (one warn per process). */
let warnedMemoryNoToken = false;
interface RefreshState {
entries: Map<string, CatalogSnapshot>;
inFlight: Map<string, Promise<CatalogSnapshot>>;
fingerprint: string | undefined;
/** Digest of the optional tier, so a reload only follows a real change. */
optionalFingerprint: string | undefined;
/**
* When the last refresh found the gateway unreachable, skip the network
* until this timestamp and serve last-known-good instead. Without it every
* transform past TTL re-fires the full fetch suite against a gateway that
* just proved it cannot answer — a self-inflicted retry storm.
*/
unreachableUntil: number;
}
export { toResolvedOptions } from "./options.js";
export default Plugin.define({
id: PLUGIN_ID,
setup: async (ctx) => {
assertContext(ctx);
const parsed = parsePluginOptions(ctx.options);
const X = parsed.providerId;
const resolved = toResolvedOptions(parsed);
const timeouts = resolveTimeouts(parsed);
const log = createLogger(parsed.startupDebug ? "debug" : (parsed.logLevel ?? "warn"));
resolved.logger = log;
resolved.logLevel = parsed.logLevel;
resolved.startupDebug = parsed.startupDebug;
// Forward plugin lines to the host log when the host exposes one, so a
// service install (stdout lost) still records warnings. Defensive at
// every level: without it the console output above stays the only copy.
try {
const maybeClient = (ctx as { client?: unknown }).client as
{ app?: { log?: unknown } } | undefined;
const appLog = maybeClient?.app?.log;
if (typeof appLog === "function") {
const hostLog = appLog as (input: {
body: { service: string; level: LogLevel; message: string };
}) => unknown;
setHostSink((level, message) => {
const out = hostLog({
body: { service: "[omniroute-plugin]", level, message },
});
return out;
});
}
} catch (err) {
// The probe itself threw (a throwing getter on the host object):
// trace it on the console so a missed host log is never silent.
console.warn(
`[omniroute-plugin] [WARN] host log probe failed, keeping console output: ${err instanceof Error ? err.message : String(err)}`
);
}
log.info(`[omniroute-v2] init providerId=${X}`);
// The inference key stands in below when no management token is set, and
// gateways usually reject that stand-in with 401/403. Say so once here,
// before any fetch, instead of letting the refusal surface per endpoint.
if (resolved.managementReadToken === undefined) {
log.warn(
`[omniroute-v2] no management token configured: management endpoints (/api/*) will reuse the inference key, ` +
`which gateways usually reject with 401/403. Set "managementReadToken" in the plugin options ` +
`or export ${MANAGEMENT_TOKEN_ENV_VAR}.`
);
}
if (
resolved.usageMemory !== false &&
resolved.managementReadToken === undefined &&
!warnedMemoryNoToken
) {
warnedMemoryNoToken = true;
log.warn(
"[omniroute-v2] usage history inactive without management token: statically dropped models stay unpublished."
);
}
// v1 parity port: in-memory TTL + disk snapshot. The memory key
// `baseURL::sha256(creds)` isolates credential tuples (prod vs
// staging); the TTL is checked in the transform before any fetch;
// concurrent calls share the refresh promise in the setup closure keyed
// by (providerId, baseURL); the disk snapshot feeds warm-startup and
// the offline fallback. The existing in-memory keep-last-good is kept.
const state: RefreshState = {
entries: new Map(),
inFlight: new Map(),
fingerprint: undefined,
optionalFingerprint: undefined,
unreachableUntil: 0,
};
// Per-installation stopped flag for the background refresh loop. Declared
// up front so the closures below can reference it without a temporal
// dead zone, and so a tick that lands after teardown publishes nothing.
let stopped = false;
// The credential the host holds wins over one written in config, so a
// user who connected the integration from the UI never has to paste a
// key into `opencode.json`. Reading it is async and the transforms must
// register synchronously, so the lookup happens on the first publish;
// until then the option/env key resolved above stands in.
const credentialsOf = (): { cacheKey: string; identityFingerprint: string } => ({
cacheKey: memoryCacheKey(
resolved.baseURL,
`${resolved.apiKey}\0${resolved.managementReadToken ?? resolved.apiKey}`
),
identityFingerprint: snapshotIdentityFingerprint(
resolved.baseURL,
resolved.apiKey,
resolved.managementReadToken ?? resolved.apiKey
),
});
let { cacheKey, identityFingerprint } = credentialsOf();
// Both keys are derived from the credential: two credentials must never
// share a snapshot, so they are recomputed whenever the key moves.
let credentialChecked = false;
let apiKeyOrigin: ApiKeyOrigin = resolved.apiKey.length > 0 ? "option" : "missing";
const ensureCredential = async (): Promise<void> => {
// Settled once a key is in hand: re-reading on every refresh would let
// a mid-session change silently repoint the snapshot keys.
if (credentialChecked && apiKeyOrigin !== "missing") return;
const next = await resolveApiKey(ctx, X, parsed.apiKey, log);
const moved = next.key !== resolved.apiKey;
const previousCacheKey = cacheKey;
resolved.apiKey = next.key;
apiKeyOrigin = next.origin;
if (moved) {
({ cacheKey, identityFingerprint } = credentialsOf());
// Drop the stale entry so the memory cache does not grow across a
// credential change.
state.entries.delete(previousCacheKey);
state.inFlight.delete(previousCacheKey);
}
if (!credentialChecked) warnIfMissing(next, X, log);
else if (moved) log.info(`[omniroute-v2] API key picked up from the ${next.origin} source`);
credentialChecked = true;
};
const fetchModelsSafe = async (): Promise<OmniRouteRawModelEntry[]> => {
try {
return await defaultOmniRouteModelsFetcher(
resolved.baseURL,
resolved.apiKey,
timeouts.models
);
} catch (err) {
log.warn(
`[omniroute-v2] models fetch failed, publishing empty catalog: ${err instanceof Error ? err.message : String(err)}`
);
return [];
}
};
// Failures are reported once per endpoint (with the management-token hint
// when the inference key stands in), so a gated `/api/*` degrades loudly
// rather than silently. Declared before the wrappers that use it.
const reportSourceError = createSourceErrorReporter(
log,
resolved.managementReadToken === undefined
);
const fetchCombosSafe = async (): Promise<SourceResult<OmniRouteRawCombo[]>> => {
if (resolved.combos === false) return { ok: true, value: [] };
// Opt-in models source: the combo rows already arrive in /v1/models,
// so /api/combos is not requested at all (default "api" keeps it).
if (usesModelsComboSource(resolved)) return { ok: true, value: [] };
try {
return {
ok: true,
value: await defaultOmniRouteCombosFetcher(
resolved.baseURL,
resolved.managementReadToken ?? resolved.apiKey,
timeouts.combos
),
};
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
reportSourceError("/api/combos", reason);
log.warn(`[omniroute-v2] combos fetch failed, keeping the last known combos: ${reason}`);
return { ok: false };
}
};
// Providers connections follow the same rule: gated on usableOnly (no
// request when false, v1 parity), soft-fail to [] so the filter degrades
// to keep-all instead of hiding the catalog.
const fetchProvidersSafe = async (): Promise<SourceResult<OmniRouteProviderConnection[]>> => {
if (!resolved.usableOnly) return { ok: true, value: [] };
try {
return {
ok: true,
value: await defaultOmniRouteProvidersFetcher(
resolved.baseURL,
resolved.managementReadToken ?? resolved.apiKey,
timeouts.models,
reportSourceError
),
};
} catch (err) {
log.warn(
`[omniroute-v2] providers fetch failed, keeping the last known provider list: ${err instanceof Error ? err.message : String(err)}`
);
return { ok: false };
}
};
// Enrichment follows the same rule: gated on the option (default on,
// v1 parity), soft-fail to an empty map so names/pricing degrade to
// mapper defaults instead of hiding the catalog.
const fetchEnrichmentSafe = async (): Promise<SourceResult<OmniRouteEnrichmentMap>> => {
if (resolved.enrichment === false) return { ok: true, value: new Map() };
try {
return {
ok: true,
value: await defaultOmniRouteEnrichmentFetcher(
resolved.baseURL,
resolved.managementReadToken ?? resolved.apiKey,
timeouts.enrichment,
reportSourceError
),
};
} catch (err) {
log.warn(
`[omniroute-v2] enrichment fetch failed, keeping the last known names/pricing: ${err instanceof Error ? err.message : String(err)}`
);
return { ok: false };
}
};
/**
* Fetch in two tiers. Models are what a catalog *is*: without them there
* is nothing to publish. Everything else — combos, the
* provider list, the enrichment overlay — improves an already usable
* catalog, so awaiting any of them before publishing makes the catalog
* hostage to the slowest source: a gateway that accepts the connection
* and never answers one endpoint kept everything unpublished until that
* fetch's own timeout fired, which is longer than some hosts stay alive.
*
* The optional tier therefore keeps running after the publish and upgrades
* the stored snapshot when it lands, so the next transform serves the
* complete catalog.
*/
async function refreshSnapshot(): Promise<CatalogSnapshot> {
// Models are what a catalog *is*; everything else improves one that
// already works. Combos used to sit here too, so a gateway slow to
// answer /api/combos held the whole picker back — the very thing the
// staged publish exists to prevent.
const essential = fetchModelsSafe();
const optional = Promise.all([
fetchCombosSafe(),
fetchProvidersSafe(),
fetchEnrichmentSafe(),
]);
const models = await essential;
const previous = state.entries.get(cacheKey);
// A gateway that just failed everything gets a short breather: serving
// last-known-good for a few seconds beats hammering it on every
// transform while it is down. Arms whenever the models fetch comes back
// empty — with or without a prior entry to serve — so a totally dead
// gateway stops getting hit every window. Partial degradation (models
// healthy, an optional tier failed) still retries normally next window.
if (models.length === 0) {
state.unreachableUntil = Date.now() + UNREACHABLE_COOLDOWN_MS;
}
// Carry every source forward until its replacement lands, and keep the
// old value when a fetch FAILED — but honour a gateway that legitimately
// returns nothing, which is a different answer from "I could not ask".
const snapshot: CatalogSnapshot = {
models,
combos: previous?.combos ?? [],
providers: previous?.providers ?? [],
enrichment: previous?.enrichment ?? new Map(),
fetchedAt: Date.now(),
};
if (!stopped && models.length > 0) {
state.entries.set(cacheKey, snapshot);
await writeDiskSnapshot(X, snapshot, identityFingerprint, log);
}
void optional.then(
(parts) => upgradeWithOptional(snapshot, parts),
(err) => {
// The wrappers never reject; a throw here would be a bug in them, and
// an unhandled rejection is a worse way to learn about it.
log.warn(
`[omniroute-v2] optional catalog sources failed unexpectedly: ${err instanceof Error ? err.message : String(err)}`
);
}
);
return snapshot;
}
/**
* Fold late optional data into the snapshot that was published without it.
* Skipped when a newer refresh has already replaced that snapshot, so a
* slow tier can never resurrect a stale catalog.
*/
async function upgradeWithOptional(
base: CatalogSnapshot,
[combos, providers, enrichment]: [
SourceResult<OmniRouteRawCombo[]>,
SourceResult<OmniRouteProviderConnection[]>,
SourceResult<OmniRouteEnrichmentMap>,
]
): Promise<void> {
if (stopped) return;
if (state.entries.get(cacheKey) !== base) return;
// Per source: a success replaces (even with an empty answer — that is
// the gateway's answer), a failure keeps what we had.
const upgraded: CatalogSnapshot = {
...base,
combos: combos.ok ? combos.value : base.combos,
providers: providers.ok ? providers.value : base.providers,
enrichment: enrichment.ok ? enrichment.value : base.enrichment,
};
const unchanged =
upgraded.combos === base.combos &&
upgraded.providers === base.providers &&
upgraded.enrichment === base.enrichment;
if (unchanged) return;
state.entries.set(cacheKey, upgraded);
if (upgraded.models.length > 0) {
await writeDiskSnapshot(X, upgraded, identityFingerprint, log);
}
// Reload only when the optional tier actually moved: the catalog
// fingerprint covers ids alone, so without this the host would rebuild
// its catalog once per TTL window for an identical result.
const optionalFingerprint = optionalTierFingerprint(
upgraded.providers ?? [],
upgraded.enrichment,
upgraded.combos
);
const optionalChanged = state.optionalFingerprint !== optionalFingerprint;
state.optionalFingerprint = optionalFingerprint;
if (optionalChanged && !stopped) {
try {
await ctx.provider.reload();
} catch (err) {
log.warn(
`[omniroute-v2] provider reload after late sources failed, keeping current catalog: ${err instanceof Error ? err.message : String(err)}`
);
}
}
}
function loadSnapshot(force = false): Promise<CatalogSnapshot> {
const now = Date.now();
const hit = state.entries.get(cacheKey);
if (!force && hit && hit.fetchedAt + resolved.modelCacheTtlMs > now)
return Promise.resolve(hit);
// Cooldown after a total models failure: skip the network until it
// lapses. Serves last-known-good when one exists; otherwise the refresh
// below still runs (nothing to serve, no point pretending).
if (now < state.unreachableUntil && hit) return Promise.resolve(hit);
if (now >= state.unreachableUntil) state.unreachableUntil = 0;
const inflight = state.inFlight.get(cacheKey);
if (inflight) return inflight;
const snapshot = refreshSnapshot();
state.inFlight.set(cacheKey, snapshot);
const clear = () => {
if (state.inFlight.get(cacheKey) === snapshot) state.inFlight.delete(cacheKey);
};
snapshot.then(clear, clear);
return snapshot;
}
// Warm-startup: the disk snapshot is read at boot (without blocking
// the synchronous transform registration) to publish the last-known
// catalog before the first successful fetch.
/**
* Warm start: publish the last known catalog from disk before the first
* fetch returns. Deliberately read *after* the credential is resolved —
* the snapshot is keyed by the credential tuple, and resolving the host
* credential changes that key, so reading at setup time would look up the
* wrong identity and reject a perfectly good snapshot.
*/
let warmLoadedFor: string | undefined;
const ensureWarmSnapshot = async (): Promise<void> => {
if (warmLoadedFor === identityFingerprint) return;
warmLoadedFor = identityFingerprint;
const warm = await readDiskSnapshot(X, identityFingerprint, log);
if (warm && !state.entries.has(cacheKey)) state.entries.set(cacheKey, warm);
};
// Fail-closed models (keep-last-good, validated): an empty models fetch
// (transient 500/timeout) must not wipe a known catalog. The latest
// non-empty entry (fresh fetch or warm disk snapshot) is replayed
// instead of publishing the empty set. `refreshSnapshot` never overwrites
// the memory entry on failure, so `entries` stays the last-known-good
// source — including cross-setup via the disk snapshot.
// Fail-open one level down, in the wrappers (never reject) and the
// `collectCatalog` catches — so no try/catch here.
//
// The stable host replays the registered transform to rebuild its
// registry, so the callback only reads the latest collected snapshot;
// the refresh below keeps that snapshot current and reloads the host.
// The transform callback is synchronous, so it cannot await the fetch:
// setup publishes first, then the host replays the callback (during
// registration and on every reload) and reads the published snapshot.
let latest: { info: unknown; models: unknown[] } | undefined;
const refreshAndPublish = async (options?: { force?: boolean }): Promise<void> => {
if (stopped) return;
await ensureCredential();
if (stopped) return;
await ensureWarmSnapshot();
const snapshot = await loadSnapshot(options?.force === true);
if (stopped) return;
let effective = snapshot;
if (snapshot.models.length === 0) {
const stale = state.entries.get(cacheKey);
if (stale !== undefined && stale.models.length > 0) {
log.warn(
`[omniroute-v2] models fetch returned empty, keeping last-known catalog (${stale.models.length} models, ${stale.combos.length} combos)`
);
effective = stale;
}
}
const counts = await (async (): Promise<{
models: number;
combos: number;
}> => {
// fetcher-level fail-open covers fetches; this guard covers mapper throws.
try {
const collected = await collectCatalog(resolved, {
onSourceError: reportSourceError,
models: async () => effective.models,
combos: async () => effective.combos,
providers: async () => effective.providers ?? [],
enrichment: async () => effective.enrichment ?? new Map(),
});
const payload = buildProviderPayload(collected, resolved);
latest = payload as unknown as { info: unknown; models: unknown[] };
return collected.counts;
} catch (err) {
log.warn(
`[omniroute-v2] catalog publish failed, keeping current catalog: ${err instanceof Error ? err.message : String(err)}`
);
return { models: 0, combos: 0 };
}
})();
void counts;
const fingerprint = catalogContentFingerprint(effective.models, effective.combos);
const changed = state.fingerprint !== undefined && state.fingerprint !== fingerprint;
state.fingerprint = fingerprint;
if (changed && !stopped) {
await Promise.resolve();
try {
await ctx.provider.reload();
} catch (err) {
log.warn(
`[omniroute-v2] provider reload failed, keeping current catalog: ${err instanceof Error ? err.message : String(err)}`
);
}
}
};
// Publish before returning so the first transform replay already has
// data; without a key this degrades to an empty provider, not a crash.
// A host throw in `editor.add` must not reject setup: the catalog is
// the job, and a failed publish keeps the previous one.
await refreshAndPublish();
const providerRegistration = ctx.provider.transform((editor) => {
if (latest !== undefined) {
try {
editor.add(latest as never);
} catch (err) {
log.warn(
`[omniroute-v2] catalog publish failed, keeping current catalog: ${err instanceof Error ? err.message : String(err)}`
);
}
}
});
const integrationHook = (ctx.integration as unknown as { transform?: unknown } | undefined)
?.transform;
// A host that exposes the hook but throws while registering it must cost
// the plugin nothing but the connect action: the throw happens OUTSIDE
// any await, so only a call-site guard catches it (an await-guard alone
// would let a synchronous throw escape setup and kill the catalog).
let integrationRegistration: unknown;
if (typeof integrationHook === "function") {
try {
integrationRegistration = (
integrationHook as (
cb: (draft: {
update: (id: string, fn: (i: { name: string }) => void) => void;
method: { update: (input: unknown) => void };
}) => void
) => unknown
)((draft) => {
draft.update(X, (integration) => {
integration.name = parsed.displayName ?? "OmniRoute";
});
draft.method.update({ integrationID: X, method: { type: "key", label: "API key" } });
draft.method.update({
integrationID: X,
method: { type: "env", names: ["OMNIROUTE_API_KEY"] },
});
});
} catch (err) {
log.warn(
`[omniroute-v2] host refused the integration hook, the connect action will be missing: ${err instanceof Error ? err.message : String(err)}`
);
integrationRegistration = undefined;
}
}
/**
* `aisdk.hook("language")` cleans Gemini tool schemas where the model is
* still structured data. A host without the domain stays loadable,
* minus the sanitising.
*/
const languageHook = (ctx.aisdk as unknown as { hook?: unknown } | undefined)?.hook;
// A host that rejects this registration must cost the catalog nothing: the
// plugin is a catalog first, and tool-schema cleaning is an extra.
let languageRegistration: Promise<{ dispose: () => Promise<void> }> | undefined;
if (parsed.geminiSanitization !== false && typeof languageHook === "function") {
try {
languageRegistration = (
languageHook as (
name: string,
cb: (input: { model: { providerID: string; id: string }; language?: unknown }) => void
) => Promise<{ dispose: () => Promise<void> }>
)("language", (input) => {
if (input.model.providerID !== X) return;
input.language = sanitizeToolSchemasFor(
input.language as never,
input.model.id,
log
) as unknown as undefined;
});
} catch (err) {
log.warn(
`[omniroute-v2] host refused the language-model hook, Gemini tool schemas will not be cleaned: ${err instanceof Error ? err.message : String(err)}`
);
}
}
/**
* `aisdk.hook("sdk")` carries inference-telemetry options. It is the same
* entry point the `"language"` hook above goes through, so a host that
* exposes no `aisdk` domain — or refuses this particular name — must still
* load the catalog. Strict fallback (no proven options-only marking):
* register the hook and record the observation in `options` only — never
* wrap fetch, never assign `sdk`. Gated on the opt-in `telemetry` flag
* (off by default).
*/
const sdkHook = (ctx.aisdk as unknown as { hook?: unknown } | undefined)?.hook;
let sdkRegistration: Promise<{ dispose: () => Promise<void> }> | undefined;
if (parsed.telemetry === true && typeof sdkHook === "function") {
try {
sdkRegistration = (
sdkHook as (
name: string,
cb: (input: {
model: { providerID: string; id: string };
package: string;
options: Record<string, unknown>;
}) => void
) => Promise<{ dispose: () => Promise<void> }>
)("sdk", (input) => {
if (input.model.providerID !== X) return;
if (!input.package.includes("@ai-sdk/openai-compatible")) return;
input.options.telemetry = true;
});
} catch (err) {
log.warn(
`[omniroute-v2] host refused the sdk hook, inference telemetry will not be marked: ${err instanceof Error ? err.message : String(err)}`
);
}
}
await providerRegistration;
if (integrationRegistration !== undefined) {
try {
await integrationRegistration;
} catch (err) {
log.warn(
`[omniroute-v2] host refused the integration hook, the connect action will be missing: ${err instanceof Error ? err.message : String(err)}`
);
}
}
if (languageRegistration !== undefined) {
try {
await languageRegistration;
} catch (err) {
log.warn(
`[omniroute-v2] language-model hook registration failed, Gemini tool schemas will not be cleaned: ${err instanceof Error ? err.message : String(err)}`
);
}
}
if (sdkRegistration !== undefined) {
try {
await sdkRegistration;
} catch (err) {
log.warn(
`[omniroute-v2] sdk hook registration failed, inference telemetry will not be marked: ${err instanceof Error ? err.message : String(err)}`
);
}
}
// Background refresh loop: keep the served catalog aligned with the
// gateway. The first publish above already populated `latest`; the loop
// only re-runs refreshAndPublish on the configured TTL.
// Registry of live loops, keyed by providerId, scoped to globalThis so it
// survives module re-evaluation (the host loads the plugin up to ~20
// times per process). Defense in depth behind the Cleanup returned below.
const registryKey = Symbol.for("omniroute.opencode-plugin-v2.refresh-loops");
const g = globalThis as unknown as Record<
symbol,
Map<string, { stop: () => void; state: RefreshState }>
>;
if (!g[registryKey]) g[registryKey] = new Map();
const registry = g[registryKey];
// Stop any loop already registered for this providerId.
const existing = registry.get(X);
if (existing) {
try {
existing.stop();
} catch {
// ignore
}
registry.delete(X);
}
const stopLoop = startRefreshLoop({
intervalMs: Math.max(MIN_REFRESH_INTERVAL_MS, resolved.modelCacheTtlMs),
refresh: () => refreshAndPublish({ force: true }),
logger: log,
});
// Cleanup returned to the host: flag the installation as stopped (a tick
// already in flight then publishes nothing), clear the timer and drop the
// registry entry. The entry carries `state` only so tests can inspect the
// memory cache.
const stop = () => {
stopped = true;
try {
stopLoop();
} catch {
// ignore
}
registry.delete(X);
};
registry.set(X, { stop, state });
return stop;
},
});

View File

@@ -1,81 +0,0 @@
/**
* Vendored legacy catalog shape (beta `Model`), kept dependency-free.
*
* The shared mappers (`models-map`, `combos-map`, `enrich`)
* speak the rich legacy catalog shape (`auto-combos` retired): nested boolean capabilities, a
* single-object cost block, `options`/`headers` escape hatches, a string
* `release_date`, and variants as a record. It was previously imported from
* `@opencode-ai/sdk/v2`; vendoring it removes the beta SDK dependency while
* keeping the mapper layer untouched. The stable-contract boundary lives in
* `catalog.ts` (`legacyToStable`), which projects this shape onto the
* `Model.Info`/`Provider.Info` types from `@opencode/plugin`.
*/
export interface LegacyModelCapabilities {
temperature: boolean;
reasoning: boolean;
attachment: boolean;
toolcall: boolean;
input: {
text: boolean;
audio: boolean;
image: boolean;
video: boolean;
pdf: boolean;
};
output: {
text: boolean;
audio: boolean;
image: boolean;
video: boolean;
pdf: boolean;
};
interleaved:
| boolean
| {
field: "reasoning" | "reasoning_content" | "reasoning_text" | string;
};
}
export interface LegacyModelCost {
input: number;
output: number;
cache: {
read: number;
write: number;
};
}
export interface LegacyModel {
id: string;
providerID: string;
api: {
id: string;
url: string;
npm: string;
};
name: string;
family?: string;
capabilities: LegacyModelCapabilities;
cost: LegacyModelCost;
limit: {
context: number;
input?: number;
output: number;
};
status: "alpha" | "beta" | "deprecated" | "active";
options: {
[key: string]: unknown;
};
headers: {
[key: string]: string;
};
release_date: string;
variants?: {
[key: string]: {
[key: string]: unknown;
};
};
}
/** Namespace alias so existing `Model as X` imports keep working. */
export type Model = LegacyModel;

View File

@@ -1,68 +0,0 @@
export interface ModelListFilter {
/** Exact ids (contain a slash): they match one row. */
exact: Set<string>;
/** Suffixes (no slash): they match the part after the first "/". */
suffixes: Set<string>;
/** Claimed branches (from "prefix/*" entries): they match the first segment. */
branches: Set<string>;
}
/** Branch of an id: the segment before the first "/". Single source of the rule. */
export function branchOf(id: string): string | undefined {
if (typeof id !== "string") return undefined;
const slash = id.indexOf("/");
if (slash <= 0) return undefined;
const branch = id.slice(0, slash);
return branch.length > 0 ? branch : undefined;
}
/** Classify one entry against the "prefix/*" claim shape. Single source of the shape. */
export function parseBranchClaim(entry: string): { claimed: boolean; branch: string } {
if (typeof entry !== "string") return { claimed: false, branch: "" };
if (!entry.endsWith("/*")) return { claimed: false, branch: "" };
const name = entry.slice(0, -2);
if (name.length === 0 || name.includes("*")) return { claimed: false, branch: "" };
return { claimed: true, branch: name };
}
export function compileModelListFilter(list?: string[]): ModelListFilter | undefined {
if (!list || list.length === 0) return undefined;
const exact = new Set<string>();
const suffixes = new Set<string>();
const branches = new Set<string>();
for (const entry of list) {
if (typeof entry !== "string" || entry.length === 0) continue;
const claim = parseBranchClaim(entry);
if (claim.claimed) {
branches.add(claim.branch);
continue;
}
if (entry.includes("/")) {
exact.add(entry);
} else {
suffixes.add(entry);
}
}
if (exact.size === 0 && suffixes.size === 0 && branches.size === 0) return undefined;
return { exact, suffixes, branches };
}
export function matchesSuffix(id: string, suffixes: Set<string>): boolean {
if (suffixes.size === 0) return false;
const slash = id.indexOf("/");
const suffix = slash > 0 ? id.slice(slash + 1) : id;
return suffixes.has(suffix);
}
export function matchesBranch(id: string, branches: Set<string>): boolean {
if (branches.size === 0) return false;
const branch = branchOf(id);
if (branch === undefined) return false;
return branches.has(branch);
}
export function matchesModelFilter(id: string, filter: ModelListFilter): boolean {
return (
filter.exact.has(id) || matchesSuffix(id, filter.suffixes) || matchesBranch(id, filter.branches)
);
}

View File

@@ -1,209 +0,0 @@
import { z } from "zod";
import { DEFAULT_MODEL_CACHE_TTL_MS } from "./cache.js";
import type { ResolvedOptions } from "./catalog.js";
import { DEFAULT_FREE_SIGNALS, FREE_SIGNALS } from "./shared/free-signals.js";
import { isHttpUrl } from "./shared/models-map.js";
const apiFormatSchema = z
.object({
allowAnthropic: z.boolean().optional(),
anthropicModels: z.array(z.string()).optional(),
// Deprecated v1 prefix list. Accepted (warn at resolve time) so copied
// v1 configs keep routing; prefer anthropicModels (full IDs).
anthropicPrefixes: z.array(z.string()).optional(),
})
.strict();
const timeoutsSchema = z
.object({
models: z.number().positive().optional(),
combos: z.number().positive().optional(),
autoCombos: z.number().positive().optional(),
enrichment: z.number().positive().optional(),
})
.strict();
const pluginOptionsSchema = z
.object({
// Reaches a filesystem path (the on-disk catalog snapshot) and the
// catalog keys, so it is bounded here rather than escaped at each use.
providerId: z
.string()
.regex(/^[A-Za-z0-9._-]+$/, "providerId may only contain letters, digits, '.', '_' and '-'")
.refine((v) => v !== "." && v !== "..", "providerId cannot be a path segment")
.default("omniroute"),
baseURL: z
.string()
.trim()
.refine(isHttpUrl, "baseURL must be an http(s) URL, for example http://localhost:20128"),
apiKey: z.string().optional(),
displayName: z.string().optional(),
managementReadToken: z.string().optional(),
timeoutMs: z.number().positive().default(10000),
timeouts: timeoutsSchema.optional(),
logLevel: z.enum(["error", "warn", "info", "debug"]).optional(),
startupDebug: z.boolean().optional(),
modelCacheTtlMs: z.number().positive().optional(),
visibleModels: z.array(z.string()).optional(),
hiddenModels: z.array(z.string()).optional(),
providersAllow: z.array(z.string()).optional(),
usableOnly: z.boolean().default(false),
// Hide every combo when false: no /api/combos request and no combo
// rows from /v1/models; models are unchanged.
combos: z.boolean().default(true),
// Combo source: "api" (default) folds /api/combos over each combo's
// members, so a combo publishes only when every member passes the
// filters. "models" skips that request and publishes the combo rows
// /v1/models serves; any member-level filter keeps the "api" source.
combosSource: z.enum(["api", "models"]).default("api"),
freeOnly: z.boolean().default(false),
// Extra signals that admit a model under `freeOnly` besides the declared
// free-tier catalog. Opt-in: the default keeps the declared-only rule.
freeSignals: z.array(z.enum(FREE_SIGNALS)).default([...DEFAULT_FREE_SIGNALS]),
// Provider prefixes whose models count as free under the
// `provider-named` signal (prefixes ending in `-free` always do).
freeProviders: z.array(z.string()).optional(),
toolsOnly: z.boolean().default(false),
visionOnly: z.boolean().default(false),
// Per-provider showcase size: how many models each provider keeps in
// the default view. Absent means the catalog default below.
showcasePerOwner: z.number().positive().optional(),
freshPerOwner: z.number().positive().optional(),
// Freshness window in days: entries dated within it publish via the
// fresh branch. Absent means the catalog default below.
freshWindowDays: z.number().positive().optional(),
// Restore statically dropped entries named by 30-day usage analytics.
// On by default; needs a management token.
usageMemory: z.boolean().optional(),
// v1 parity: enrichment overlay on by default (names + pricing).
enrichment: z.boolean().default(true),
// v1 parity: strip the JSON-Schema keywords Gemini rejects from tool
// declarations bound for a Gemini model. On by default — leaving them in
// fails the whole request with 400 INVALID_ARGUMENT.
geminiSanitization: z.boolean().default(true),
// v1 parity: prefix a model's display name with the upstream provider it
// routes to, so the same model sold through two connections is
// distinguishable in the picker.
providerTag: z.boolean().default(true),
// Inference telemetry is off by default: the host must opt in before the
// plugin touches the sdk domain at all.
telemetry: z.boolean().default(false),
apiFormat: apiFormatSchema.optional(),
})
.strict();
export type PluginOptions = z.infer<typeof pluginOptionsSchema>;
/** Environment source for the management token (option wins over this). */
export const MANAGEMENT_TOKEN_ENV_VAR = "OMNIROUTE_MANAGEMENT_API_KEY";
/**
* Resolve the management token: a non-empty option wins, then a non-empty
* environment value, else absent. Empty counts as absent on both inputs, the
* same rule the inference key follows; no trimming, the token is opaque.
*/
export function resolveManagementReadToken(optionValue: string | undefined): string | undefined {
if (optionValue !== undefined && optionValue.length > 0) return optionValue;
const fromEnv = process.env[MANAGEMENT_TOKEN_ENV_VAR];
if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv;
return undefined;
}
/** Per-endpoint timeout defaults (v1 parity). `timeoutMs` is the global fallback. */
export const DEFAULT_TIMEOUT_MS = 10_000 as const;
export interface EndpointTimeouts {
models: number;
combos: number;
enrichment: number;
}
export function resolveTimeouts(
opts: Pick<PluginOptions, "timeoutMs" | "timeouts">
): EndpointTimeouts {
const fallback =
typeof opts.timeoutMs === "number" && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_TIMEOUT_MS;
return {
models: opts.timeouts?.models ?? fallback,
combos: opts.timeouts?.combos ?? fallback,
enrichment: opts.timeouts?.enrichment ?? fallback,
};
}
/**
* Parse the plugin block of `opencode.json`.
*
* A rejected option aborts the whole plugin, and the host reports that as a
* bare load failure with the validator's raw dump attached — which is how a
* single mistyped key turns into a wall of JSON and an empty model picker. The
* schema is strict on purpose (a silently ignored option is worse), so the
* least we owe the user is a first line naming what to fix.
*/
export function parsePluginOptions(raw: unknown): PluginOptions {
const result = pluginOptionsSchema.safeParse(raw);
if (result.success) return result.data;
const problems = result.error.issues.map((issue) => {
const at = issue.path.length > 0 ? issue.path.join(".") : "(root)";
const unknown = issue.code === "unrecognized_keys" ? issue.keys.join(", ") : undefined;
return unknown !== undefined ? `unknown option "${unknown}"` : `${at}: ${issue.message}`;
});
throw new Error(`[omniroute-v2] invalid plugin options — ${problems.join("; ")}`);
}
/**
* Map parsed options to the catalog's runtime shape. Lives here (not
* index.ts) so tests reach it without importing the plugin entrypoint, whose
* `@opencode/plugin` runtime import is a devDependency absent from the
* caller's tree — importing index.ts fails at module load there.
*/
export function toResolvedOptions(parsed: PluginOptions): ResolvedOptions {
return {
providerId: parsed.providerId,
baseURL: parsed.baseURL,
apiKey: parsed.apiKey ?? process.env.OMNIROUTE_API_KEY ?? "",
managementReadToken: resolveManagementReadToken(parsed.managementReadToken),
timeoutMs: parsed.timeoutMs,
timeouts: parsed.timeouts,
logLevel: parsed.logLevel,
startupDebug: parsed.startupDebug,
providerTag: parsed.providerTag,
modelCacheTtlMs:
typeof parsed.modelCacheTtlMs === "number" && parsed.modelCacheTtlMs > 0
? parsed.modelCacheTtlMs
: DEFAULT_MODEL_CACHE_TTL_MS,
displayName: parsed.displayName,
apiFormat: parsed.apiFormat,
visibleModels: parsed.visibleModels,
hiddenModels: parsed.hiddenModels,
providersAllow: parsed.providersAllow,
usableOnly: parsed.usableOnly,
combos: parsed.combos ?? true,
combosSource: parsed.combosSource,
freeOnly: parsed.freeOnly,
freeSignals: parsed.freeSignals,
freeProviders: parsed.freeProviders,
toolsOnly: parsed.toolsOnly,
visionOnly: parsed.visionOnly,
showcasePerOwner: parsed.showcasePerOwner,
freshPerOwner: parsed.freshPerOwner,
freshWindowDays: parsed.freshWindowDays,
usageMemory: parsed.usageMemory,
enrichment: parsed.enrichment,
};
}
/**
* The host reads the plugin id from the module, before any option is known, so
* it cannot carry the configured provider id. Publishing two gateways from one
* install is a `providerId` matter — that one does reach the catalog.
*/
export const PLUGIN_ID = "omniroute-v2";
export function providerIdFor(providerId: string): string {
return providerId;
}
export function integrationIdFor(providerId: string): string {
return providerId;
}

Some files were not shown because too many files have changed in this diff Show More