Compare commits

...

6 Commits

32 changed files with 157 additions and 4867 deletions

View File

@@ -53,8 +53,10 @@ reports/mutation
# Local caches and quality-gate artifacts (all gitignored). `_*` does not match
# dot-prefixed names, so these need explicit entries.
.artifacts
.eslintcache
.eslintcache-complexity
.eslintcache*
.fakebin-*
MAX
quality-ratchet/
# Documentation
# Issue #2348: The Dashboard Docs viewer reads markdown from `/app/docs` at

17
.gitignore vendored
View File

@@ -18,7 +18,7 @@ _tasks/
.logs/**
.tests/**
.coverage/**
coverage/
/coverage/
.dist/**
.next/**
.build/**
@@ -44,6 +44,7 @@ memory-bank/
# Root-level underscore-prefixed directories (private/draft — never commit)
/_*/
/_*
# Draft features documentation (internal only)
docs/new-features/
@@ -57,10 +58,6 @@ node_modules/
*.map
.DS_Store
# Obsidian sync plugin — committed for community distribution
!obsidian-plugin/
obsidian-plugin/node_modules/
# Serena AI assistant config (local-only tool, not project code)
.serena/
@@ -74,6 +71,7 @@ yarn-error.log*
.env*
!.env.example
!.env.homolog.example
!.env.devin-bridge.example
# Provider API keys (never commit)
*.api-key
.nvidia-api-key
@@ -86,7 +84,7 @@ yarn-error.log*
next-env.d.ts
# data and logs
data/
/data/
.data/
logs/*
test_output.log
@@ -108,7 +106,7 @@ open-sse/test/*
test-results/
playwright-report/
blob-report/
cloud/
/cloud/
.tmp/
# Security Analysis (standalone project with own git)
@@ -175,7 +173,6 @@ config/quality/test-impact-map.json
# GitNexus local index
.gitnexus
.worktrees
bin/omniroute.mjs
# Consistent with .dockerignore / .npmignore
.omc/
@@ -213,7 +210,7 @@ scripts/i18n/_pending-keys.json
# AI agent local settings and configs
.agents/
.antigravitycli/
.claude/
/.claude/
# PR Reviews and local feedback files
pr_reviews*.json
@@ -271,6 +268,8 @@ _artifacts/ # release-green artifacts
# 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

View File

@@ -94,6 +94,10 @@ vscode-extension/
/_*/
# Consistent with .gitignore and .dockerignore
.claude/
.fakebin-*
.eslintcache*
_tasks/
.DS_Store
.idea/
.config/

View File

@@ -247,7 +247,7 @@ Read the nearest `AGENTS.md` and the linked deep-dive before making a non-trivia
## File placement & repo-root hygiene
- **Test files**: ALL unit tests, integration tests, ecosystem tests, or Vitest files MUST strictly be placed within the `tests/` directory (e.g., `tests/unit/`, `tests/integration/`). NEVER create test files in the project root (`/`).
- **Scripts and utilities**: ALL maintenance, debugging, generation, or experimental scripts (`.cjs`, `.mjs`, `.js`, `.ts`) MUST be placed strictly inside one of the `scripts/` subfolders (`build/`, `dev/`, `check/`, `docs/`, `i18n/`, `ad-hoc/`). One-shot or experimental code goes under `scripts/ad-hoc/`. NEVER dump loose scripts in the project root (`/`) or the top-level `scripts/` folder.
- **Scripts and utilities**: ALL maintenance, debugging, generation, or experimental scripts (`.cjs`, `.mjs`, `.js`, `.ts`) MUST be placed strictly inside one of the `scripts/` subfolders (`build/`, `dev/`, `check/`, `docs/`, `i18n/`, `ad-hoc/`, `quality/`, `release/`, `ci/`, `ops/`, `perf/`, `research/`, `sre/`, `vps/`, `homolog/`, `raycast/`, `skills/`, `test/`, `cli/`, `compression/`, `compression-eval/`, `devin-bridge/`, `docker/`, `features/`, `router-eval/`). One-shot or experimental code goes under `scripts/ad-hoc/`. NEVER dump loose scripts in the project root (`/`) or the top-level `scripts/` folder.
**The project root MUST ONLY contain:**
@@ -258,6 +258,15 @@ Read the nearest `AGENTS.md` and the linked deep-dive before making a non-trivia
When creating _any_ validation tests or one-off logic scripts, default to `scripts/ad-hoc/` or `tests/unit/` according to your goals. Do not pollute the `/` root context.
- **Root `_*` paths are private and NEVER tracked** (`_tasks/`, `_references/`, `_mono_repo/`,
`_ideia/`, `_cache/` and any future `_<name>`): they live on disk only, are gitignored by the
anchored patterns `/_*/` + `/_*`, and some are full git repositories of their own (`_tasks`
private remote `_tasks_omniroute`). Never `git add` anything inside them (a plain `add` is
already blocked by the ignore; never use `-f`), and never "clean them up" from the main repo —
untracking is done with `git rm --cached` so the disk content stays. The
`check:tracked-artifacts` gate (pre-commit + CI) fails on ANY tracked root path starting with
`_`, present or future. See Hard Rule #23 for the `_tasks` specifics.
---
## Key Conventions
@@ -662,6 +671,18 @@ the stale-enforcement added in Fase 6A.3.
22. **Cross-session safety — this repo is worked by MANY parallel sessions/agents at once; never step on another's in-flight work.** Two absolute bans, both recurring incidents (this rule exists because they keep happening):
- **(a) Never `git stash` / `git stash pop` — ANYWHERE in this repo, including inside an isolated worktree, and including inside any subagent you dispatch.** `git stash` operates on the **shared repository object store**, not the per-worktree working tree — so a stash pushed or popped in one session can silently clobber or resurrect another parallel session's uncommitted changes. This is not hypothetical: 2026-07-02 a `#5923` quotaCache change leaked into the unrelated `#2296` worktree via a global `stash pop`, and the same class reincided through a **subagent**. To compare working changes against a base ref **without** stashing, use `git show <ref>:<path>` or `git diff <ref> -- <path>`; to confirm a typecheck/lint error is pre-existing on the base, inspect the base ref directly (`git show origin/release/vX.Y.Z:<path>`) — never stash your tree away to "get it clean". **Put this ban verbatim in the prompt of every subagent that touches git** (agents don't inherit this file's context — the recurrence was a subagent).
- **(b) Never merge, push, rebase, or force-push a PR / branch / worktree that another session is actively working.** An open PR whose head is a live fix worktree in `.claude/worktrees/` you did **not** create (e.g. `fix-5852`/`fix-5923` carrying fresh commits, even when they share your `diegosouzapw` identity), or any branch another session owns, is **off-limits — HOLD**, and let the owning session merge it. **Before** merging or pushing to any PR you did not create _this_ session, run `git worktree list` to check for a matching in-flight worktree and re-check `gh pr view <N> --json state,headRefOid`. Only the owning session merges its own in-flight PR; mid-flight merges race the owner and re-trigger the exact commit/CHANGELOG races Rule #19 and Rule #21 guard against. (Reinforces Rule #19.)
23. **`_tasks/` é INTOCÁVEL como estrutura — append/edit-only.** É um repositório git SEPARADO
(remote privado `diegosouzapw/_tasks_omniroute`) montado como diretório real na raiz do
checkout principal. Regras absolutas: (a) NUNCA mover, renomear, deletar, esvaziar ou
transformar `_tasks` em symlink; sessões só podem CRIAR ou EDITAR arquivos dentro dele;
(b) NUNCA rastrear `_tasks` (nem como symlink) no repo principal — o blob rastreado foi a
causa-raiz de DOIS wipes (2026-08-08 e 2026-08-10: `git reset --hard` materializou o
symlink rastreado por cima do diretório real e o git apagou todo o conteúdo ignorado sem
aviso); (c) após qualquer escrita relevante, `git -C _tasks add -A && git -C _tasks commit
&& git -C _tasks push` — o push frequente é o backup real; (d) repetir esta proibição
VERBATIM no prompt de todo subagente que toque git; (e) se `_tasks` aparecer como symlink
quebrado, NÃO commitar nada — restaurar do remote e avisar o operador. O gate
`check:tracked-artifacts` (pre-commit + CI) bloqueia `_tasks` rastreado em qualquer forma.
---

View File

@@ -3,7 +3,7 @@
@AGENTS.md
**All project rules live in [`AGENTS.md`](AGENTS.md)** — the single source of truth for every AI
assistant (architecture, conventions, testing, quality gates, git workflow, the 22 Hard Rules,
assistant (architecture, conventions, testing, quality gates, git workflow, the 23 Hard Rules,
PII learnings). Read it in full; do not re-add project rules here. Everything below applies ONLY
to Claude Code — operational refinements of rules already defined in `AGENTS.md`.

View File

@@ -1,7 +1,7 @@
# GEMINI.md
> **Single source of truth:** all project rules for AI assistants live in
> [`AGENTS.md`](AGENTS.md). Read it in full before any change — it contains the 22 Hard Rules,
> [`AGENTS.md`](AGENTS.md). Read it in full before any change — it contains the 23 Hard Rules,
> quality gates, code conventions, file-placement / repo-root hygiene rules, the repository map
> and the local development access notes that used to live in this file.

View File

@@ -1,296 +0,0 @@
# Relatorio de pesquisa: repositorios de CLI integraveis com OmniRoute
> **Status final (2026-08-03):** este documento preserva o inventário inicial. A pesquisa foi concluída para `104/104` casos. Para resultados por projeto, use `04-tracker-integracoes-clis.md`; para o fechamento executivo e a estratégia de publicação, use `06-relatorio-final-104-clis-e-estrategia-prs.md`.
**Data da pesquisa:** 2026-08-01
**Escopo:** agentes de codigo de terminal, CLIs de LLM, runtimes de agentes e harnesses que possam consumir um endpoint HTTP compativel com OpenAI, Anthropic ou Gemini, ou que possam ser adaptados por provider/plugin/ACP/MITM.
**Fonte local principal:** `_tasks/hands-off/2026-08-01_release-v3.8.50_v3.8.50_sess-e1846bc2/handoff.md`
**Fontes externas principais:** GitHub Search/API, READMEs dos repositorios e a lista publica `bradAGI/awesome-cli-coding-agents` (atualizada em 2026-07-29).
## 1. Resumo executivo
O OmniRoute ja possui uma integracao funcional com o jcode e um catalogo local de ferramentas CLI. O proximo ganho de maior valor e transformar o OmniRoute em um endpoint reconhecido pelos principais agentes de terminal, priorizando configuracao nativa e PR upstream quando o projeto aceitar contribuicoes.
A pesquisa encontrou:
- **33 entradas de ferramentas no registro local `CLI_TOOLS`**, contando o registro extraido de Grok Build em `src/shared/constants/cliToolsGrokBuild.ts`, incluindo Claude Code, Codex CLI, Cline, Kilo, Continue, OpenCode, Aider, jcode, Smelt, Pi, Crush, Goose, Open Interpreter, OpenClaw, Hermes Agent, Letta CLI e outros.
- **Mais de 90 projetos publicos** no inventario externo consultado, entre agentes de codigo, CLIs generalistas, forks, runtimes e orquestradores.
- **Candidatos com evidencia forte de endpoint customizavel:** Gemini CLI, Claw Code, Plandex, MiMo Code, Trae Agent, Kimi CLI, Every Code, Open Codex, VT Code, OpenHands CLI, gptme, Nanocoder, RA.Aid, CoreCoder, Grok CLI, Gitlawb Zero, DeepSeek Reasonix, KlaatCode, CodeMini, DvalinCode, Coro Code, Mini-Kode, Late CLI, Agentty, Aizen, Minacode, YottaCode, aichat, ShellGPT, Mistral Vibe, OpenSquilla, Kode CLI e outros.
- **Candidatos que exigem pesquisa confirmatoria:** projetos com README generico, configuracao recente, repositorio ambiguo, binario fechado ou sem evidencia textual suficiente de `base_url`/provider.
- **Candidatos que podem ser integrados por outros caminhos:** ACP, MCP, wrapper/launcher, provider adapter, proxy MITM ou apenas documentacao; eles nao devem ser classificados automaticamente como OpenAI-compatible.
Conclusao: devemos pesquisar e tentar todos os candidatos tecnicamente viaveis, mas separar claramente `suporte no catalogo OmniRoute`, `configuracao generica`, `adaptacao upstream publicada` e `PR/issue aceita`. O tracker acompanha essas dimensoes separadamente.
## 2. Metodo e limites
### 2.1 Como a busca foi feita
1. Leitura integral do handoff do caso jcode para capturar o padrao de integracao, validacao, publicacao e as restricoes de worktree.
2. Inspecao do catalogo local em `src/shared/constants/cliTools.ts`, da documentacao de CLI e do fluxo de setup em `docs/guides/CLI-INTEGRATIONS.md`.
3. Consulta do GitHub Search/API para resolver o repositorio canonico de cada nome, evitando homonimos.
4. Leitura de README/raw quando disponivel, procurando sinais como `base_url`, `baseURL`, `OPENAI_BASE_URL`, `OPENAI_API_BASE`, `LLM_BASE_URL`, `provider`, `gateway`, `model provider`, `Anthropic` e `Gemini`.
5. Consulta da lista `https://github.com/bradAGI/awesome-cli-coding-agents`, que serve como descoberta ampla, nao como prova de compatibilidade.
6. Classificacao por adocao, manutencao, licenca, evidencia de endpoint, maturidade, potencial de PR e utilidade para o ecossistema OmniRoute.
### 2.2 O que ainda nao foi afirmado
- Nao foi feita implementacao ou abertura de PR/issue para os candidatos abaixo; o unico caso publicado nesta sessao anterior e o jcode.
- A presenca da palavra `provider` no README nao prova que uma URL arbitraria funciona em runtime.
- Estrelas e datas sao snapshots aproximados obtidos em 2026-08-01 e podem mudar.
- Repositorios fechados ou com EULA entram no inventario para avaliacao de configuracao, mas nao implicam possibilidade de fork ou PR.
- Cada task de integracao precisa repetir a pesquisa no upstream antes de editar codigo.
## 3. Baseline do OmniRoute
### 3.1 Superficie que o OmniRoute oferece
- Endpoint OpenAI em `/v1`.
- Superficie Anthropic na raiz, usada por clientes que esperam `/v1/messages` a partir do `ANTHROPIC_BASE_URL`.
- Superficie Gemini em `/v1beta`.
- Catalogo de modelos consultavel pelos comandos de setup quando o cliente suporta descoberta.
- Chave via `OMNIROUTE_API_KEY` ou chave selecionada no dashboard.
- Traducao entre formatos, streaming SSE, tool calling, fallback, combos, custos e politicas de autenticacao.
- Modos de consumo: configuracao de ambiente, arquivo nativo do cliente, provider customizado, ACP/MCP e MITM.
### 3.2 Catalogo local ja registrado
Fonte: `src/shared/constants/cliTools.ts` e `src/shared/constants/cliToolsGrokBuild.ts`.
**Codigo/CLI:** Claude Code, OpenAI Codex CLI, Factory Droid, OpenClaw, Cursor, Cline, Kilo Code, Continue, Antigravity, GitHub Copilot CLI, OpenCode, Kiro, Qwen Code, Aider, ForgeCode, Cursor Agent CLI, Roo Code, jcode, DeepSeek TUI, CodeWhale, Smelt, Pi, Crush.
**Agentes:** Hermes, Hermes Agent, Goose, Open Interpreter, Oh My Pi, Letta CLI, Warp AI, Agent Deck.
Os documentos do catalogo tambem mantem um backlog MITM para ferramentas sem base URL, como Windsurf, Amp, Amazon Q/Kiro CLI e Cowork. Esses casos devem permanecer separados de uma integracao direta.
### 3.3 Caso jcode (referencia validada)
- Upstream: `https://github.com/1jehuang/jcode`
- Mecanismo: perfil OpenAI-compatible dirigido por metadados; nao foi criado um plugin de runtime.
- Branch: `feat/omniroute-provider`
- Commit: `ee4f904e6`
- PR no fork: `https://github.com/diegosouzapw/jcode/pull/1`
- Issue no upstream: `https://github.com/1jehuang/jcode/issues/704`
- Diff: 6 arquivos, `+56/-3`.
- Validacao: `cargo check --workspace` limpo; 205 testes passaram e uma falha foi preexistente/ambiental.
- Estado: aguardando mantenedor; o upstream nao aceita PR de forks externos, por isso a issue e o artefato oficial.
- Pendencia prometida: adicionar no README do OmniRoute a secao "Tools & repositories that work with OmniRoute".
Licao: o trabalho deve comecar descobrindo o mecanismo real de providers do upstream. Nem todos os clientes precisam de mudanca no OmniRoute; alguns precisam somente de um perfil local, e outros exigirao um adaptador especifico.
## 4. Candidatos prioritarios com evidencia concreta
As evidencias abaixo sao sinais de README/configuracao observados na pesquisa inicial. A task individual deve abrir o arquivo exato, confirmar a versao atual e executar um smoke test.
| Projeto | Repositorio | Evidencia inicial | Rota provavel |
|---|---|---|---|
| Gemini CLI | `google-gemini/gemini-cli` | `GOOGLE_GEMINI_BASE_URL` | configuracao direta; possivel PR/documentacao |
| Claw Code | `ultraworkers/claw-code` | `OPENAI_BASE_URL`, provider compativel | configuracao direta ou provider |
| Plandex | `plandex-ai/plandex` | providers customizados com `baseUrl` | provider/preset |
| MiMo Code | `XiaomiMiMo/MiMo-Code` | `@ai-sdk/openai-compatible` e `baseURL` | provider customizado |
| Trae Agent | `bytedance/trae-agent` | `model_providers` e `base_url` | provider/config |
| Kimi CLI | `MoonshotAI/kimi-cli` | modos `openai_legacy`, `openai_responses`, `anthropic` e `base_url` | provider nativo/config |
| Every Code | `just-every/code` | fork Codex com providers OpenAI/Claude/Gemini | perfil/provider |
| Open Codex | `ymichael/open-codex` | multi-provider e OpenAI-compatible | fork/provider |
| VT Code | `vinhnx/vtcode` | `custom_providers[].base_url`, failover | provider customizado |
| OpenHands CLI | `OpenHands/OpenHands-CLI` | `LLM_BASE_URL` | configuracao direta |
| gptme | `gptme/gptme` | `OPENAI_BASE_URL` e providers | configuracao direta |
| Nanocoder | `Nano-Collective/nanocoder` | qualquer API OpenAI-compatible | configuracao direta |
| RA.Aid | `ai-christianson/RA.Aid` | `OPENAI_API_BASE` | configuracao direta |
| CoreCoder | `he-yufeng/CoreCoder` | `OPENAI_BASE_URL` | configuracao direta |
| Grok CLI | `superagent-ai/grok-cli` | `GROK_BASE_URL`/`baseURL` | configuracao direta |
| Gitlawb Zero | `Gitlawb/zero` | provider `custom-openai-compatible`, `--base-url` | provider/flag |
| DeepSeek Reasonix | `esengine/DeepSeek-Reasonix` | provider compativel e endpoint | confirmar configuracao |
| KlaatCode | `KlaatAI/klaatcode` | `customModels` OpenAI-compatible | configuracao JSON |
| CodeMini CLI | `havingautism/Codemini-CLI` | `gateway.base_url` | gateway/config |
| Zot | `patriceckhart/zot` | `--base-url` e provider custom em `models.json` | flag/config |
| Pool | `poolsideai/pool` | `POOLSIDE_STANDALONE_BASE_URL`; licenca proprietaria | configuracao, sem PR assumido |
| Octomind | `Muvon/octomind` | `<PROVIDER>_API_URL`/`LOCAL_API_URL` | provider/env |
| Coro Code | `Blushyes/coro-code` | `OPENAI_BASE_URL` | configuracao direta |
| Mini-Kode | `minmaxflow/mini-kode` | `MINIKODE_BASE_URL` | configuracao direta |
| Late CLI | `mlhher/late-cli` | `OPENAI_BASE_URL`/`api-url` | env/flag |
| Agentty | `1ay1/agentty` | modelo agnostico e endpoints compativeis | confirmar arquivo de config |
| Aizen | `aizen-stack/aizen` | CLI Rust OpenAI-compatible; `AIZEN_BASE_URL` | configuracao direta |
| Clif-Code | `DLhugly/Clif-Code` | OpenRouter/OpenAI/Anthropic/Ollama | provider/config |
| Minacode | `hit9/minacode` | provider e compatibilidade no README | confirmar URL |
| YottaCode | `yottadynamics/yottacode` | modelo escolhido, gateway/provider | confirmar config |
| aichat | `sigoden/aichat` | providers OpenAI/Claude/Gemini e compatibilidade | `models.yaml`/provider |
| ShellGPT | `TheR1D/shell_gpt` | `API_BASE_URL` | env/config |
| Mistral Vibe | `mistralai/mistral-vibe` | `base_url`, API base e provider | config/env |
| OpenSquilla | `opensquilla/opensquilla` | 20+ providers e gateway | provider/config |
| Kode CLI | `shareAI-lab/Kode-cli` | provider, endpoint e Anthropic/OpenAI/Gemini | config |
| Crush | `charmbracelet/crush` | `base_url`, provider compativel | ja catalogado no OmniRoute; validar upstream |
| Hermes Agent | `NousResearch/hermes-agent` | endpoint/gateway e 300+ modelos | ja catalogado; validar modo de endpoint |
| OpenClaw | `openclaw/openclaw` | providers, gateway e endpoints | ja catalogado; validar configuracao atual |
## 5. Inventario amplo localizado
### 5.1 Agentes de terminal e coding CLIs
Os projetos desta tabela foram encontrados na lista curada ou no GitHub Search. `Pesquisa` indica o proximo gate; nao significa que a integracao ja esta pronta.
| Projeto | Repositorio | Licenca/sinal publico | Situacao inicial |
|---|---|---|---|
| OpenCode | `anomalyco/opencode` | multi-provider, 75+ providers | ja suportado; acompanhar provider/plugin |
| Codex CLI | `openai/codex` | Apache-2.0, provider configuravel | ja suportado |
| OpenHands principal | `All-Hands-AI/OpenHands` | OSS, CLI e web | pesquisar CLI e `LLM_BASE_URL` |
| Pi | `badlogic/pi-mono` | harness multi-provider | ja suportado; confirmar repo atual |
| Open Interpreter | `OpenInterpreter/open-interpreter` | Apache-2.0, `--api_base` | ja suportado |
| Cline | `cline/cline` | Apache-2.0, base URL/gateway | ja suportado |
| Goose | `aaif-goose/goose` | Apache-2.0, providers | ja suportado |
| Aider | `Aider-AI/aider` | Apache-2.0, Anthropic/OpenAI | ja suportado |
| Continue | `continuedev/continue` | Apache-2.0, multi-model | ja suportado |
| Deep Agents Code | `langchain-ai/deepagents` | MIT, tool-calling LLM | pesquisar pacote `deepagents-code` |
| Crush | `charmbracelet/crush` | provider/base URL | ja suportado |
| Kilo Code | `Kilo-Org/kilocode` | MIT, providers | ja suportado |
| Qwen Code | `QwenLM/qwen-code` | Apache-2.0, providers | ja suportado |
| Roo Code | `RooCodeInc/Roo-Code` | Apache-2.0 | ja catalogado; validar CLI |
| Grok Build | `xai-org/grok-build` | Apache-2.0, provider | ja suportado |
| Oh My Pi | `can1357/oh-my-pi` | provider custom em YAML | ja suportado |
| SWE-agent | `SWE-agent/SWE-agent` | MIT | pesquisar backend e base URL |
| Smol Developer | `smol-ai/developer` | embeddable agent | adapter/SDK, nao necessariamente CLI |
| Claude Engineer | `Doriandarko/claude-engineer` | CLI Claude | pesquisar provider |
| Claurst | `Kuberwastaken/claurst` | GPL-3.0, provider | confirmar endpoint e politica de fork |
| Free Code | `paoloanzn/free-code` | fork de Claude Code | pesquisar licenca e endpoint |
| Codebuff | `CodebuffAI/codebuff` | multi-agent CLI | pesquisar provider |
| ForgeCode | `antinomyhq/forge` | 300+ modelos | ja suportado |
| OpenSquilla | `opensquilla/opensquilla` | Apache-2.0, gateway | candidato forte |
| Kode CLI | `shareAI-lab/Kode-cli` | Apache-2.0, endpoint | candidato forte |
| Devon | `entropy-research/Devon` | pair programmer TUI | pesquisar backend |
| AutoCodeRover | `AutoCodeRoverSG/auto-code-rover` | agente de issues | pesquisar configuracao de modelos |
| Letta Code | `letta-ai/letta-code` | Apache-2.0, model-agnostic | pesquisar API base |
| CodeMachine CLI | `moazbuilds/CodeMachine-CLI` | multi-agent local | pesquisar provider |
| Codel | `semanser/codel` | AGPL-3.0, Docker/web UI | confirmar servidor OpenAI e restricoes AGPL |
| Agentless | `OpenAutoCoder/Agentless` | workflow sem loop persistente | pesquisar entrada de modelo |
| Amazon Q Developer CLI | `aws/amazon-q-developer-cli` | Apache-2.0 | provavelmente auth/ecossistema AWS; pesquisar |
| Neovate Code | `neovateai/neovate-code` | MIT, plugin/multi-provider | candidato forte |
| Groq Code CLI | `build-with-groq/groq-code-cli` | multi-model | pesquisar endpoint |
| Dexto | `truffle-ai/dexto` | CLI/web/API, subagentes | pesquisar provider |
| claw-code-agent | `HarnessLab/claw-code-agent` | Python, sem dependencias | confirmar endpoint |
| g3 | `dhanji/g3` | Rust, provider abstraction | confirmar licenca e URL |
| Coro Code | `Blushyes/coro-code` | base URL/OpenAI | candidato |
| Mini-Kode | `minmaxflow/mini-kode` | MIT, referencia educacional | candidato |
| zot | `patriceckhart/zot` | MIT, TUI/JSON/RPC | candidato |
| agentty | `1ay1/agentty` | MIT, ACP e multi-provider | candidato |
| nori-cli | `tilework-tech/nori-cli` | multi-provider sobre Codex | pesquisar base URL |
| cursor-agent clone | `civai-technologies/cursor-agent` | OpenAI/Claude/Ollama | pesquisar maturidade e licenca |
| DvalinCode | `arthurpanhku/dvalincode` | MIT, OpenAI-compatible | candidato |
| OpenHarness | `zhijiewong/openharness` | Apache-2.0, any LLM | candidato |
| Octomind | `Muvon/octomind` | Apache-2.0, 13+ providers | candidato |
| Codex Infinity | `lee101/codex-infinity` | fork Codex | pesquisar endpoint |
| San | `genai-io/san` | Apache-2.0, provider-neutral | pesquisar endpoint |
| Waveloom | `Menfre01/waveloom` | Apache-2.0, DeepSeek-focused | pesquisar provider |
| picocode | `jondot/picocode` | Rust, multi-LLM | pesquisar provider |
| QQCode | `qnguyen3/qqcode` | Rust, skills | pesquisar provider |
| Keen Code | `mochow13/keen-code` | MIT, 9+ providers | pesquisar provider |
| Smelt | `leonardcser/smelt` | MIT, OpenAI-compatible | ja suportado |
| Grinta | `josephsenior/Grinta-Coding-Agent` | MIT, Python | pesquisar provider |
| Zap | `zap-coding-agent/zap-coding-agent` | MIT, MCP, local/OpenAI | pesquisar endpoint |
| Binharic | `CogitatorTech/binharic-cli` | multi-provider | pesquisar endpoint |
| Darce | `AmerSarhan/darce-cli` | MIT, multi-model | pesquisar endpoint |
| CLAII | `agencyswarm/CLAII` | multi-agent/MCP | pesquisar endpoint |
### 5.2 Agentes generalistas e ecossistema OpenClaw
Estes podem consumir OmniRoute como backend, mas a task deve confirmar se a interface de configuracao e realmente uma CLI de codigo ou apenas um gateway de agente.
| Projeto | Repositorio | Possivel caminho |
|---|---|---|
| OpenClaw | `openclaw/openclaw` | provider/gateway; ja catalogado |
| nanobot | `HKUDS/nanobot` | provider OpenAI-compatible |
| ZeroClaw | `zeroclaw-labs/zeroclaw` | trait de provider |
| NanoClaw | `gavrielc/nanoclaw` | Anthropic SDK; pesquisar base |
| PicoClaw | `sipeed/picoclaw` | provider/config |
| IronClaw | `nearai/ironclaw` | provider Rust |
| NullClaw | `nullclaw/nullclaw` | 23+ providers |
| Clawith | `dataelement/Clawith` | gateway/teams |
| claw0 | `shareAI-lab/claw0` | tutorial/runtime; pesquisa de viabilidade |
| Moltis | `moltis-org/moltis` | provider Rust |
| GitClaw | `open-gitagent/gitclaw` | agente Git-native; pesquisar |
| LionClaw | `moshthepitt/lionclaw` | CLI local; pesquisar |
| Aizen | `aizen-stack/aizen` | OpenAI-compatible |
| aichat | `sigoden/aichat` | provider/model YAML |
| ShellGPT | `TheR1D/shell_gpt` | `API_BASE_URL` |
| gptme | `gptme/gptme` | `OPENAI_BASE_URL` |
### 5.3 Orquestradores, wrappers e ferramentas adjacentes
Nao sao todos alvos de um provider OmniRoute. Devem ser avaliados para launcher, ACP, MCP, observabilidade ou configuracao de seus agentes filhos.
| Projeto | Repositorio | Tipo de integracao a investigar |
|---|---|---|
| Agent Deck | `asheshgoplani/agent-deck` | config dos CLIs filhos; ja catalogado |
| VibePod | `VibePod/vibepod-cli` | wrapper Docker e metricas |
| zeroshot | `the-open-engine/zeroshot` | launcher/worktrees |
| Fractal | `plasma-ai/fractal` | orquestrador de CLIs |
| Bernstein | `chernistry/bernstein` | orquestrador/verificador |
| Traycer | `traycerai/traycer` | CLI custom e agentes filhos |
| h5i | `h5i-dev/h5i` | execucao paralela |
| OMK | `dmae97/open-multi-agent-kit` | control plane/provider-neutral |
| kodo | `ikamensh/kodo` | orquestrador |
| ORCH | `oxgeneral/ORCH` | fila de tarefas |
| LoopTroop | `LoopTroop-ai/LoopTroop` | orchestration sobre OpenCode |
| Galley | `shinpr/galley` | worktree/PR handoff |
| Relay | `jcast90/relay` | MCP/orquestracao |
| sage | `youwangd/SageCLI` | runtime-agnostic |
| 5dive | `5dive-ai/5dive` | agentes em servidor |
| agx | `ramarlina/agx` | checkpoints e agentes |
| claude-code-router | `musistudio/claude-code-router` | proxy/roteamento; possivel upstream consumidor |
| cc-router | `finch-xu/cc-router` | proxy Anthropic multi-provider |
| OneCLI | `onecli/onecli` | broker de credenciais, nao agente |
| agent-browser | `vercel-labs/agent-browser` | ferramenta MCP/plugin |
| OpenWork | `different-ai/openwork` | desktop sobre OpenCode |
| Mistral Vibe | `mistralai/mistral-vibe` | provider/base URL |
| Junie CLI | `junie.jetbrains.com` | fechado; configuracao BYOK a confirmar |
| Pool | `poolsideai/pool` | binario/EULA; sem PR presumido |
## 6. Evidencias tecnicas e mapeamento para OmniRoute
### 6.1 Padroes de endpoint encontrados
| Padrao observado | Exemplos | Acao OmniRoute |
|---|---|---|
| `OPENAI_BASE_URL`/`OPENAI_API_BASE` | Claw Code, RA.Aid, CoreCoder, Coro Code | fornecer root ou `/v1` conforme o cliente; testar append de path |
| `base_url`/`baseURL` em provider | Plandex, MiMo Code, Trae Agent, VT Code, KlaatCode | gerar bloco de provider e modelo |
| `LLM_BASE_URL` | OpenHands CLI | configurar surface OpenAI e validar streaming/tool calling |
| `GOOGLE_GEMINI_BASE_URL` | Gemini CLI | usar superficie `/v1beta`/Gemini; confirmar formato esperado |
| `GROK_BASE_URL` | Grok CLI | decidir se o cliente fala xAI ou OpenAI; testar traducoes |
| `--base-url` | Gitlawb Zero, Zot, jcode | launcher ou perfil persistido |
| `API_BASE_URL` | ShellGPT | config/env direta |
| `<PROVIDER>_API_URL`/gateway | Octomind, Pool, OpenSquilla | provider selecionavel; testar cada preset |
| ACP/MCP sem URL direta | Agentty, Kimi CLI, Goose, OpenCode | avaliar se OmniRoute deve ser provider ou backend ACP |
| endpoint nao customizavel | Cursor desktop, Antigravity, Kiro, Windsurf, Amp | somente MITM/guide; nao prometer integracao direta |
### 6.2 Superficies e riscos de protocolo
- **`/v1` duplicado:** alguns clientes recebem a raiz e acrescentam `/v1/chat/completions`; outros exigem a URL final com `/v1`. Cada task deve registrar o resultado real.
- **Chat Completions vs Responses:** forks do Codex e clientes modernos podem usar Responses; testar ambas quando o cliente permitir.
- **Anthropic:** clientes que mandam `/v1/messages` esperam `ANTHROPIC_BASE_URL` sem `/v1` no valor. A traducao Anthropic do OmniRoute deve ser validada com streaming e tool use.
- **Gemini:** Gemini CLI pode esperar uma base Gemini nativa, nao somente OpenAI-compatible; validar `generateContent`, streaming e headers.
- **Tool calling:** o agente pode exigir nomes/ids de ferramenta estaveis, JSON estrito, `tool_choice` ou blocos de pensamento especificos.
- **Descoberta de modelos:** `/v1/models` pode ser obrigatorio, opcional ou inexistente. O setup precisa aceitar `--model` fixo quando a descoberta nao for suportada.
- **Autenticacao:** alguns projetos leem somente env, outros gravam tokens em arquivo/keyring e alguns usam OAuth proprietario. Nunca reutilizar credenciais de um upstream sem verificar escopo.
- **Streaming e retry:** SSE, timeouts, abort signals e re-tentativas podem divergir do cliente. Validar uma chamada longa e uma falha de provider.
- **Licenca:** GPL/AGPL, EULA e repositorios sem SPDX exigem decisao de distribuicao antes de enviar patch.
## 7. Riscos de pesquisa e integracao
1. **Homonomimos e clones:** usar sempre URL canonica, organizacao, release e README do repositorio correto.
2. **Repositorios que mudam rapidamente:** congelar commit/versao no relatorio da task e repetir a consulta no dia da implementacao.
3. **README divergente do codigo:** procurar schema, parser de config, testes e comando de execucao; README sozinho e evidencia Tier 1.
4. **Clientes fechados:** registrar como `needs-mitm` ou `config-only`, nunca como PR upstream.
5. **Forks com historia de origem controversa:** avaliar politica, licenca e aceite de contribuicoes antes de reproduzir componentes.
6. **Segredos no ambiente:** limpar `OMNIROUTE_API_KEY` e chaves de teste quando a suite assume ambiente sem credencial, como ocorreu no jcode.
7. **Mudancas no checkout:** usar worktree em `.claude/worktrees/` por projeto; nao editar o checkout compartilhado do OmniRoute nem usar `git stash`.
## 8. Recomendacao
Executar primeiro os lotes P0/P1 do documento de prioridade. Cada lote pode ter ate tres subagentes, um repositorio por worktree. O agente principal deve revisar a pesquisa, o smoke test e a licenca antes de permitir implementacao. O resultado de cada caso deve atualizar o tracker com commit, PR/issue, validacao e status upstream, sem preencher campos externos por suposicao.
## 9. Referencias
- OmniRoute CLI catalogo: `src/shared/constants/cliTools.ts`
- OmniRoute CLI reference: `docs/reference/CLI-TOOLS.md`
- OmniRoute setup guide: `docs/guides/CLI-INTEGRATIONS.md`
- Handoff jcode: `_tasks/hands-off/2026-08-01_release-v3.8.50_v3.8.50_sess-e1846bc2/handoff.md`
- Inventario curado: `https://github.com/bradAGI/awesome-cli-coding-agents`
- GitHub Search API: `https://api.github.com/search/repositories`

View File

@@ -1,167 +0,0 @@
# Prioridade de integracoes de CLIs com OmniRoute
> **Status final (2026-08-03):** esta é a priorização inicial que orientou a execução. Todos os `104/104` casos já foram pesquisados. A classificação final está no tracker `04`; a estratégia revisada de contribuição está no relatório `06`.
**Snapshot:** 2026-08-01
**Objetivo:** ordenar do melhor para o pior todos os projetos tecnicamente candidatos a consumir OmniRoute, sem remover projetos pequenos. A ordem e uma fila de pesquisa/execucao; ela nao e promessa de que todo upstream aceitara um PR.
## Como ler a prioridade
- **P0:** ja esta no catalogo OmniRoute ou tem evidencia muito forte de endpoint customizavel; executar/consolidar primeiro.
- **P1:** forte candidato novo, com provider/base URL evidente e bom retorno para o ecossistema.
- **P2:** tecnicamente promissor, mas requer confirmacao de protocolo, config, maturidade ou licenca.
- **P3:** possivel via ACP/MCP/wrapper/launcher, ou com menor adocao; pesquisar depois dos P0-P2.
- **P4:** cliente fechado, EULA, MITM ou pesquisa exploratoria; manter no inventario, mas nao bloquear os demais.
Os fatores usados foram: evidencia de endpoint arbitrario, adocao/atividade, facilidade de teste, compatibilidade OpenAI/Anthropic/Gemini, maturidade, licenca, chance de PR upstream, valor para usuarios OmniRoute e risco de protocolo.
## A. Catalogo OmniRoute ja existente
Estas entradas ja aparecem no registro local. A prioridade aqui significa consolidar documentacao, smoke tests, detector/configurador e eventual upstream nominal; nao significa recriar uma integracao que ja existe.
| Ordem | Projeto | Repositorio/documentacao | Estado local | Proximo foco |
|---:|---|---|---|---|
| A1 | Claude Code | `anthropics/claude-code` | catalogado; Anthropic base URL | manter compatibilidade Anthropic, streaming e tools |
| A2 | Codex CLI | `openai/codex` | catalogado; OpenAI-compatible | Responses, profiles e `/v1` |
| A3 | OpenCode | `anomalyco/opencode` | catalogado; provider | provider nativo/plugin e model discovery |
| A4 | Cline | `cline/cline` | catalogado; base URL | validar CLI/extension e append de `/v1` |
| A5 | Goose | `aaif-goose/goose` | catalogado; `OPENAI_HOST` | validar schema atual e ACP |
| A6 | Aider | `Aider-AI/aider` | catalogado; `OPENAI_API_BASE` | LiteLLM path, tools e custo |
| A7 | Continue | `continuedev/continue` | catalogado; provider OpenAI | CLI e config YAML atual |
| A8 | Kilo Code | `Kilo-Org/kilocode` | catalogado; custom URL | CLI, extension e auth |
| A9 | Roo Code | `RooCodeInc/Roo-Code` | catalogado; custom URL | CLI/headless e provider |
| A10 | Qwen Code | `QwenLM/qwen-code` | catalogado; `modelProviders` | V4 schema, Responses e env |
| A11 | Open Interpreter | `OpenInterpreter/open-interpreter` | catalogado; `--api_base` | streaming e tool execution |
| A12 | OpenClaw | `openclaw/openclaw` | catalogado; gateway/provider | config atual e segurança |
| A13 | Hermes Agent | `NousResearch/hermes-agent` | catalogado; provider/gateway | endpoint custom e modelos |
| A14 | Hermes | `NousResearch/hermes-agent` | catalogado/dual entry | distinguir CLI e agente |
| A15 | Oh My Pi | `can1357/oh-my-pi` | catalogado; YAML provider | auto-discovery e tool calling |
| A16 | Pi | `badlogic/pi-mono` | catalogado; provider | confirmar repositorio/CLI atual |
| A17 | Crush | `charmbracelet/crush` | catalogado; `base_url` | config TOML/JSON atual |
| A18 | Smelt | `leonardcser/smelt` | catalogado; OpenAI-compatible | headless e subagents |
| A19 | ForgeCode | `antinomyhq/forge` | catalogado; multi-provider | base URL e custom agents |
| A20 | jcode | `1jehuang/jcode` | integrado e proposto upstream | aguardar issue #704; manter README OmniRoute |
| A21 | DeepSeek TUI | `hunterbown/deepseek-tui` | catalogado legado | confirmar sucessor CodeWhale |
| A22 | CodeWhale | `Hmbown/CodeWhale` | catalogado | config primaria e legado |
| A23 | Grok Build | `xai-org/grok-build` | catalogado; `~/.grok/config.toml` | provider OmniRoute e modelos |
| A24 | Cursor Agent CLI | `cursor.com/cli` | catalogado parcial | confirmar limites de endpoint |
| A25 | Factory Droid | `Factory-AI/factory` | catalogado parcial | BYOK e endpoint suportado |
| A26 | GitHub Copilot CLI | `github/copilot-cli` | catalogado | provider base URL atual |
| A27 | Letta CLI | `letta-ai/letta-code` | catalogado | config pi-ai/local mode |
| A28 | Warp AI | `warpdotdev/Warp` | catalogado parcial | somente BYOK/desktop |
| A29 | Agent Deck | `asheshgoplani/agent-deck` | catalogado | agentes filhos e ACP |
| A30 | Antigravity | produto Google | MITM backlog | nao tratar como endpoint direto |
| A31 | Kiro AI | produto AWS | MITM backlog | auth/SSO e MITM |
| A32 | Cursor desktop | produto Anysphere | cloud/MITM | manter separado do Cursor CLI |
## B. Novos candidatos em ordem de execucao
| Ordem | Prioridade | Projeto | Repositorio | Evidencia inicial | Rota esperada |
|---:|:---:|---|---|---|---|
| 1 | P0 | Gemini CLI | `google-gemini/gemini-cli` | `GOOGLE_GEMINI_BASE_URL` | config direta/Gemini |
| 2 | P0 | Claw Code | `ultraworkers/claw-code` | `OPENAI_BASE_URL`, provider | OpenAI-compatible |
| 3 | P0 | Plandex | `plandex-ai/plandex` | provider com `baseUrl` | preset/provider |
| 4 | P0 | MiMo Code | `XiaomiMiMo/MiMo-Code` | `@ai-sdk/openai-compatible`, `baseURL` | provider |
| 5 | P0 | Trae Agent | `bytedance/trae-agent` | `model_providers`, `base_url` | provider/config |
| 6 | P0 | Kimi CLI | `MoonshotAI/kimi-cli` | OpenAI legacy/Responses/Anthropic, `base_url` | provider nativo |
| 7 | P0 | Every Code | `just-every/code` | fork Codex, OpenAI/Claude/Gemini | profile/provider |
| 8 | P0 | Open Codex | `ymichael/open-codex` | OpenAI/Gemini/OpenRouter/Ollama | profile/provider |
| 9 | P0 | VT Code | `vinhnx/vtcode` | `custom_providers[].base_url` | provider/failover |
| 10 | P0 | OpenHands CLI | `OpenHands/OpenHands-CLI` | `LLM_BASE_URL` | config direta |
| 11 | P0 | gptme | `gptme/gptme` | `OPENAI_BASE_URL` | config direta |
| 12 | P0 | Nanocoder | `Nano-Collective/nanocoder` | qualquer OpenAI-compatible | config direta |
| 13 | P0 | RA.Aid | `ai-christianson/RA.Aid` | `OPENAI_API_BASE` | config direta |
| 14 | P0 | CoreCoder | `he-yufeng/CoreCoder` | `OPENAI_BASE_URL` | config direta |
| 15 | P1 | Grok CLI | `superagent-ai/grok-cli` | `GROK_BASE_URL`/`baseURL` | config direta |
| 16 | P1 | Gitlawb Zero | `Gitlawb/zero` | `custom-openai-compatible`, `--base-url` | provider/flag |
| 17 | P1 | DeepSeek Reasonix | `esengine/DeepSeek-Reasonix` | endpoint/provider compativel | provider |
| 18 | P1 | KlaatCode | `KlaatAI/klaatcode` | `customModels` OpenAI-compatible | config |
| 19 | P1 | CodeMini CLI | `havingautism/Codemini-CLI` | `gateway.base_url` | gateway |
| 20 | P1 | Zot | `patriceckhart/zot` | `--base-url`, `models.json` | flag/config |
| 21 | P1 | Octomind | `Muvon/octomind` | provider URL envs | provider/env |
| 22 | P1 | DvalinCode | `arthurpanhku/dvalincode` | qualquer OpenAI-compatible | config direta |
| 23 | P1 | Coro Code | `Blushyes/coro-code` | `OPENAI_BASE_URL` | env |
| 24 | P1 | Mini-Kode | `minmaxflow/mini-kode` | `MINIKODE_BASE_URL` | env |
| 25 | P1 | Late CLI | `mlhher/late-cli` | `OPENAI_BASE_URL`, `api-url` | env/flag |
| 26 | P1 | Agentty | `1ay1/agentty` | provider-agnostic, ACP | config/ACP |
| 27 | P1 | Aizen | `aizen-stack/aizen` | Rust OpenAI-compatible, `AIZEN_BASE_URL` | config |
| 28 | P1 | Clif-Code | `DLhugly/Clif-Code` | OpenAI/Anthropic/Ollama | provider |
| 29 | P1 | Minacode | `hit9/minacode` | provider/compatibilidade | confirmar URL |
| 30 | P1 | YottaCode | `yottadynamics/yottacode` | modelo escolhido/gateway | provider |
| 31 | P1 | aichat | `sigoden/aichat` | OpenAI/Claude/Gemini | models YAML |
| 32 | P1 | ShellGPT | `TheR1D/shell_gpt` | `API_BASE_URL` | env |
| 33 | P1 | Mistral Vibe | `mistralai/mistral-vibe` | `base_url`, API base | config |
| 34 | P1 | OpenSquilla | `opensquilla/opensquilla` | gateway, 20+ providers | provider |
| 35 | P1 | Kode CLI | `shareAI-lab/Kode-cli` | endpoint/Anthropic/OpenAI/Gemini | config |
| 36 | P1 | Neovate Code | `neovateai/neovate-code` | plugin/multi-provider | plugin/provider |
| 37 | P1 | Deep Agents Code | `langchain-ai/deepagents` | qualquer tool-calling LLM | provider SDK |
| 38 | P1 | Kode fork/variants | `shareAI-lab/Kode-cli` | multi-provider | confirmar upstream |
| 39 | P1 | OpenHands principal | `All-Hands-AI/OpenHands` | CLI/web; pesquisar LLM base | config/CLI |
| 40 | P1 | SWE-agent | `SWE-agent/SWE-agent` | agente de issues | backend/provider |
| 41 | P1 | AutoCodeRover | `AutoCodeRoverSG/auto-code-rover` | agente de patches | backend/provider |
| 42 | P2 | Claurst | `Kuberwastaken/claurst` | provider/Anthropic | config; licenca GPL |
| 43 | P2 | Codebuff | `CodebuffAI/codebuff` | multi-agent CLI | provider |
| 44 | P2 | Devon | `entropy-research/Devon` | TUI pair programmer | backend |
| 45 | P2 | Letta Code | `letta-ai/letta-code` | model-agnostic | provider |
| 46 | P2 | CodeMachine CLI | `moazbuilds/CodeMachine-CLI` | multi-agent local | provider |
| 47 | P2 | Groq Code CLI | `build-with-groq/groq-code-cli` | multi-model | endpoint |
| 48 | P2 | Dexto | `truffle-ai/dexto` | CLI/web/API | provider |
| 49 | P2 | claw-code-agent | `HarnessLab/claw-code-agent` | endpoint/gateway | provider |
| 50 | P2 | g3 | `dhanji/g3` | Rust provider abstraction | provider |
| 51 | P2 | San | `genai-io/san` | provider-neutral | provider |
| 52 | P2 | Waveloom | `Menfre01/waveloom` | DeepSeek/provider | endpoint |
| 53 | P2 | picocode | `jondot/picocode` | multi-LLM | config |
| 54 | P2 | QQCode | `qnguyen3/qqcode` | skills, Rust | config |
| 55 | P2 | Keen Code | `mochow13/keen-code` | 9+ providers | config |
| 56 | P2 | Grinta | `josephsenior/Grinta-Coding-Agent` | provider-agnostic | config |
| 57 | P2 | Zap | `zap-coding-agent/zap-coding-agent` | Claude/Gemini/OpenAI/LM Studio | provider |
| 58 | P2 | Binharic | `CogitatorTech/binharic-cli` | multi-provider | config |
| 59 | P2 | Darce | `AmerSarhan/darce-cli` | multi-model/streaming | config |
| 60 | P2 | CLAII | `agencyswarm/CLAII` | multi-agent/MCP | provider |
| 61 | P2 | nori-cli | `tilework-tech/nori-cli` | multi-provider sobre Codex | config |
| 62 | P2 | cursor-agent clone | `civai-technologies/cursor-agent` | Claude/OpenAI/Ollama | provider |
| 63 | P2 | Free Code | `paoloanzn/free-code` | fork Claude Code | licenca/config |
| 64 | P2 | Claude Engineer | `Doriandarko/claude-engineer` | CLI Claude | provider |
| 65 | P2 | Smol Developer | `smol-ai/developer` | agent embutivel | SDK/adaptador |
| 66 | P2 | Agentless | `OpenAutoCoder/Agentless` | workflow sem loop | entrada de modelo |
| 67 | P2 | Amazon Q Developer CLI | `aws/amazon-q-developer-cli` | CLI AWS | auth/provider |
| 68 | P2 | nanobot | `HKUDS/nanobot` | OpenClaw rewrite | provider |
| 69 | P2 | ZeroClaw | `zeroclaw-labs/zeroclaw` | providers pluggable | provider |
| 70 | P2 | NanoClaw | `gavrielc/nanoclaw` | Anthropic SDK | base URL |
| 71 | P2 | PicoClaw | `sipeed/picoclaw` | provider/config | provider |
| 72 | P2 | IronClaw | `nearai/ironclaw` | provider Rust | provider |
| 73 | P2 | NullClaw | `nullclaw/nullclaw` | 23+ providers | provider |
| 74 | P2 | Moltis | `moltis-org/moltis` | Rust agent | provider |
| 75 | P2 | GitClaw | `open-gitagent/gitclaw` | Git-native agent | provider |
| 76 | P2 | LionClaw | `moshthepitt/lionclaw` | CLI local | provider |
| 77 | P3 | VibePod | `VibePod/vibepod-cli` | wrapper Docker | launcher |
| 78 | P3 | zeroshot | `the-open-engine/zeroshot` | worktrees/orchestration | launcher |
| 79 | P3 | Fractal | `plasma-ai/fractal` | orquestra CLIs | launcher |
| 80 | P3 | Bernstein | `chernistry/bernstein` | executa/verifica agentes | launcher |
| 81 | P3 | Traycer | `traycerai/traycer` | agentes paralelos | launcher |
| 82 | P3 | h5i | `h5i-dev/h5i` | sandbox e peer review | launcher |
| 83 | P3 | OMK | `dmae97/open-multi-agent-kit` | control plane | ACP/MCP |
| 84 | P3 | kodo | `ikamensh/kodo` | orquestrador | launcher |
| 85 | P3 | ORCH | `oxgeneral/ORCH` | fila de tarefas | launcher |
| 86 | P3 | LoopTroop | `LoopTroop-ai/LoopTroop` | orquestrador OpenCode | launcher |
| 87 | P3 | Galley | `shinpr/galley` | worktree/PR | launcher |
| 88 | P3 | Relay | `jcast90/relay` | MCP/orquestracao | MCP |
| 89 | P3 | SageCLI | `youwangd/SageCLI` | runtime-agnostic | launcher/ACP |
| 90 | P3 | 5dive | `5dive-ai/5dive` | agentes em servidor | launcher |
| 91 | P3 | agx | `ramarlina/agx` | checkpoints | launcher |
| 92 | P3 | claude-code-router | `musistudio/claude-code-router` | proxy multi-provider | integrar como consumidor/proxy |
| 93 | P3 | cc-router | `finch-xu/cc-router` | proxy Anthropic | interoperabilidade |
| 94 | P3 | OneCLI | `onecli/onecli` | broker de credenciais | seguranca/integ. adjacente |
| 95 | P3 | agent-browser | `vercel-labs/agent-browser` | ferramenta para agentes | MCP/plugin |
| 96 | P3 | OpenWork | `different-ai/openwork` | desktop sobre OpenCode | config do agente filho |
| 97 | P4 | Pool | `poolsideai/pool` | `POOLSIDE_STANDALONE_BASE_URL`; EULA | config sem PR presumido |
| 98 | P4 | Junie CLI | `junie.jetbrains.com` | fechado/EAP | BYOK/endpoint a confirmar |
| 99 | P4 | Cursor desktop | `Anysphere` | cloud endpoint | MITM/guide |
| 100 | P4 | Windsurf | produto Codeium | sem base URL geral | MITM |
| 101 | P4 | Amp | `sourcegraph.com/amp` | fechado | MITM/sem PR |
| 102 | P4 | Amazon Q/Kiro CLI | AWS | SSO/ecossistema AWS | MITM/adapter |
| 103 | P4 | Cowork | produto Anthropic | endpoint opaco | MITM |
## C. Regra de promocao/rebaixamento
Um projeto sobe de prioridade quando a pesquisa individual confirma: configuracao documentada, teste local com OmniRoute, licenca permissiva e contribuicao aceita. Desce quando: a URL e fixa, o endpoint e somente SaaS, o README nao corresponde ao codigo, a autenticacao e inseparavel do provedor, ou a licenca/EULA impede redistribuicao. Nenhum projeto e marcado como impossivel sem registrar a evidencia no tracker.

View File

@@ -1,314 +0,0 @@
# Plano executavel de integracao de CLIs
> **Status final (2026-08-03):** a fase de pesquisa foi concluída em lotes de até três worktrees/agentes, cobrindo `104/104` casos. Este documento continua válido como processo operacional para implementação/publicação. Consulte `06-relatorio-final-104-clis-e-estrategia-prs.md` para o resultado final.
**Data:** 2026-08-01
**Objetivo:** pesquisar, integrar, validar e publicar suporte ao OmniRoute em todos os projetos tecnicamente possiveis, mantendo uma fila que permite ate tres subagentes simultaneos.
O ciclo especifico de preparacao, revisao, envio e acompanhamento das contribuicoes upstream esta
em `05-plano-publicacao-prs-upstream.md`.
## 1. Principios operacionais
- Um repositorio por subagente e por worktree.
- No maximo tres tasks de repositorios em execucao ao mesmo tempo.
- Cada task pesquisa o upstream novamente antes de editar; o relatorio inicial e somente contexto.
- O agente principal revisa licenca, arquitetura, smoke test e diff antes do proximo lote.
- Nao usar checkout compartilhado para desenvolvimento e nao usar `git stash`/`git pop`.
- Usar worktrees em `.claude/worktrees/` e branches especificas.
- Nao inventar PR, issue, commit ou aceite de mantenedor.
- Nao adicionar trailers ou rodapes de IA em commits/PRs.
## 2. Fases obrigatorias por projeto
### Fase 0 - Preparacao da task
Criar uma task com nome do projeto, URL canonica, prioridade, evidencia inicial, estado no catalogo OmniRoute e objetivo de integrar. Definir a worktree e o agente responsavel.
### Fase 1 - Pesquisa individual fresca
O agente deve verificar no upstream atual:
- arquitetura de providers e ponto de entrada do CLI;
- arquivo/schema de configuracao e suporte a `base_url`, `baseURL`, `OPENAI_BASE_URL`, `OPENAI_API_BASE`, `LLM_BASE_URL` ou equivalente;
- protocolo real (Chat Completions, Responses, Anthropic Messages, Gemini, ACP, MCP ou outro);
- descoberta de modelos e necessidade de `/v1/models`;
- autenticacao, keyring, OAuth e variaveis de ambiente;
- streaming, tool calling, reasoning e limites conhecidos;
- politica de contribuicao, licenca e se PR de fork externo e aceito;
- atividade, releases, issues/PRs sobre providers customizados ou endpoints locais;
- comandos de build, lint, teste e smoke test;
- possibilidade de fork/PR, issue de proposta, documentacao ou apenas wrapper/MITM.
Registrar commit/release pesquisado e links de evidencia.
### Fase 2 - Gate de viabilidade
Classificar exatamente um caminho inicial:
`viable-direct` (somente configuracao), `viable-upstream` (mudanca no upstream), `viable-acp`, `viable-mcp`, `needs-wrapper`, `needs-mitm`, `config-only`, `blocked` ou `research-more`.
Nao implementar antes de haver uma conclusao de viabilidade e uma razao verificavel.
### Fase 3 - Baseline e TDD
- Executar a suite recomendada pelo upstream antes das mudancas.
- Registrar falhas preexistentes, dependencias ausentes e comandos exatos.
- Limpar `OMNIROUTE_API_KEY` e demais credenciais quando os testes pressupuserem ambiente sem chaves.
- Adicionar primeiro um teste de configuracao, endpoint e selecao de modelo que falhe sem a integracao.
### Fase 4 - Implementacao minima
Implementar apenas o necessario para o caso pesquisado:
- perfil/preset `omniroute` ou provider custom;
- base URL correta (raiz, `/v1` ou `/v1beta` conforme o cliente);
- chave via ambiente ou mecanismo seguro do cliente;
- modelo fixo ou descoberta de modelos;
- selecao/login/report se o CLI tiver esses fluxos;
- documentacao de uso e limites;
- testes de config e chamada.
Se o upstream nao aceitar mudanca, preparar wrapper/launcher ou documentacao local e registrar a limitacao.
### Fase 5 - Validacao funcional
Executar, conforme o protocolo:
- build, lint, typecheck e testes do upstream;
- smoke request com OmniRoute;
- streaming SSE e encerramento por abort;
- tool calling e JSON de argumentos;
- `/v1/models` ou equivalente;
- Chat Completions, Responses, Anthropic Messages e Gemini `generateContent` quando aplicavel;
- fallback/erro, timeout, retry e modelo inexistente;
- teste com chave limpa e teste com `OMNIROUTE_API_KEY` real fora dos logs.
### Fase 6 - Publicacao upstream
- Criar fork somente quando permitido e branch especifica.
- Abrir PR upstream se contribuicoes externas forem aceitas.
- Se PR externo for bloqueado, abrir issue com proposta, patch/referencia e smoke test.
- Se o projeto for fechado/EULA, registrar config manual ou issue de produto; nao criar PR ficticio.
- Atualizar o tracker com URL, commit, estado e resposta do mantenedor.
### Fase 7 - Catalogo e integracao OmniRoute
Quando houver valor para usuarios OmniRoute:
- criar worktree propria do OmniRoute;
- atualizar `src/shared/constants/cliTools.ts` ou `src/shared/constants/cliToolsGrokBuild.ts`;
- atualizar detector em `src/lib/cli-helper/tool-detector.ts` se necessario;
- adicionar gerador/configurador e rota de settings somente se o caso exigir;
- adicionar testes do catalogo, detector, settings, `baseUrlSupport` e `/v1`;
- atualizar `docs/reference/CLI-TOOLS.md`, `docs/guides/CLI-INTEGRATIONS.md` e README quando apropriado;
- atualizar o tracker com a integracao local e evidencias.
### Fase 8 - Fechamento
Registrar commit, branch, PR/issue, testes, limitacoes, status do upstream, status do catalogo OmniRoute e proximo passo. O agente principal faz uma revisao final de seguranca, licenca e factualidade.
## 3. Lotes de ate tres subagentes
O lote e uma unidade operacional. A fila abaixo e ordenada pelo documento `02-prioridade-integracoes-clis.md`; cada linha representa uma task individual.
### Lote 0 - consolidacao do caso de referencia
- `CLI-000` - jcode - manter a issue #704, validar resposta do mantenedor e concluir a secao do README OmniRoute.
### Lote P0.1
- `CLI-001` - Gemini CLI - integrar provider/base URL Gemini.
- `CLI-002` - Claw Code - integrar `OPENAI_BASE_URL`/provider OmniRoute.
- `CLI-003` - Plandex - integrar provider custom com `baseUrl`.
### Lote P0.2
- `CLI-004` - MiMo Code - integrar provider OpenAI-compatible.
- `CLI-005` - Trae Agent - integrar `model_providers` e `base_url`.
- `CLI-006` - Kimi CLI - integrar modos OpenAI/Responses/Anthropic.
### Lote P0.3
- `CLI-007` - Every Code - integrar perfil derivado do Codex.
- `CLI-008` - Open Codex - integrar provider multi-modelo.
- `CLI-009` - VT Code - integrar `custom_providers` e failover.
### Lote P0.4
- `CLI-010` - OpenHands CLI - integrar `LLM_BASE_URL`.
- `CLI-011` - gptme - integrar `OPENAI_BASE_URL`.
- `CLI-012` - Nanocoder - integrar API OpenAI-compatible.
### Lote P0.5
- `CLI-013` - RA.Aid - integrar `OPENAI_API_BASE`.
- `CLI-014` - CoreCoder - integrar `OPENAI_BASE_URL`.
- `CLI-015` - Grok CLI - integrar `GROK_BASE_URL`.
### Lote P1.1
- `CLI-016` - Gitlawb Zero - integrar provider custom e `--base-url`.
- `CLI-017` - DeepSeek Reasonix - confirmar e integrar endpoint.
- `CLI-018` - KlaatCode - integrar `customModels`.
### Lote P1.2
- `CLI-019` - CodeMini CLI - integrar `gateway.base_url`.
- `CLI-020` - Zot - integrar flag/config `--base-url`.
- `CLI-021` - Octomind - integrar provider URL envs.
### Lote P1.3
- `CLI-022` - DvalinCode - integrar OpenAI-compatible.
- `CLI-023` - Coro Code - integrar `OPENAI_BASE_URL`.
- `CLI-024` - Mini-Kode - integrar `MINIKODE_BASE_URL`.
### Lote P1.4
- `CLI-025` - Late CLI - integrar `OPENAI_BASE_URL`/`api-url`.
- `CLI-026` - Agentty - integrar provider e/ou ACP.
- `CLI-027` - Aizen - integrar `AIZEN_BASE_URL`.
### Lote P1.5
- `CLI-028` - Clif-Code - integrar providers OpenAI/Anthropic/Ollama.
- `CLI-029` - Minacode - confirmar provider e integrar URL.
- `CLI-030` - YottaCode - integrar gateway/provider.
### Lote P1.6
- `CLI-031` - aichat - integrar models YAML/provider.
- `CLI-032` - ShellGPT - integrar `API_BASE_URL`.
- `CLI-033` - Mistral Vibe - integrar base URL/provider.
### Lote P1.7
- `CLI-034` - OpenSquilla - integrar gateway/provider.
- `CLI-035` - Kode CLI - integrar endpoint multi-provider.
- `CLI-036` - Neovate Code - integrar plugin/provider.
### Lote P1.8
- `CLI-037` - Deep Agents Code - integrar provider do pacote CLI.
- `CLI-038` - OpenHands principal - integrar CLI/config.
- `CLI-039` - SWE-agent - integrar backend/provider.
### Lote P1.9
- `CLI-040` - AutoCodeRover - integrar backend/provider.
- `CLI-041` - Claurst - integrar provider, respeitando GPL.
- `CLI-042` - Codebuff - integrar provider.
### Lote P2.1
- `CLI-043` - Devon - integrar backend.
- `CLI-044` - Letta Code - integrar provider.
- `CLI-045` - CodeMachine CLI - integrar provider.
### Lote P2.2
- `CLI-046` - Groq Code CLI - integrar endpoint.
- `CLI-047` - Dexto - integrar provider.
- `CLI-048` - claw-code-agent - integrar endpoint.
### Lote P2.3
- `CLI-049` - g3 - integrar provider Rust.
- `CLI-050` - San - integrar provider-neutral.
- `CLI-051` - Waveloom - integrar provider/endpoint.
### Lote P2.4
- `CLI-052` - picocode - integrar multi-LLM.
- `CLI-053` - QQCode - integrar config.
- `CLI-054` - Keen Code - integrar provider.
### Lote P2.5
- `CLI-055` - Grinta - integrar provider.
- `CLI-056` - Zap - integrar Claude/Gemini/OpenAI.
- `CLI-057` - Binharic - integrar multi-provider.
### Lote P2.6
- `CLI-058` - Darce - integrar multi-modelo.
- `CLI-059` - CLAII - integrar provider/MCP.
- `CLI-060` - nori-cli - integrar provider baseado em Codex.
### Lote P2.7
- `CLI-061` - cursor-agent clone - integrar provider.
- `CLI-062` - Free Code - pesquisar licenca e integrar se viavel.
- `CLI-063` - Claude Engineer - integrar provider.
### Lote P2.8
- `CLI-064` - Smol Developer - integrar SDK/adaptador.
- `CLI-065` - Agentless - integrar entrada de modelo.
- `CLI-066` - Amazon Q Developer CLI - pesquisar auth/provider.
### Lote P2.9
- `CLI-067` - nanobot - integrar provider OpenClaw-compatible.
- `CLI-068` - ZeroClaw - integrar trait de provider.
- `CLI-069` - NanoClaw - confirmar base Anthropic.
### Lote P2.10
- `CLI-070` - PicoClaw - integrar provider/config.
- `CLI-071` - IronClaw - integrar provider Rust.
- `CLI-072` - NullClaw - integrar provider.
### Lote P2.11
- `CLI-073` - Moltis - integrar provider Rust.
- `CLI-074` - GitClaw - integrar provider Git-native.
- `CLI-075` - LionClaw - integrar provider CLI.
### Lote P3.1 - wrappers e orquestradores
- `CLI-076` - VibePod; `CLI-077` - zeroshot; `CLI-078` - Fractal.
### Lote P3.2
- `CLI-079` - Bernstein; `CLI-080` - Traycer; `CLI-081` - h5i.
### Lote P3.3
- `CLI-082` - OMK; `CLI-083` - kodo; `CLI-084` - ORCH.
### Lote P3.4
- `CLI-085` - LoopTroop; `CLI-086` - Galley; `CLI-087` - Relay.
### Lote P3.5
- `CLI-088` - SageCLI; `CLI-089` - 5dive; `CLI-090` - agx.
### Lote P3.6
- `CLI-091` - claude-code-router; `CLI-092` - cc-router; `CLI-093` - OneCLI.
### Lote P3.7
- `CLI-094` - agent-browser; `CLI-095` - OpenWork; `CLI-096` - Agent Deck (revisao de agente filho).
### Lote P4 - fechados/MITM
- `CLI-097` - Pool; `CLI-098` - Junie CLI; `CLI-099` - Cursor desktop.
- `CLI-100` - Windsurf; `CLI-101` - Amp; `CLI-102` - Amazon Q/Kiro CLI; `CLI-103` - Cowork.
## 4. Criterio para iniciar o lote seguinte
O lote seguinte pode iniciar quando os tres agentes do lote atual tiverem: pesquisa upstream anexada, gate de viabilidade preenchido, baseline registrado, resultado de smoke test ou bloqueio reproduzivel, e tracker atualizado. Uma falha de um agente nao deve paralisar os outros dois; o agente principal deve marcar `blocked` ou `research-more` com evidencia e seguir a fila.
## 5. Entregaveis de cada task
1. Nota de pesquisa fresca com commit/release e links.
2. Classificacao de viabilidade.
3. Diff minimo ou conclusao documentada de que nao ha diff necessario.
4. Testes e comandos executados, incluindo falhas preexistentes.
5. PR/issue upstream ou justificativa de config-only/MITM.
6. Entrada no catalogo OmniRoute quando aplicavel.
7. Atualizacao do tracker `04-tracker-integracoes-clis.md`.

View File

@@ -1,144 +0,0 @@
# Tracker de integracoes de CLIs com OmniRoute
**Status final da pesquisa:** `104/104` concluídos (`100%`), `0` casos `not-started`. Este é o registro individual autoritativo. O relatório executivo está em `06-relatorio-final-104-clis-e-estrategia-prs.md`.
**Snapshot inicial:** 2026-08-01
**Legenda de status:** `not-started`, `researching`, `research-more`, `viable-direct`, `viable-upstream`, `viable-acp`, `viable-mcp`, `needs-wrapper`, `needs-mitm`, `blocked`, `implementing`, `validating`, `published-pr`, `published-issue`, `awaiting-maintainer`, `accepted`, `rejected`, `integrated`.
Os campos externos (`branch`, `commit`, `PR`, `issue`) ficam como `—` ate haver evidencia real. “Catalogo OmniRoute” significa entrada local, nao necessariamente suporte upstream publicado.
| ID | Prio | Projeto | Repositorio | Pesquisa | Tipo | Upstream | Branch | Commit | PR | Issue | Catalogo OmniRoute | Observacoes/proximo passo |
|---|:---:|---|---|---|---|---|---|---|---|---|---|---|
| CLI-000 | P0 | jcode | `1jehuang/jcode` | concluida | `viable-upstream` | `awaiting-maintainer` | `feat/omniroute-provider` | `ee4f904e6` | [fork PR](https://github.com/diegosouzapw/jcode/pull/1) | [upstream #704](https://github.com/1jehuang/jcode/issues/704) | integrated | acompanhar mantenedor e concluir secao do README |
## Caso publicado: jcode
| Campo | Valor |
|---|---|
| Projeto | jcode |
| Repositorio | `https://github.com/1jehuang/jcode` |
| Status geral | `awaiting-maintainer` |
| Tipo | `viable-upstream`; perfil OpenAI-compatible dirigido por metadados |
| Branch | `feat/omniroute-provider` |
| Commit | `ee4f904e6` |
| PR | `https://github.com/diegosouzapw/jcode/pull/1` (fork de referencia) |
| Issue | `https://github.com/1jehuang/jcode/issues/704` |
| Catalogo OmniRoute | `integrated` / entrada existente |
| Validacao | `cargo check --workspace` limpo; 205 testes passaram; 1 falha preexistente/ambiental |
| Diff | 6 arquivos, `+56/-3` |
| Proximo passo | acompanhar issue #704 e criar secao de README do OmniRoute |
## Tabela principal
| ID | Prio | Projeto | Repositorio | Pesquisa | Tipo | Upstream | Branch | Commit | PR | Issue | Catalogo OmniRoute | Observacoes/proximo passo |
|---|:---:|---|---|---|---|---|---|---|---|---|---|---|
| CLI-001 | P0 | Gemini CLI | `google-gemini/gemini-cli` | concluida | `pr-generic` | `published-issue` | `fix/omniroute-gateway-auth` | `8138105c38cc1637fe9e8a9bd520eb835f1620e6` | — | [upstream #27550](https://github.com/google-gemini/gemini-cli/issues/27550#issuecomment-5152312278) | not-in-catalog | regression `AuthType.GATEWAY`; patch +26; auth 10/10, non-interactive 17/17, content generator 55/55, Gemini `/v1beta` stream/tools smoke verde; aguardar `help wanted` antes de terceira PR |
| CLI-002 | P0 | Claw Code | `ultraworkers/claw-code` | concluida | `pr-docs` | `published-issue` | `docs/omniroute-setup` | `de857038b2f9ff9b319132e2241549e86215c351` | — | [upstream #3283](https://github.com/ultraworkers/claw-code/issues/3283) | not-in-catalog | generic OpenAI Chat Completions; docs +37; 1.415 testes, fmt, docs/release checks e clippy oficial verdes; fork bloqueado pelo GitHub, issue-first; smoke OmniRoute parcial/timeout; chave do smoke deve ser rotacionada |
| CLI-003 | P0 | Plandex | `plandex-ai/plandex` | concluida | `pr-docs` | `published-pr` | `feat/omniroute-provider-docs` | `f8f0694bdf7d1cb6e65a1f1c5bc39f84921a4507` | [upstream #359](https://github.com/plandex-ai/plandex/pull/359) | — | not-in-catalog | custom provider OpenAI-compatible ja existia; docs com `/v1`, `OMNIROUTE_API_KEY`, Docker reachability e model mapping; Go indisponivel; Docusaurus build verde; acompanhar mantenedor |
| CLI-004 | P0 | MiMo Code | `XiaomiMiMo/MiMo-Code` | concluida | `config-only` | not-applicable | `research/omniroute-mimo-code` | — | — | — | not-in-catalog | SHA `ce124cb`; provider customizado `@ai-sdk/openai-compatible` já suporta `baseURL`, `apiKey` e modelo; 116 testes focados + typecheck verdes; smoke CLI inconclusivo por travamento ambiental; sem PR artificial |
| CLI-005 | P0 | Trae Agent | `bytedance/trae-agent` | concluida | `pr-docs` | `published-pr` | `research/omniroute-trae-agent` | `4801e48b69d7583300eb86ec5c69235506d7f205` | [upstream #449](https://github.com/bytedance/trae-agent/pull/449) | — | not-in-catalog | README +39; `provider: openai` + mapping `base_url=/v1`; `/v1/responses`, `/v1/models`, Bearer, tools e limitação sem streaming; 62 testes/17 skips, pre-commit e mocks verdes; CLA pendente |
| CLI-006 | P0 | Kimi CLI | `MoonshotAI/kimi-cli` | concluida | `pr-docs` | `published-issue` | `research/omniroute-kimi-cli` | `a2f62bf6108a6954e798db992411aa06670e224f` | — | [upstream #2576](https://github.com/MoonshotAI/kimi-cli/issues/2576) | not-in-catalog | docs EN/ZH +63; `openai_legacy` `/v1`, chave via `OPENAI_API_KEY`, modelo manual; Responses/Anthropic alternativos; 47 testes e VitePress verdes; aguardar direção do mantenedor antes da PR |
| CLI-007 | P0 | Every Code | `just-every/code` | concluida | `pr-docs` / `config-only` | `published-pr` | `feat/omniroute-integration` | `8fbc8dab5fb76bf05535055801af0c3ccfea6f3b` | [upstream #614](https://github.com/just-every/code/pull/614) | — | not-in-catalog | PR documental aberta e mergeable; release `v0.6.162`; `./build-fast.sh` baseline/pós-patch verdes; smoke mock Responses/SSE/tools verde; acompanhar CI/mantenedor |
| CLI-008 | P0 | Open Codex | `ymichael/open-codex` | concluida | `pr-generic` / `issue-first` | `published-issue` | `feat/omniroute-integration` | `f25de99f991c0e4d9d6ae2811d307cdbff92f869` | — | [upstream #4](https://github.com/ymichael/open-codex/issues/4#issuecomment-5152804104) | not-in-catalog | patch genérico pronto localmente; issue-first por firewall de container e PR #19 fechada; 132 testes, typecheck/build/format verdes; lint bloqueado por ambiente; aguardar mantenedor antes de PR |
| CLI-009 | P0 | VT Code | `vinhnx/vtcode` | concluida | `pr-docs` / `config-only` | `published-pr` | `feat/omniroute-integration` | `256682d10c72f3e6e145d852b6d9d53f5c471988` | [upstream #717](https://github.com/vinhnx/VTCode/pull/717) | — | not-in-catalog | PR documental aberta e mergeable; release `0.141.10`; custom provider `/v1`, Bearer, `auto`, discovery manual, streaming/tools; 10 testes config verdes; nextest/docs checks bloqueados por ambiente; acompanhar CI/mantenedor |
| CLI-010 | P0 | OpenHands CLI | `OpenHands/OpenHands-CLI` | concluida | `config-only` | not-applicable | `feat/omniroute-openhands-cli-integration` | — | — | — | not-in-catalog | SHA `2df8a283`; `LLM_BASE_URL=/v1`, `LLM_API_KEY`, modelo obrigatório `openai/auto`, Chat Completions/SSE/tools; 63 testes focados e mock verdes; sem PR artificial |
| CLI-011 | P0 | gptme | `gptme/gptme` | concluida | `config-only` | not-applicable | `feat/omniroute-gptme-integration` | — | — | — | not-in-catalog | SHA `7fe250529`; provider TOML nomeado, `/v1/chat/completions`, `/v1/models`, Bearer, streaming/tools; compileall verde, pytest bloqueado por deps; docs genericas ja cobrem |
| CLI-012 | P0 | Nanocoder | `Nano-Collective/nanocoder` | concluida | `config-only` | not-applicable | `feat/omniroute-nanocoder-integration` | — | — | — | not-in-catalog | SHA `becae998`; `createOpenAICompatible`, `/v1/models`, streaming/native tools + XML/JSON fallback; types/format/lint/build verdes; suite ampla com falhas preexistentes; sem PR artificial |
| CLI-013 | P0 | RA.Aid | `ai-christianson/RA.Aid` | concluida | `config-only` | not-applicable | `feat/omniroute-ra-aid-integration` | — | — | — | not-in-catalog | SHA `e71bb83`; provider `openai-compatible`, `/v1/chat/completions`, Bearer, modelo explicito/`auto`, function tools; 762 testes + 62 focados e smoke verdes; sem Responses/stream HTTP garantido; Aider exige config separada; sem PR artificial |
| CLI-014 | P0 | CoreCoder | `he-yufeng/CoreCoder` | concluida | `pr-docs` / `config-only` | `published-pr` | `feat/omniroute-integration` | `f4d2851649e5dda20738c313a8a94337b24eeb9d` | [upstream #20](https://github.com/he-yufeng/CoreCoder/pull/20) | — | not-in-catalog | PR documental aberta, nao draft e mergeable; `/v1/chat/completions`, Bearer, `auto`, streaming/native tools; 86 testes, compileall, build, twine e smoke verdes; Ruff mantem 41 falhas preexistentes; acompanhar CI/mantenedor |
| CLI-015 | P1 | Grok CLI | `superagent-ai/grok-cli` | concluida | `config-only` | not-applicable | `feat/omniroute-grok-cli-integration` | — | — | — | not-in-catalog | SHA `fb97af8`; `GROK_BASE_URL`/`--base-url`, Chat Completions/SSE, Bearer, `auto` e tools confirmados; 47/48 suites e 246 testes no gate isolado, 6 arquivos/39 testes focados verdes; Node não carrega `bun:sqlite`; Responses/search/STT/Batch/midia não garantidos; monitorar PRs #290/#349 |
| CLI-016 | P1 | Gitlawb Zero | `Gitlawb/zero` | concluida | `config-only` | not-applicable | `feat/omniroute-gitlawb-zero-integration` | — | — | — | not-in-catalog | SHA `8e266797`; release `v0.6.0`; provider custom `/v1`, Bearer, `auto`, Chat/SSE/tools, usage e `/v1/models` confirmados; Go test/vet/fmt e smoke verdes; release build bloqueado por falta de espaco; politica exige issue aprovada; sem contribuicao nominal artificial |
| CLI-017 | P1 | DeepSeek Reasonix | `esengine/DeepSeek-Reasonix` | concluida | `config-only` | not-applicable | `feat/omniroute-deepseek-reasonix-integration` | — | — | — | not-in-catalog | SHA `1c62489d`; release `v1.19.1`; `kind=openai`, `/v1/chat/completions`, Bearer, `auto`, SSE/tools, `/v1/models` e reasoning confirmados; suite completa, vet, fmt, build e smoke verdes apos remover env SSH do runner; sem PR/issue redundante |
| CLI-018 | P1 | KlaatCode | `KlaatAI/klaatcode` | concluida | `config-only` | not-applicable | `feat/omniroute-klaatcode-integration` | — | — | — | not-in-catalog | SHA `0d20f24a`; release `V2.4.0`; `customModels` com `/v1`, Bearer, `auto`, Chat/SSE/tools confirmados; 316 testes, 33 fixtures e build verdes; typecheck local divergiu do CI verde; custom endpoint e apenas TUI; divergencia de metadata de licenca registrada; sem contribuicao nominal artificial |
| CLI-019 | P1 | CodeMini CLI | `havingautism/Codemini-CLI` | concluida | `config-only` | not-applicable | `feat/omniroute-codemini-cli-integration` | — | — | — | not-in-catalog | SHA `a3764b21`; package `0.8.3`; gateway `/v1`, Bearer persistido, `auto`, Chat/SSE/usage/tools e tool round trip confirmados; `/models` e probe, nao picker; 122/123 testes, 10 focados e pack-imports verdes; sem PR nominal redundante |
| CLI-020 | P1 | Zot | `patriceckhart/zot` | concluida | `config-only` | not-applicable | `feat/omniroute-zot-integration` | — | — | — | not-in-catalog | SHA `f3d8eb66`; release `v0.3.29`; custom provider `omniroute` em `models.json`, `/v1`, Bearer, `auto`, Chat/SSE/tools/reasoning opt-in e cache usage confirmados; `--base-url` e so override; PR #36 ja cita OmniRoute; race suite/build/vet/fmt verdes |
| CLI-021 | P1 | Octomind | `Muvon/octomind` | concluida | `config-only` | not-applicable | `feat/omniroute-octomind-integration` | — | — | — | not-in-catalog | SHA `65ab1db1`; release `0.39.0`; provider `local:auto` usa endpoint completo `/v1/chat/completions`, Bearer opcional, Chat JSON buffered, tools/reasoning/usage; sem SSE/Responses/discovery; fmt/fetch e smokes com/sem auth verdes; suite ampla nao executada por disco/contencao |
| CLI-022 | P1 | DvalinCode | `arthurpanhku/dvalincode` | concluida | `config-only` | not-applicable | `feat/omniroute-dvalincode-integration` | — | — | — | not-in-catalog | SHA `7d42664a`; release `v0.14.1`; provider OpenAI-compatible custom com `/v1`, Bearer via env, `auto`, Chat/SSE/usage/tools e tool round trip confirmados; `provider test` bloqueado por trusted presets; issues #109/#118/#135 ja cobrem melhorias genericas; sem PR nominal |
| CLI-023 | P1 | Coro Code | `Blushyes/coro-code` | concluida | `config-only` | not-applicable | `feat/omniroute-coro-code-integration` | — | — | — | not-in-catalog | SHA `679c57af`; release `v0.0.8`; `OPENAI_BASE_URL=/v1`, Bearer, `auto`, Chat JSON e function tools/tool loop confirmados; streaming existe mas nao e usado pelo agente; sem Responses/discovery; `cargo check`/fmt bloqueados por drift preexistente; risco de LICENSE ausente; sem PR nominal |
| CLI-024 | P1 | Mini-Kode | `minmaxflow/mini-kode` | concluida | `config-only` | not-applicable | `feat/omniroute-mini-kode-integration` | — | — | — | not-in-catalog | SHA `4e7f9767`; release/tag npm `0.2.3`; provider custom por `MINIKODE_BASE_URL=/v1`, Bearer, `auto`, Chat/SSE e tools/tool loop confirmados; sem Responses/discovery/reasoning dedicado; sem PR nominal redundante |
| CLI-025 | P1 | Late CLI | `mlhher/late-cli` | concluida | `config-only` | not-applicable | `feat/omniroute-late-cli-integration` | — | — | — | not-in-catalog | SHA `26814e62`; release `v1.4.2`; `OPENAI_BASE_URL=/v1`, Bearer, `auto`, Chat/SSE/usage/reasoning_content/tools e tool round trip confirmados; probes `/props`/`/v1/models` nao sao picker; BSL 1.1/CLA; sem PR nominal |
| CLI-026 | P1 | Agentty | `1ay1/agentty` | concluida | `config-only` | not-applicable | `feat/omniroute-agentty-integration` | — | — | — | not-in-catalog | SHA `e947b26c`; release `v0.2.10`; custom host `127.0.0.1:20128`, Bearer, Chat/SSE/tools e `/v1/models` confirmados; Responses/reasoning/tool round trip dinamico nao confirmados; MIT; sem PR nominal |
| CLI-027 | P1 | Aizen | `aizen-stack/aizen` | concluida | `config-only` | not-applicable | `feat/omniroute-aizen-integration` | — | — | — | not-in-catalog | SHA `3d8ae0f6`; release `v0.5.4`; `AIZEN_BASE_URL=/v1`, Bearer, `auto`/modelo literal, Chat/SSE/reasoning_content e `/v1/models`; tools confirmadas estaticamente, sem smoke dinamico; PolyForm Noncommercial/CLA; sem PR nominal |
| CLI-028 | P1 | Clif-Code | `DLhugly/Clif-Code` | concluida | `config-only` | not-applicable | `feat/omniroute-clif-code-integration` | — | — | — | not-in-catalog | SHA `282a787a`; release `v1.72.0`; `CLIFCODE_API_URL=/v1`, Bearer, `auto`, Chat/SSE/usage/tools e tool loop confirmados por fonte; smoke bloqueado por binario ausente; sem Responses/reasoning; licença proprietária conflitante com FSL declarada exige revisão jurídica; sem PR nominal |
| CLI-029 | P1 | Minacode | `hit9/minacode` | concluida | `config-only` | not-applicable | `feat/omniroute-minacode-integration` | — | — | — | not-in-catalog | SHA `d4ea4a97`; release `v0.18.1`; TOML custom `/v1`, key obrigatória, `auto`, Chat/Responses/Anthropic, SSE/tools/reasoning/discovery confirmados; smoke de protocolo Chat+Responses+models e compileall verdes; CI remoto verde; sem PR nominal |
| CLI-030 | P1 | YottaCode | `yottadynamics/yottacode` | concluida | `config-only` | not-applicable | `feat/omniroute-yottacode-integration` | — | — | — | not-in-catalog | SHA `039f61ce`; release `v0.3.1`; provider `openai-compatible`, `/v1`, Bearer, `/v1/models`, Chat/SSE/tools/reasoning parsing confirmados; smoke oficial com mock passou; Go 1.26 nao instalado e gates completos nao executados por espaco; sem PR nominal |
| CLI-031 | P1 | aichat | `sigoden/aichat` | concluida | `config-only` | not-applicable | `feat/omniroute-aichat-integration` | — | — | — | not-in-catalog | SHA `82976d3`; package/release `v0.30.0`; provider `openai-compatible` com base `/v1`, Bearer opcional e modelo `auto`; Chat stream/JSON, reasoning e tool round-trip confirmados; Responses ausente (#1431); limites de tool SSE ja cobertos por #1454/#1495 e PR #1496; sem publicacao nominal |
| CLI-032 | P1 | ShellGPT | `TheR1D/shell_gpt` | concluida | `config-only` | not-applicable | `feat/omniroute-shellgpt-integration` | — | — | — | not-in-catalog | SHA `a082bd53`; release `1.5.1`; `API_BASE_URL=/v1`, `OPENAI_API_KEY`, `DEFAULT_MODEL=auto` e `USE_LITELLM=false`; smoke real confirmou env e `.sgptrc`, Chat/SSE e Bearer; issue #718 nao reproduz no HEAD; CI baseline vermelho por temperatura default independente; sem publicacao nominal |
| CLI-033 | P1 | Mistral Vibe | `mistralai/mistral-vibe` | concluida | `config-only` | not-applicable | `feat/omniroute-mistral-vibe-integration` | — | — | — | not-in-catalog | SHA/release `99a6efa9` / `v2.23.2`; `GenericBackend` custom com base `/v1`, Bearer, Chat/SSE, usage, tools e reasoning; smoke do binario oficial verde; #790 cobre somente discovery `/v1/models`; upstream nao aceita contribuicoes de codigo no momento; sem publicacao |
| CLI-034 | P1 | OpenSquilla | `opensquilla/opensquilla` | concluida | `config-only` | not-applicable | `feat/omniroute-opensquilla-integration` | — | — | — | not-in-catalog | `custom` com `/v1`, Bearer opcional, Chat/SSE, tools, reasoning recebido, usage e `/v1/models`; smoke provider-level verde; monitorar issue #912 do probe custom; sem publicacao nominal |
| CLI-035 | P1 | Kode CLI | `shareAI-lab/Kode-cli` | concluida | `config-only` | not-applicable | `feat/omniroute-kode-cli-integration` | — | — | — | not-in-catalog | `custom-openai` com `/v1`, discovery `/v1/models`, fallback manual, Bearer, Chat/SSE, tools/tool round-trip e persistencia; smoke runtime bloqueado por Bun/artefato ausente; CI baseline vermelho por formatacao; sem publicacao nominal |
| CLI-036 | P1 | Neovate Code | `neovateai/neovate-code` | concluida | `config-only` | not-applicable | `feat/omniroute-neovate-code-integration` | — | — | — | not-in-catalog | provider JSON custom normalizado para OpenAI-compatible, `/v1`, Bearer, Chat/SSE, tools/tool round-trip; model catalog declarado (sem discovery); smoke do pacote publicado verde; sem publicacao nominal |
| CLI-037 | P1 | Deep Agents Code | `langchain-ai/deepagents` | concluida | `config-only` | not-applicable | `feat/omniroute-deepagents-code-integration` | — | — | — | not-in-catalog | SHA `46ee772b4`; `deepagents-code==0.1.51`; provider `openai`, base OmniRoute `/v1`, model `openai:auto`; Responses e default, Chat usa `use_responses_api=false`; smoke de config verde, sem HTTP/runtime por deps e disco; #3973/#3287 ja cobrem os pontos genericos; sem publicacao nominal |
| CLI-038 | P1 | OpenHands principal | `OpenHands/OpenHands` | concluida | `config-only` | not-applicable | `feat/omniroute-openhands-main-integration` | — | — | — | not-in-catalog | SHA `1708efc44`; Agent Canvas `1.8.0`; `openai/auto` + base `/v1` + API key + `api_mode=chat`; LiteLLM envia `model=auto`, Chat/SSE/tools estruturais; sem discovery generico `/v1/models`; PRs OmniRoute [#15189](https://github.com/OpenHands/OpenHands/pull/15189)/[#15211](https://github.com/OpenHands/OpenHands/pull/15211) fechadas sem merge; sem nova publicacao |
| CLI-039 | P1 | SWE-agent | `SWE-agent/SWE-agent` | concluida | `config-only` | not-applicable | `feat/omniroute-swe-agent-integration` | — | — | — | not-in-catalog | SHA `3ea751c08`; release `v1.1.0`; LiteLLM com `openai/<model-id>`, `api_base=/v1` e chave por env; Chat/tools/tool round-trip e batch confirmados por fonte; reasoning parcial; smoke HTTP bloqueado por deps ausentes; sem publicacao nominal |
| CLI-040 | P1 | AutoCodeRover | `AutoCodeRoverSG/auto-code-rover` | concluida | `pr-generic` | `validating` | `feat/omniroute-auto-code-rover-integration` | — | — | — | not-in-catalog | SHA `585d3e639`; patch local sem commit em 4 arquivos corrige `litellm-generic-openai/auto`, base `/v1`, precedencia da chave e pricing desconhecido; 9 testes focados com stubs, tracer source-only, compileall e diff-check verdes; sem HTTP real; licenca SONAR Source-Available exige gate juridico antes de publicar |
| CLI-041 | P2 | Claurst | `Kuberwastaken/claurst` | concluida | `config-only` | not-applicable | `feat/omniroute-claurst-integration` | — | — | — | not-in-catalog | SHA `595b0ebe3`; `custom-openai` com settings persistidos, base `/v1`, `CUSTOM_OPENAI_API_KEY`, modelo `auto`, Chat/SSE/tools e `/v1/models`; CI upstream verde; sem build/smoke local e sem publicacao nominal; monitorar PR #365 sem duplicar |
| CLI-042 | P2 | Codebuff | `CodebuffAI/codebuff` | concluida | `blocked` / `issue-first` | `blocked` | `feat/omniroute-codebuff-integration` | — | — | — | not-in-catalog | SHA `195b9bef6`; main nao expoe base/chave/provider custom na CLI/SDK; PR upstream existente [#693](https://github.com/CodebuffAI/codebuff/pull/693) cobre a lacuna, observada OPEN/CONFLICTING/DIRTY; nao criar patch concorrente; acompanhar #693 e validar apos merge/port |
| CLI-043 | P2 | Devon | `entropy-research/Devon` | concluida | `pr-generic` | validating | `feat/omniroute-devon-integration` | — | — | [upstream #100](https://github.com/entropy-research/Devon/issues/100) | not-in-catalog | SHA `8f68f1d74`; diff local genérico em 5 arquivos, sem commit; reprodução literal DeepSeek/OpenRouter e resume corrigidos; 9 testes focados, compileall e diff-check verdes; Standards/Spec aprovados; aguardar autorização antes de fork/push/PR |
| CLI-044 | P2 | Letta Code | `letta-ai/letta-code` | concluida | `config-only` | not-applicable | `feat/omniroute-letta-code-integration` | — | — | — | integrated | SHA `09aff1bb4`; já coberta pelo provider local `lmstudio` (`lmstudio_openai`), discovery `/api/v0/models``/v1/models`, Chat/SSE/tools; 8 testes OmniRoute verdes; sem PR nominal |
| CLI-045 | P2 | CodeMachine CLI | `moazbuilds/CodeMachine-CLI` | concluida | `config-only` | not-applicable | `feat/omniroute-codemachine-cli-integration` | — | — | — | not-in-catalog | SHA `572def63e`; integração indireta por OpenCode custom `@ai-sdk/openai-compatible`, base `/v1`, chave por env e `omniroute/auto`; provider/model reconhecidos no smoke de config; alternativa Claude Code; sem PR nominal |
| CLI-046 | P2 | Groq Code CLI | `build-with-groq/groq-code-cli` | concluida | `pr-generic` | `awaiting-maintainer` | `feat/omniroute-groq-code-cli-integration` | — | — | — | not-in-catalog | SHA `a303eb4be`; `groq-sdk@0.27.0` fixa `/openai/v1/chat/completions`, logo não há config-only para OmniRoute; mock confirmou path/Bearer; PR existente [#7](https://github.com/build-with-groq/groq-code-cli/pull/7) é a duplicata natural, mas precisa distinguir Groq-compatible de OpenAI-compatible; 17 testes oficiais + 5 testes de contexto, build e mock verdes; clone limpo, sem patch/publicação |
| CLI-047 | P2 | Dexto | `truffle-ai/dexto` | concluida | `config-only` | `not-applicable` | `feat/omniroute-dexto-integration` | — | — | — | not-in-catalog | SHA `4108a9c73`; provider `openai-compatible` nativo exige `baseURL`, aceita modelo arbitrário, Bearer opcional, Chat/SSE/tools e reasoning effort; receita `/v1` + `auto`; 175 testes focados e builds llm/core verdes; TS2741 em chatgpt-oauth é baseline; ELv2; sem PR/issue nominal |
| CLI-048 | P2 | claw-code-agent | `HarnessLab/claw-code-agent` | concluida | `config-only` | `not-applicable` | `feat/omniroute-claw-code-agent-integration` | — | — | — | not-in-catalog | SHA `167571da8`; `OPENAI_BASE_URL=http://127.0.0.1:20128/v1`, Bearer, model manual/`auto`, Chat/SSE/tools/usage confirmados; smoke `MOCK_SMOKE_OK`, 80 testes focados; sem discovery/Responses API; licença não identificada (`license: null`); sem PR/issue |
| CLI-049 | P2 | g3 | `dhanji/g3` | concluida | `pr-generic` | `validating` | `feat/omniroute-g3-integration` | — | — | [upstream #70](https://github.com/dhanji/g3/issues/70) | not-in-catalog | SHA `0ddb052d2`; diff local provider-neutral em `provider_registration.rs`, 1 arquivo `+25/-1`, corrige registro `custom``custom.default`; `cargo check -p g3-config`, 6 testes config e diff-check verdes; teste focal escrito mas build bloqueado em `x11.pc`; manifesto declara MIT sem arquivo LICENSE; Standards/Spec centrais aprovados; sem publicação |
| CLI-050 | P2 | San | `genai-io/san` | concluida | `config-only` | `not-applicable` | `feat/omniroute-san-integration` | — | — | — | not-in-catalog | SHA `e45ec0ef7`; Apache-2.0/release v1.22.1; provider Custom com base `/v1`, Bearer, `/models`, Chat/SSE/tools/tool result e reasoning best-effort; smoke HTTP de dois turnos e gates Go focados verdes; sem provider nominal ou publicação |
| CLI-051 | P2 | Waveloom | `Menfre01/waveloom` | concluida | `config-only` | `not-applicable` | `feat/omniroute-waveloom-integration` | — | — | — | not-in-catalog | SHA `293d5cd11`; Apache-2.0/release v0.5.1; adapter OpenAI com `/v1`, Bearer, `/models`, SSE, 14 tools, tool-result round-trip e sessões; smoke do binário oficial verde e CI remoto do HEAD verde; reasoning/cache avançados não são projetados; sem publicação |
| CLI-052 | P2 | picocode | `jondot/picocode` | concluida | `config-only` | `not-applicable` | `feat/omniroute-picocode-integration` | — | — | — | not-in-catalog | SHA `064a2a6ea`; MIT/release v0.6.0; Rig 0.28 lê `OPENAI_BASE_URL` e usa Responses `/v1/responses`; smoke confirmou Bearer, `auto`, 11 tools e function_call_output; 7 testes/doc-tests verdes; fmt/clippy só baseline; sem PR/issue |
| CLI-053 | P2 | QQCode | `qnguyen3/qqcode` | concluida | `config-only` | `not-applicable` | `feat/omniroute-qqcode-integration` | — | — | — | not-in-catalog | SHA `be6a96ce7`; Apache-2.0/release v1.2.0; provider arbitrário + `GENERIC`/OpenAI com base `/v1`; smoke confirmou JSON/SSE, Bearer, extra_body, reasoning e tool-result; backend 20/20, ACP 13+1 skip, observer 11/11, compileall/helps verdes; sem PR/issue |
| CLI-054 | P2 | Keen Code | `mochow13/keen-code` | concluida | `config-only` | `not-applicable` | `feat/omniroute-keen-code-integration` | — | — | — | not-in-catalog | SHA `ee2eaf0f4`; MIT/release v0.40.0; receita manual `openai-compatible` + `/v1` + Bearer + model arbitrário; smoke oficial confirmou Chat/SSE, tools/tool-result, usage e reasoning replay; provider oculto apenas no picker; CI remoto verde; sem PR/issue |
| CLI-055 | P2 | Grinta | `josephsenior/Grinta-Coding-Agent` | concluida | `config-only` | `not-applicable` | `feat/omniroute-grinta-integration` | — | — | — | not-in-catalog | SHA `df7437524`; provider OpenAI-compatible com `LLM_API_KEY`, model `auto`, base `/v1`; smoke Chat/SSE/tools/tool-result/reasoning/usage/cache verde; 183 testes focados, compileall e Ruff verdes; sem PR/issue nominal |
| CLI-056 | P2 | Zap | `zap-coding-agent/zap-coding-agent` | concluida | `config-only` | `not-applicable` | `feat/omniroute-zap-integration` | — | — | — | not-in-catalog | SHA `f0203f872`; provider arbitrário `kind=openai`, base `/v1`, Bearer, discovery `/models`, Chat JSON/SSE, tools/tool-result, reasoning e usage confirmados; cargo check + 16 testes/gates focados verdes; issue #2 confirma arquitetura; sem PR nominal |
| CLI-057 | P2 | Binharic | `CogitatorTech/binharic-cli` | concluida | `pr-generic` | `validating` | `feat/omniroute-binharic-integration` | — | — | — | not-in-catalog | SHA `52ccca70b`; patch sem commit em `provider.ts` + teste: aplica `baseURL` ao OpenAI/Anthropic e usa Chat Completions para base customizada; RED→GREEN, 14 focal, 88 arquivos/774 testes, typecheck/build e smoke wire verdes; lint upstream bloqueado; sem publicação |
| CLI-058 | P2 | Darce | `AmerSarhan/darce-cli` | concluida | `config-only` | `not-applicable` | `feat/omniroute-darce-integration` | — | — | — | not-in-catalog | SHA `1b90c379a`; MIT declarada no package/npm sem arquivo LICENSE; `DARCE_API_BASE` raiz sem `/v1`, `DARCE_API_KEY`, `DARCE_MODEL=auto`; smoke PTY do binário confirmou 2 Chat/SSE, 7 tools, tool-result e Bearer; 106 testes/build verdes; sem MCP/ACP/A2A; sem PR/issue |
| CLI-059 | P2 | CLAII | `agencyswarm/CLAII` | concluida | `pr-generic` | `blocked` | `feat/omniroute-claii-integration` | — | — | — | not-in-catalog | SHA `89d42311b`; patch sem commit em README/config/providers/test: `CLAII_API_KEY`, `CLAII_BASE_URL` origem sem `/v1beta`, model runtime e reject explícito; 4 wire/loop + 10 calculator + pip install + smoke CLI verdes; unittest discover falha só baseline `calculator`/`pkg`; sem MCP/ACP/A2A; **All Rights Reserved**, não publicar sem autorização jurídica |
| CLI-060 | P2 | nori-cli | `tilework-tech/nori-cli` | concluida | `config-only` | `not-applicable` | `feat/omniroute-nori-cli-integration` | — | — | — | not-in-catalog | SHA `829ecf3fd`; Apache-2.0/v0.24.0; Nori custom ACP → OpenCode `opencode-ai@1.18.11` → OmniRoute `/v1`; MCP separado por `/api/mcp/stream` ou stdio; 5 testes focados, cargo build nori e smoke ACP Nori→OpenCode verdes; sem patch/publicação |
| CLI-061 | P2 | cursor-agent clone | `civai-technologies/cursor-agent` | concluida | `config-only` | `not-applicable` | `feat/omniroute-cursor-agent-clone-integration` | — | — | — | not-in-catalog | SHA `d21a8f3d4`; MIT/v0.1.39; SDK OpenAI usa base `/v1`, Anthropic usa raiz; smokes de 2 turnos/tools verdes; factory rejeita `auto` puro; 23 testes, mypy/build verdes; sem patch/publicação |
| CLI-062 | P2 | Free Code | `freecodexyz/free-code` | concluida | `config-only` | `blocked` | `feat/omniroute-free-code-integration` | — | — | [upstream #20](https://github.com/freecodexyz/free-code/issues/20) | not-in-catalog | SHA `6b25ab68b`; URL antiga `paoloanzn/free-code` redireciona; base Anthropic raiz, `model=auto`, stream/tools/MCP; build verde; sem LICENSE/campo license e código atribuído à Anthropic, não publicar |
| CLI-063 | P2 | Claude Engineer | `Doriandarko/claude-engineer` | concluida | `config-only` / `pr-generic` | `blocked` | `feat/omniroute-claude-engineer-integration` | — | [upstream #250](https://github.com/Doriandarko/claude-engineer/pull/250) | [upstream #116](https://github.com/Doriandarko/claude-engineer/issues/116) | not-in-catalog | SHA `0a9e4b309`; v3 funciona por base Anthropic raiz com modelo fixo; #250 já adiciona `ANTHROPIC_MODEL`; arquivo LICENSE ausente apesar de declaração MIT; sem patch concorrente/publicação |
| CLI-064 | P2 | Smol Developer | `smol-ai/developer` | concluida | `config-only` | `not-applicable` | `feat/omniroute-smol-developer-integration` | — | — | — | not-in-catalog | SHA `a6747d1a6`; `OPENAI_API_BASE=/v1`, `auto`, 3 Chat calls, SSE/function calling e Agent Protocol validados; gates de runtime verdes, build metadata preexistente; sem patch/publicação |
| CLI-065 | P2 | Agentless | `OpenAutoCoder/Agentless` | concluida | `config-only` | `not-applicable` | `feat/omniroute-agentless-integration` | — | — | — | not-in-catalog | SHA `5ce5888b9`; OpenAI chat + embeddings funcionam com bases distintas; Anthropic normal/cache histórico validados; DeepSeek fixa host; pre-commit/compileall verdes; sem patch/publicação |
| CLI-066 | P2 | Amazon Q Developer CLI | `aws/amazon-q-developer-cli` | concluida | `viable-mcp` / `needs-wrapper` | `not-applicable` | `feat/omniroute-amazon-q-developer-cli-integration` | — | — | — | not-in-catalog | SHA `15cc8f3cd`; modelo usa AWS JSON/EventStream Bearer/SigV4 e não `/v1`; MCP stdio imediato, HTTP legado com ressalva; upstream issue-first/manutenção crítica; sem patch/publicação |
| CLI-067 | P2 | nanobot | `HKUDS/nanobot` | concluida | `config-only` | `not-applicable` | `feat/omniroute-nanobot-integration` | — | — | — | not-in-catalog | HEAD `44b7e1bf4`; provider dinâmico OpenAI-compatible com base `/api/v1` e modelo `omniroute/auto`; Chat/SSE/tools/reasoning/usage/images/discovery e retry validados; 424 testes + Ruff; sem PR nominal |
| CLI-068 | P2 | ZeroClaw | `zeroclaw-labs/zeroclaw` | concluida | `config-only` | `not-applicable` | `feat/omniroute-zeroclaw-integration` | — | — | — | not-in-catalog | HEAD `4770420ab`; `custom.omniroute`, base `/v1`, Bearer, `auto`, Chat/Responses e tools nativas opt-in; 1.173 unit + 1 integração, fmt/config/smoke verdes; sem PR nominal |
| CLI-069 | P2 | NanoClaw | `gavrielc/nanoclaw` | concluida | `config-only` | `not-applicable` | `feat/omniroute-nanoclaw-integration` | — | — | — | not-in-catalog | HEAD `dfac7e0af`; provider Claude existente aponta para raiz Anthropic OmniRoute e OneCLI guarda a chave; baseline e 49 testes OmniRoute verdes; Codex #3155/#1984 e OpenCode #2985 ficam como follow-ups; sem PR |
| CLI-070 | P2 | PicoClaw | `sipeed/picoclaw` | concluida | `config-only` | `not-applicable` | `feat/omniroute-picoclaw-integration` | — | — | — | not-in-catalog | HEAD `49183d7`, `/api/v1`, `openai/auto``auto`; Chat/SSE/tools/usage/images/discovery; Go ausente, testes locais não executados; issue router #3298; sem publicação |
| CLI-071 | P2 | IronClaw | `nearai/ironclaw` | concluida | `config-only` | `not-applicable` | `feat/omniroute-ironclaw-integration` | — | — | — | not-in-catalog | HEAD `4b71aaae`; `openai_compatible` `/api/v1`, Chat/SSE/tools/images/discovery; 889+5 testes e fmt verdes; reasoning #3673; sem publicação |
| CLI-072 | P2 | NullClaw | `nullclaw/nullclaw` | concluida | `config-only` | `not-applicable` | `feat/omniroute-nullclaw-integration` | — | — | — | not-in-catalog | HEAD `d8a802fd`; custom `/api/v1`, Chat/Responses/Anthropic, tools/streaming/usage/images; Zig ausente, CI run 30788444193 verde; sem publicação |
| CLI-073 | P2 | Moltis | `moltis-org/moltis` | concluida | `config-only` | `not-applicable` | `feat/omniroute-moltis-integration` | — | — | — | not-in-catalog | HEAD `678d407`; `custom-omniroute`, `/api/v1`, `auto`, Chat/SSE/tools/reasoning/usage/images; 401 testes + fmt verdes; MCP/ACP separados; sem publicação |
| CLI-074 | P2 | GitClaw | `open-gitagent/gitclaw` | concluida | `config-only` | `not-applicable` | `feat/omniroute-gitclaw-integration` | — | — | — | not-in-catalog | GitAgent HEAD `d3e25d7`; base `/api/v1`, `omniroute:auto`, Chat/SSE/tools/images; build + 65 testes + smoke verdes; reasoning=false no descriptor; sem publicação |
| CLI-075 | P2 | LionClaw | `moshthepitt/lionclaw` | concluida | `patch-required` / `issue-first` | `awaiting-maintainer` | `feat/omniroute-lionclaw-integration` | — | — | — | not-in-catalog | HEAD `cb59b23d`; Codex app-server não projeta config.toml/secret para runtime confinado; patch seguro necessário, alinhado à #157; gates locais bloqueados por uv/podman; CI verde; sem publicação |
| CLI-076 | P3 | VibePod | `VibePod/vibepod-cli` | concluida | `config-only` | `not-applicable` | `feat/omniroute-vibepod-integration` | — | — | — | not-in-catalog | Claude Code via `/api`, container usa `host.docker.internal`; Codex não injeta chave; compileall verde, pytest bloqueado por typer; sem publicação |
| CLI-077 | P3 | zeroshot | `the-open-engine/zeroshot` | concluida | `config-only` | `not-applicable` | `feat/omniroute-zeroshot-integration` | — | — | — | not-in-catalog | Gateway OpenAI `/api/v1`, `auto`, tools fail-closed; 22 testes + build verdes; sem streaming JSON/reasoning/MCP no gateway; sem publicação |
| CLI-078 | P3 | Fractal | `plasma-ai/fractal` | concluida | `config-only` / `needs-wrapper` | `awaiting-maintainer` | `feat/omniroute-fractal-integration` | — | — | — | not-in-catalog | Codex Responses por node `CODEX_HOME`; caveat tmux quente não encaminha `OMNIROUTE_API_KEY`; fix genérico recomendado, sem PR |
| CLI-079 | P3 | Bernstein | `chernistry/bernstein` | concluida | `config-only` | `not-applicable` | `feat/omniroute-bernstein-integration` | — | — | — | not-in-catalog | Canonical `sipyourdrink-ltd/bernstein`; openai_agents `/api/v1`, auto, api_key_env allowlisted; testes bloqueados por openai ausente; sem publicação |
| CLI-080 | P3 | Traycer | `traycerai/traycer` | concluida | `config-only` indireto | `not-applicable` | `feat/omniroute-traycer-integration` | — | — | — | not-in-catalog | Harness OpenCode + provider `@ai-sdk/openai-compatible`, `/api/v1`, `omniroute/auto`; host central fechado; sem publicação |
| CLI-081 | P3 | h5i | `h5i-dev/h5i` | concluida | `patch-required` | `awaiting-maintainer` | `feat/omniroute-h5i-integration` | — | — | — | not-in-catalog | Auth proxy/egress Codex fixos em OpenAI anulam base custom; patch seguro/policy-pinned necessário; CI externa verde; sem publicação |
| CLI-082 | P3 | OMK | `dmae97/open-multi-agent-kit` | concluida | `viable-mcp` | `not-applicable` | `feat/omniroute-omk-integration` | — | — | — | not-in-catalog | pesquisa concluída neste lote; controle multiagente, MCP é caminho primário; sem provider nominal |
| CLI-083 | P3 | kodo | `ikamensh/kodo` | concluida | `config-only` indireto | `not-applicable` | `feat/omniroute-kodo-integration` | — | — | — | not-in-catalog | pesquisa concluída neste lote; orquestrador/agent child, propagar env/base/model ao agente filho |
| CLI-084 | P3 | ORCH | `oxgeneral/ORCH` | concluida | `needs-wrapper` | `awaiting-maintainer` | `feat/omniroute-orch-integration` | — | — | — | not-in-catalog | pesquisa concluída neste lote; fila/controle sem provider LLM direto, wrapper/adaptador necessário |
| CLI-085 | P3 | LoopTroop | `LoopTroop-ai/LoopTroop` | concluida | `config-only` indireto | `not-applicable` | `feat/omniroute-looptroop-integration` | — | — | — | not-in-catalog | HEAD `cbfc81c5`; OpenCode recebe provider `@ai-sdk/openai-compatible`, `/api/v1`, `omniroute/auto`; 16 testes verdes; sem publicação |
| CLI-086 | P3 | Galley | `shinpr/galley` | concluida | `patch-required` | `awaiting-maintainer` | `feat/omniroute-galley-integration` | — | — | — | not-in-catalog | HEAD `6bcc593d`; registry/transports fechados, requer transport OpenAI-compatible para executor e supervisor; Go ausente; sem publicação |
| CLI-087 | P3 | Relay | `jcast90/relay` | concluida | `config-only` | `not-applicable` | `feat/omniroute-relay-integration` | — | — | — | not-in-catalog | HEAD `7bd5a2f6`; provider profile Codex com `OPENAI_BASE_URL`, key ref e modelo; smoke Responses obrigatório; MCP separado; sem publicação |
| CLI-088 | P3 | SageCLI | `youwangd/SageCLI` | concluida | `config-only` indireto | `not-applicable` | `feat/omniroute-sagecli-integration` | — | — | — | not-in-catalog | HEAD `c167712d`; Codex runtime, base/key configuradas fora do Sage; env plaintext caveat; 45 testes verdes; sem publicação |
| CLI-089 | P3 | 5dive | `5dive-ai/5dive` | concluida | `patch-required` | `awaiting-maintainer` | `feat/omniroute-5dive-integration` | — | — | — | not-in-catalog | HEAD `b64b6dac`; provider/base maps fechados; patch OpenAI-compatible genérico; 50 testes focados verdes; sem publicação |
| CLI-090 | P3 | agx | `ramarlina/agx` | concluida | `config-only` indireto | `not-applicable` | `feat/omniroute-agx-integration` | — | — | — | not-in-catalog | HEAD `e674cec1`; Codex herda base/key/model; smoke Responses e governança `--full-auto`; Jest ausente; sem publicação |
| CLI-091 | P3 | claude-code-router | `musistudio/claude-code-router` | concluida | `config-only` | `not-applicable` | `feat/omniroute-claude-code-router-integration` | — | — | — | not-in-catalog | HEAD `bc8a8e62`; provider custom OpenAI/Anthropic/Gemini, Chat/Responses; smoke por protocolo; sem publicação |
| CLI-092 | P3 | cc-router | `finch-xu/cc-router` | concluida | `config-only` | `not-applicable` | `feat/omniroute-cc-router-integration` | — | — | — | not-in-catalog | HEAD `c4c7579`; custom Responses/Chat com base/path/header, SSE/tools/reasoning; cargo bloqueado por glib; sem publicação |
| CLI-093 | P3 | OneCLI | `onecli/onecli` | concluida | `config-only` | `not-applicable` | `feat/omniroute-onecli-integration` | — | — | — | not-in-catalog | HEAD `84ccaf74`; MITM credential gateway, generic host injection; MCP separado; sem publicação |
| CLI-094 | P3 | agent-browser | `vercel-labs/agent-browser` | concluida | `config-only` | `not-applicable` | `feat/omniroute-agent-browser-integration` | — | — | — | not-in-catalog | HEAD `01c1147d`; chat usa gateway Chat/SSE/tools com env key/model; base precisa validar sufixo `/v1` para não duplicar path; cargo test exit 0; sem publicação |
| CLI-095 | P3 | OpenWork | `different-ai/openwork` | concluida | `config-only` indireto | `not-applicable` | `feat/omniroute-openwork-integration` | — | — | — | not-in-catalog | HEAD `ecb7a5f0`; OpenCode custom provider `/api/v1`, auth gerenciada; sem testes/deps; sem publicação |
| CLI-096 | P3 | Agent Deck review | `asheshgoplani/agent-deck` | concluida | `config-only` indireto | `not-applicable` | `feat/omniroute-agent-deck-review` | — | — | — | integrated | HEAD `46300807`; env/model propagados a Codex/OpenCode; Go ausente; sem publicação |
| CLI-097 | P4 | Pool | `poolsideai/pool` | concluida | `config-only` | `not-applicable` | `feat/omniroute-pool-integration` | — | — | — | not-in-catalog | HEAD `a6fe0ca1`; `pool exec --api-url` OpenAI-compatible, sandbox required, MCP/ACP separado; EULA; sem publicação |
| CLI-098 | P4 | Junie CLI | `junie.jetbrains.com` | concluida | `config-only` | `not-applicable` | `feat/omniroute-junie-integration` | — | — | — | not-in-catalog | HEAD `d2701be6`; custom profile OpenAICompletion/Responses com baseUrl full e env ref; runtime proprietário/EAP; sem publicação |
| CLI-099 | P4 | Cursor desktop | Anysphere | concluida | `config-only` limitado | `awaiting-maintainer` | `feat/omniroute-cursor-desktop-integration` | — | — | — | integrated | disclosure-only; BYO key/chat panel; Composer/Tab nativos; privado/MITM proibido; sem publicação |
| CLI-100 | P4 | Windsurf | Codeium | concluida | `blocked-closed` / MCP-only | `awaiting-maintainer` | `feat/omniroute-windsurf-integration` | — | — | — | not-in-catalog | sem upstream/base custom; BYOK Anthropic específico; MCP separado; MITM proibido; sem publicação |
| CLI-101 | P4 | Amp | Sourcegraph | concluida | `config-only` parcial / Enterprise-gated | `awaiting-maintainer` | `feat/omniroute-amp-integration` | — | — | — | not-in-catalog | CLI fechada/Amp Server; confirmar provider custom com suporte; MCP viável; sem publicação |
| CLI-102 | P4 | Amazon Q/Kiro CLI | AWS | concluida | `patch-required` legado / `blocked-closed` Kiro | `awaiting-maintainer` | `feat/omniroute-amazon-q-integration` | — | — | — | integrated | Q usa AWS EventStream/SigV4; Kiro fechado sem base custom; MCP-only seguro; sem publicação |
| CLI-103 | P4 | Cowork | Anthropic | concluida | `blocked-closed` / MCP-only | `not-applicable` | — | — | — | — | not-in-catalog | inferência gerida pela Anthropic sem BYOK/base custom; Custom Connector MCP remoto; MITM proibido; sem publicação |
## Como atualizar
Ao terminar uma fase, alterar somente os campos comprovados e deixar os demais como `—`. Para uma integracao concluida, registrar: versao/commit pesquisado, mecanismo, arquivos modificados, testes, branch, commit, URL de PR/issue e resposta do mantenedor. Se o caso for apenas configuracao, registrar o comando/config real e marcar `config-only` ou `viable-direct`, sem criar uma PR artificial.
Antes de publicar uma contribuicao, aplicar o gate e o checklist de
`05-plano-publicacao-prs-upstream.md`.

View File

@@ -1,659 +0,0 @@
# Plano de publicacao de integracoes OmniRoute nos repositorios upstream
> **Status da campanha de pesquisa:** `104/104` casos concluídos. Este plano continua sendo o procedimento de execução e publicação. A matriz final, inclusive os casos em que PR é inadequada ou impossível, está em `06-relatorio-final-104-clis-e-estrategia-prs.md`.
**Data:** 2026-08-01
**Escopo:** transformar a fila `CLI-000` a `CLI-103` em contribuicoes upstream verificadas,
publicando PR, issue, guia de configuracao, adaptador ou conclusao de bloqueio conforme o mecanismo
real de cada projeto.
**Documentos-base:** `01-relatorio-pesquisa-clis-omniroute.md`,
`02-prioridade-integracoes-clis.md`, `03-plano-integracao-em-lotes.md` e
`04-tracker-integracoes-clis.md`.
## 1. Resultado esperado
Para cada repositorio pesquisado, a campanha deve produzir exatamente um resultado principal:
1. **PR upstream de integracao nominal:** adiciona provider/preset `omniroute`, configuracao,
documentacao e testes quando isso combina com a arquitetura do projeto.
2. **PR upstream de compatibilidade generica:** melhora suporte a endpoint customizado sem acoplar
o projeto ao nome OmniRoute, acompanhado de documentacao comprovando o uso com OmniRoute.
3. **PR somente de documentacao:** registra uma configuracao funcional quando o codigo ja suporta
OmniRoute e o upstream aceita guias de terceiros.
4. **Issue-first:** solicita decisao de arquitetura ou permissao antes do patch quando a politica do
repositorio, o desenho de providers ou o tamanho da mudanca exigirem alinhamento.
5. **Configuracao sem PR:** documenta no OmniRoute um fluxo que ja funciona e para o qual uma mudanca
upstream seria redundante ou rejeitada pela politica do projeto.
6. **Adaptador ACP/MCP/wrapper:** contribui no ponto de extensao correto quando o projeto nao consome
diretamente APIs de modelos.
7. **MITM, produto fechado ou bloqueado:** registra evidencia e nao fabrica uma contribuicao que o
upstream nao pode receber.
O objetivo e tentar integrar todos os casos tecnicamente possiveis. O objetivo nao e abrir uma PR em
todo repositorio independentemente da arquitetura, licenca ou politica de contribuicao.
## 2. Regras da campanha
- Trabalhar em lotes de no maximo tres repositorios, com um subagente por repositorio.
- Usar uma worktree isolada por repositorio dentro de `.claude/worktrees/`.
- Nao editar implementacoes no checkout compartilhado.
- Nao usar `git stash` ou `git pop`.
- Fazer pesquisa fresca no commit atual do upstream antes de criar branch ou editar arquivos.
- Ler `README`, `CONTRIBUTING`, templates de issue/PR, `SECURITY`, licenca e instrucoes locais de
agentes antes da implementacao.
- Procurar issues e PRs abertas/fechadas sobre custom provider, base URL, OpenAI-compatible,
Anthropic-compatible, Gemini endpoint, proxy, gateway e OmniRoute antes de propor uma mudanca.
- Registrar a base pesquisada por commit SHA ou release. Nao usar apenas `main` como evidencia.
- Executar baseline antes da mudanca e distinguir falhas preexistentes de regressao.
- Nunca expor `OMNIROUTE_API_KEY` ou qualquer outra credencial em comandos publicados, fixtures,
logs, commits, screenshots, PRs ou issues.
- Nao inserir trailers, assinaturas ou rodapes de IA em commits, PRs ou issues.
- Nao afirmar que uma integracao funciona sem um teste reproduzivel ou uma limitacao explicitamente
registrada.
- Nao inventar fork, branch, commit, PR, issue, CI ou resposta de mantenedor.
- Atualizar `04-tracker-integracoes-clis.md` ao concluir cada fase material.
## 3. Unidade de trabalho por repositorio
Cada item `CLI-NNN` deve possuir uma task individual. A task e o pacote de contexto entregue ao
subagente e o registro que permite retomar o trabalho sem repetir ou perder evidencias.
### 3.1 Cabecalho obrigatorio da task
```md
# CLI-NNN - <projeto> - integracao OmniRoute upstream
- Repositorio canonico: <URL>
- Prioridade/lote: <P0-P4 / lote>
- Estado no catalogo OmniRoute: <integrated/not-in-catalog/parcial>
- Evidencia inicial: <resumo vindo do relatorio; ainda nao confirmado>
- Worktree: <caminho isolado>
- Branch planejada: <definir somente depois de ler as regras upstream>
- Commit/release pesquisado: —
- Responsavel: <agente>
- Estado: researching
```
### 3.2 Pesquisa obrigatoria dentro da task
O subagente deve responder, com links e caminhos de codigo:
1. Qual e o repositorio canonico, commit/release atual, licenca e nivel de atividade?
2. Contribuicoes de forks externos sao aceitas? Ha CLA, DCO, sign-off ou issue previa obrigatoria?
3. Qual e a arquitetura de providers e qual e o menor ponto de extensao?
4. O cliente usa Chat Completions, Responses, Anthropic Messages, Gemini, ACP, MCP ou protocolo
proprietario?
5. A base URL esperada e raiz, `/v1`, `/v1beta` ou uma URL completa por operacao?
6. O cliente acrescenta algum sufixo automaticamente? Pode duplicar `/v1` ou `/v1beta`?
7. Como a autenticacao e resolvida: variavel de ambiente, arquivo, keyring, OAuth ou header custom?
8. Como os modelos sao definidos ou descobertos? O cliente chama um endpoint de modelos?
9. Streaming, tool calling, reasoning, imagens e cancelamento funcionam pelo caminho escolhido?
10. Ja existe issue, PR, discussao ou documentacao para endpoints customizados ou OmniRoute?
11. Quais comandos oficiais executam install, format, lint, typecheck, build e testes?
12. Qual contribuicao agrega valor real: codigo nominal, compatibilidade generica, docs, issue,
wrapper, MCP/ACP, somente configuracao ou nenhum patch?
### 3.3 Gate de contribuicao
Antes de editar, preencher uma decisao:
| Decisao | Quando usar | Saida esperada |
|---|---|---|
| `pr-provider` | O upstream possui catalogo/presets de providers | Provider/preset OmniRoute, docs e testes |
| `pr-generic` | Falta uma capacidade generica necessaria, como base URL customizavel | Patch generico, docs e teste com OmniRoute |
| `pr-docs` | O codigo ja funciona e o upstream aceita guias de integracao | Guia minimo e validado |
| `issue-first` | Mudanca arquitetural, politica incerta ou mantenedor exige proposta | Issue com evidencia e desenho do patch |
| `config-only` | Tudo funciona por configuracao e um PR seria redundante | Guia no OmniRoute e smoke test |
| `adapter-acp` | ACP e o ponto real de integracao | Adaptador/registro ACP e testes |
| `adapter-mcp` | MCP e o ponto real de integracao | Config/servidor MCP e testes |
| `wrapper` | O projeto apenas lanca outro agente | Wrapper/env forwarding e teste do filho |
| `needs-mitm` | Endpoint fechado ou fixo | Pesquisa/guia MITM separado; sem PR artificial |
| `blocked` | Licenca, politica, build ou protocolo impedem progresso | Evidencia reproduzivel e proximo desbloqueio |
O gate deve incluir a alternativa rejeitada. Exemplo: `pr-provider` escolhido porque o repositorio
mantem presets nomeados; `pr-docs` rejeitado porque a configuracao exigiria cinco campos internos e
nao seria uma experiencia suportada.
## 4. Ciclo completo da PR
### Fase PR-0 - Preparar o contexto
- Reservar o item no tracker e marcar pesquisa em andamento.
- Confirmar que nenhum outro agente esta trabalhando no mesmo repositorio.
- Resolver o repositorio canonico, fork existente e permissao de contribuicao.
- Criar a task individual com a evidencia inicial marcada como hipotese.
- Criar a worktree isolada somente depois de confirmar o upstream correto.
### Fase PR-1 - Pesquisar upstream e contribuicoes existentes
- Ler integralmente as regras do repositorio aplicaveis aos arquivos que podem mudar.
- Mapear provider registry, configuracao, transporte HTTP, auth, modelo, streaming e ferramentas.
- Pesquisar issues/PRs por termos de compatibilidade e pelo nome OmniRoute.
- Registrar commit/release, caminhos e links de evidencia na task.
- Escolher o gate de contribuicao da secao 3.3.
### Fase PR-2 - Baseline reproduzivel
- Instalar dependencias de acordo com o upstream.
- Rodar format check, lint, typecheck/build e testes relevantes antes do patch.
- Rodar um smoke test do caminho existente, mesmo que ele falhe por falta da integracao.
- Limpar chaves do ambiente nos testes que validem o comportamento sem credenciais.
- Registrar comando, codigo de saida, testes aprovados e falhas preexistentes.
- Se o projeto nao puder ser construido, tentar o ambiente documentado e registrar o bloqueio; nao
declarar regressao nem compatibilidade com base apenas na leitura do README.
### Fase PR-3 - Desenhar o menor patch aceitavel
A ordem de preferencia e:
1. Reusar a abstracao de provider ja existente.
2. Adicionar metadados/preset antes de criar codigo especial.
3. Reusar cliente OpenAI/Anthropic/Gemini ja presente.
4. Adicionar capacidade generica quando ela beneficiar outros gateways e for coerente com o projeto.
5. Criar executor/adapter dedicado somente quando o protocolo realmente divergir.
O patch normalmente deve cobrir:
- identificador e nome de exibicao `omniroute`, se presets nomeados forem aceitos;
- base URL correta e sem dupla concatenacao de versao;
- chave obtida de ambiente ou storage seguro;
- configuracao/descoberta de modelo;
- headers estritamente necessarios;
- streaming e tool calling preservados;
- mensagens de erro sem expor segredo;
- documentacao curta e executavel;
- testes unitarios/integracao alinhados ao padrao upstream.
Nao adicionar telemetria, dependencia, fluxo de login ou codigo de rede novo quando o provider
generico existente ja resolve o caso.
### Fase PR-4 - Implementar com teste primeiro
- Criar teste que demonstre a ausencia do preset, config ou comportamento requerido.
- Confirmar a falha pelo motivo esperado.
- Implementar o menor patch.
- Fazer o teste passar e executar testes adjacentes.
- Refatorar apenas o necessario para manter o padrao do upstream.
- Formatar somente os arquivos tocados, salvo exigencia contraria do repositorio.
Para PR somente de documentacao, substituir o teste vermelho por uma validacao real dos comandos e
do arquivo de configuracao documentado. Nao sintetizar exemplos que nao foram executados.
### Fase PR-5 - Validar contra OmniRoute
Escolher a matriz compativel com o cliente:
| Superficie | Base inicial esperada | Validacoes minimas |
|---|---|---|
| OpenAI Chat Completions | confirmar se o cliente espera raiz ou `/v1` | chamada simples, stream, tool call, erro de modelo |
| OpenAI Responses | confirmar regra de concatenacao do cliente | resposta simples, stream/eventos, tool call |
| Anthropic Messages | normalmente base antes de `/v1/messages`; confirmar no codigo | mensagem, stream, tools, headers de versao |
| Gemini | normalmente base antes das operacoes `v1beta`; confirmar no codigo | generateContent, streamGenerateContent, tools |
| ACP | endpoint/transport definido pelo protocolo | discovery, sessao, request e cancelamento |
| MCP | stdio, SSE ou Streamable HTTP conforme suporte | inicializacao, listagem e invocacao de ferramenta |
Registrar no resultado quais linhas da matriz foram executadas, omitidas ou bloqueadas. Um smoke
test simples nao deve ser apresentado como prova de tool calling ou streaming.
### Fase PR-6 - Revisar o diff antes de publicar
O agente responsavel faz uma auto-revisao e o agente principal verifica:
- aderencia a `CONTRIBUTING` e instrucoes locais;
- escopo minimo e ausencia de refactor oportunista;
- testes cobrindo config, URL, auth sem segredo e modelo;
- documentacao consistente com o codigo executado;
- ausencia de arquivos gerados, caches, logs ou credenciais;
- licenca e atribuicao preservadas;
- branch baseada no upstream atual;
- commits pequenos e com mensagem no estilo do projeto;
- ausencia de trailers ou texto de IA;
- `git diff --check` e gates oficiais limpos, ou falhas preexistentes documentadas.
Uma PR nao deve ser publicada enquanto houver alteracao sem explicacao, teste essencial faltando ou
duvida material sobre a politica do upstream.
### Fase PR-7 - Preparar a publicacao
- Confirmar fork e remotes sem sobrescrever branches existentes.
- Atualizar a branch sobre o ponto exigido pelo upstream usando operacao nao destrutiva.
- Enviar a branch ao fork somente depois da revisao.
- Criar PR contra a branch correta do repositorio canonico.
- Se a contribuicao externa estiver bloqueada, abrir issue-first e anexar o commit/patch de
referencia somente quando isso for permitido.
- Registrar URLs reais no tracker imediatamente apos a publicacao.
Convencoes de branch sugeridas, sujeitas ao padrao de cada upstream:
- `feat/omniroute-provider` para provider/preset nominal;
- `feat/custom-base-url` para capacidade generica;
- `docs/omniroute-setup` para documentacao validada;
- `fix/custom-endpoint-versioning` para correcao de raiz versus `/v1`/`/v1beta`.
### Fase PR-8 - Corpo da PR
Usar o template oficial do repositorio quando existir. Na ausencia de template, adaptar:
```md
## Why
Explain the user problem and the existing extension point. Avoid marketing claims.
## What changed
- Add or enable the smallest provider/configuration path required.
- Document the verified setup.
- Cover URL, authentication and model selection behavior with tests.
## Verification
- `<official upstream command>`
- `<focused test command>`
- `<sanitized OmniRoute smoke test and result>`
## Compatibility notes
- API surface: `<Chat Completions/Responses/Anthropic/Gemini/ACP/MCP>`
- Base URL rule: `<root, /v1, /v1beta or full operation URL>`
- Streaming: `<verified/not applicable/not verified>`
- Tool calling: `<verified/not applicable/not verified>`
## Scope
No unrelated refactors or credential changes.
```
O titulo deve descrever a mudanca, nao a campanha. Exemplos de formato, sujeitos ao estilo do
upstream: `Add OmniRoute provider preset`, `Support configurable OpenAI-compatible base URLs` ou
`Document OmniRoute as a custom endpoint`.
### Fase PR-9 - Issue-first ou fallback
Quando uma PR direta nao for apropriada, a issue deve conter:
- problema reproduzivel e publico afetado;
- ponto de extensao encontrado no codigo;
- proposta minima;
- compatibilidade esperada e protocolo;
- evidencia de teste ou prototipo;
- pergunta objetiva ao mantenedor;
- link para patch de referencia apenas se permitido.
Nao abrir simultaneamente issue e PR sem necessidade. Se o template exigir issue previa, esperar a
decisao ou seguir a politica declarada.
### Fase PR-10 - Acompanhar ate a decisao
Depois da publicacao:
- observar CI e checks obrigatorios;
- responder perguntas tecnicas com evidencia;
- corrigir somente o escopo da contribuicao ou pedidos claros do mantenedor;
- reexecutar testes depois de cada mudanca;
- registrar novos commits, revisoes e estado no tracker;
- marcar `accepted` somente depois de merge/aceite comprovado;
- marcar `rejected` com o motivo fornecido pelo upstream;
- se a PR ficar inativa, registrar `awaiting-maintainer`, sem declarar abandono prematuramente;
- manter o guia/catalogo OmniRoute coerente com o estado real do upstream.
O acompanhamento pode usar a skill `babysit` individualmente para uma PR aberta. Como essa skill
acompanha uma unica PR, nunca agrupar tres PRs em uma mesma execucao dela.
### Fase PR-11 - Fechar a task
Uma task individual termina com:
- pesquisa fresca e gate registrados;
- diff, configuracao ou bloqueio documentado;
- baseline e validacao final comparados;
- branch/commit reais, quando criados;
- PR/issue reais, quando publicados;
- status no catalogo OmniRoute;
- limitacoes e proximo passo;
- linha correspondente no tracker atualizada.
## 5. Estrategia de paralelizacao
### 5.1 Papeis por lote
- **Subagente A:** primeiro repositorio do lote; dono exclusivo da worktree e do diff upstream.
- **Subagente B:** segundo repositorio do lote; dono exclusivo da worktree e do diff upstream.
- **Subagente C:** terceiro repositorio do lote; dono exclusivo da worktree e do diff upstream.
- **Agente principal:** coordena o tracker, revisa gates/diffs, impede duplicacao e autoriza a
publicacao depois das evidencias.
Todos os agentes devem ser avisados de que nao estao sozinhos no workspace e nao podem reverter ou
sobrescrever mudancas de outros agentes.
### 5.2 Barreira do lote
O lote seguinte pode comecar quando os tres itens atuais tiverem, no minimo:
1. commit/release upstream pesquisado;
2. gate de contribuicao definido;
3. baseline registrado;
4. patch validado, configuracao comprovada ou bloqueio reproduzivel;
5. decisao de publicacao tomada;
6. tracker atualizado.
A espera por resposta de mantenedor nao bloqueia o lote seguinte. Depois de uma PR/issue publicada,
o item passa para acompanhamento e libera o slot de implementacao.
### 5.3 Limite de trabalho em progresso
- No maximo tres pesquisas/implementacoes ativas.
- Publicacoes aguardando mantenedor nao contam como slot de implementacao, mas ficam no tracker.
- No maximo uma task ativa por repositorio, inclusive forks ou variantes do mesmo upstream.
- Se dois itens resolverem o mesmo repositorio, consolidar a pesquisa e decidir se ha uma ou duas
contribuicoes antes de abrir branches.
## 6. Fila de publicacao
A ordem detalhada continua sendo a do `03-plano-integracao-em-lotes.md`. Esta secao define o objetivo
de publicacao de cada onda; a pesquisa individual pode promover, rebaixar ou mudar o tipo de
contribuicao.
### Onda 0 - referencia e infraestrutura da campanha
- `CLI-000` jcode: acompanhar issue upstream e PR de referencia; concluir a secao prometida no
README do OmniRoute.
- Preparar o modelo de task individual e aplicar o mesmo tracker a todos os novos repositorios.
### Onda 1 - P0.1 a P0.5
- `CLI-001` Gemini CLI: confirmar se o endpoint Gemini customizado pede apenas docs/config ou um
preset nominal.
- `CLI-002` Claw Code: confirmar provider OpenAI-compatible e propor preset/docs minimos.
- `CLI-003` Plandex: confirmar o registro de providers customizados e propor provider/preset.
- `CLI-004` MiMo Code: confirmar o adapter OpenAI-compatible e propor configuracao/provider.
- `CLI-005` Trae Agent: confirmar `model_providers` e propor entrada OmniRoute/documentacao.
- `CLI-006` Kimi CLI: escolher uma superficie suportada e evitar um patch que misture tres
protocolos sem testes.
- `CLI-007` Every Code: reutilizar a arquitetura herdada do Codex quando ainda aplicavel.
- `CLI-008` Open Codex: confirmar upstream canonico e propor provider multi-modelo.
- `CLI-009` VT Code: validar provider customizado, modelo e failover.
- `CLI-010` OpenHands CLI: verificar se `LLM_BASE_URL` torna o caso docs/config-only.
- `CLI-011` gptme: verificar se `OPENAI_BASE_URL` torna o caso docs/config-only.
- `CLI-012` Nanocoder: confirmar compatibilidade de tool calling e decidir preset versus docs.
- `CLI-013` RA.Aid: verificar se `OPENAI_API_BASE` torna o caso docs/config-only.
- `CLI-014` CoreCoder: verificar se `OPENAI_BASE_URL` torna o caso docs/config-only.
- `CLI-015` Grok CLI: confirmar se o endpoint e genericamente configuravel ou preso ao protocolo
Grok antes de propor patch.
### Onda 2 - P1.1 a P1.9
- `CLI-016` Gitlawb Zero: provider custom/flag; preferir docs ou preset pequeno.
- `CLI-017` DeepSeek Reasonix: confirmar repositorio, atividade e endpoint antes de qualquer PR.
- `CLI-018` KlaatCode: integrar via `customModels` ou preset se o catalogo aceitar nomes.
- `CLI-019` CodeMini CLI: validar `gateway.base_url` e sua regra de versao.
- `CLI-020` Zot: validar `--base-url` e `models.json`; docs-first se ja suficiente.
- `CLI-021` Octomind: confirmar variaveis de URL por provider e propor configuracao minima.
- `CLI-022` DvalinCode: confirmar o cliente OpenAI-compatible e testes disponiveis.
- `CLI-023` Coro Code: confirmar `OPENAI_BASE_URL`; docs-first se nao houver lacuna de codigo.
- `CLI-024` Mini-Kode: confirmar `MINIKODE_BASE_URL`; docs-first se nao houver lacuna de codigo.
- `CLI-025` Late CLI: testar ambiente e flag `api-url`; corrigir precedencia apenas se necessario.
- `CLI-026` Agentty: escolher entre provider direto e ACP conforme a arquitetura atual.
- `CLI-027` Aizen: validar `AIZEN_BASE_URL` e propor docs/preset.
- `CLI-028` Clif-Code: selecionar um unico protocolo principal para a primeira contribuicao.
- `CLI-029` Minacode: pesquisa confirmatoria antes de definir o tipo de PR.
- `CLI-030` YottaCode: confirmar gateway/provider e selecao de modelo.
- `CLI-031` aichat: integrar via configuracao de modelos ou provider nominal, conforme a politica.
- `CLI-032` ShellGPT: validar `API_BASE_URL` e decidir docs/config-only.
- `CLI-033` Mistral Vibe: confirmar base URL customizada e separar suporte generico de marca.
- `CLI-034` OpenSquilla: localizar o registro de gateways e propor provider/preset.
- `CLI-035` Kode CLI: escolher OpenAI, Anthropic ou Gemini com base na implementacao mais nativa.
- `CLI-036` Neovate Code: preferir plugin/provider oficial ao patch no core, se existir.
- `CLI-037` Deep Agents Code: contribuir no pacote CLI/provider correto, nao apenas no SDK generico.
- `CLI-038` OpenHands principal: evitar duplicar `CLI-010`; consolidar se ambos apontarem para o
mesmo mecanismo e upstream.
- `CLI-039` SWE-agent: confirmar backend de modelos e interface publica suportada.
- `CLI-040` AutoCodeRover: confirmar backend e propor config/provider minimo.
- `CLI-041` Claurst: revisar GPL e politica antes de redistribuir qualquer adaptacao.
- `CLI-042` Codebuff: confirmar se o provider e extensivel e se contribuicoes externas sao aceitas.
### Onda 3 - P2.1 a P2.11
- `CLI-043` Devon, `CLI-044` Letta Code e `CLI-045` CodeMachine CLI: pesquisar backend real;
revisar a entrada local ja existente de Letta antes de nova PR.
- `CLI-046` Groq Code CLI, `CLI-047` Dexto e `CLI-048` claw-code-agent: confirmar endpoints,
protocolos e maturidade antes do patch.
- `CLI-049` g3, `CLI-050` San e `CLI-051` Waveloom: localizar a abstracao de provider e preferir
implementacao generica.
- `CLI-052` picocode, `CLI-053` QQCode e `CLI-054` Keen Code: validar configuracao multi-modelo e
documentar o caminho minimo.
- `CLI-055` Grinta, `CLI-056` Zap e `CLI-057` Binharic: escolher o provider compativel com melhor
cobertura de streaming/tools.
- `CLI-058` Darce, `CLI-059` CLAII e `CLI-060` nori-cli: separar integracao de modelo de MCP e de
codigo herdado do Codex.
Resultado P2.6:
- `CLI-058` Darce: `config-only`, sem PR necessária; usar `DARCE_API_BASE` na raiz e `DARCE_MODEL`.
- `CLI-059` CLAII: patch genérico local validado, mas publicação bloqueada pela declaração upstream
`All Rights Reserved`/ausência de licença OSS; só reconsiderar com autorização jurídica explícita.
- `CLI-060` nori-cli: `config-only` via agente ACP customizado OpenCode; não alterar backend Codex;
MCP deve ser configurado uma vez, em Nori ou OpenCode, para evitar duplicação de tools.
- `CLI-061` cursor-agent clone, `CLI-062` Free Code e `CLI-063` Claude Engineer: revisar origem,
licenca e politica do fork antes de publicar.
Lote P2.7 reservado em 2026-08-02, na branch-base local `release/v3.8.50` em
`35405be6020696a7c66158ea7a25f06d61ff88ff`. Os três upstreams foram clonados em worktrees
separadas, indexados e delegados. Nenhuma publicação está autorizada; patches só podem surgir após
prova RED→GREEN e permanecem sem commit até revisão central.
Resultado P2.7:
- `CLI-061` cursor-agent clone: `config-only`; OpenAI usa base com `/v1`, Anthropic usa raiz sem
`/v1`; tools/tool-result foram comprovados nos dois protocolos. O factory rejeita `auto` puro,
mas isso não impede uso com modelos reconhecíveis ou classes diretas. Sem PR.
- `CLI-062` Free Code: `config-only` com `ANTHROPIC_BASE_URL` na raiz e `model=auto`; stream,
tools/tool-result e MCP nativo foram comprovados. O repo canônico agora é `freecodexyz/free-code`,
mas não há licença e o README atribui o código à Anthropic; publicação bloqueada.
- `CLI-063` Claude Engineer: endpoint/chave funcionam como `config-only` com modelo fixo. A lacuna
de `ANTHROPIC_MODEL` já está coberta pela PR #250; não criar patch concorrente. Arquivo de licença
segue ausente apesar da issue #116, portanto publicação permanece bloqueada.
- `CLI-064` Smol Developer, `CLI-065` Agentless e `CLI-066` Amazon Q Developer CLI: decidir entre
SDK/adaptador, config de modelo ou bloqueio por autenticacao.
Lote P2.8 iniciado em 2026-08-02 na branch-base local `release/v3.8.50`, SHA
`35405be6020696a7c66158ea7a25f06d61ff88ff`, com clones limpos e separados. Smol Developer será
testado primeiro como integração do SDK OpenAI legado; Agentless será avaliado por backend
OpenAI/Anthropic/DeepSeek; Amazon Q Developer CLI será tratado como protocolo AWS próprio, com MCP
avaliado separadamente. Não criar adaptador grande para Amazon Q nem qualquer publicação antes de
issue-first/coordenação exigida por `CONTRIBUTING.md`. Estado inicial: nenhum commit, fork, push,
PR, issue ou Discussion.
Resultado P2.8:
- `CLI-064` Smol Developer: `config-only`; `OPENAI_API_BASE` com `/v1` e `model=auto` passaram no
CLI, biblioteca e Agent Protocol histórico. Não há lacuna provider-specific e a PR #134 já cobre
uma expansão LiteLLM. Sem publicação.
- `CLI-065` Agentless: `config-only` pelo backend OpenAI, incluindo embeddings. Anthropic normal
também funciona; cache/tools exige SDK histórico e DeepSeek possui host fixo, mas essas melhorias
não são necessárias para integrar o projeto e propostas LiteLLM anteriores foram fechadas. Sem
publicação.
- `CLI-066` Amazon Q Developer CLI: MCP stdio é a integração direta; o backend de modelo fala AWS
JSON/EventStream e precisa de wrapper/backend novo. O upstream está em manutenção crítica e exige
issue-first; não preparar PR nominal ou adaptador surpresa. Sem publicação.
Estado final P2.8: commits `0`, pushes `0`, forks `0`, PRs `0`, issues `0`, Discussions `0`.
Próxima fila: P2.9 (`CLI-067` nanobot, `CLI-068` ZeroClaw, `CLI-069` NanoClaw), usando no máximo
três worktrees/agentes e repetindo a pesquisa individual antes de qualquer patch.
Lote P2.9 iniciado em 2026-08-03 sobre a branch-base local `release/v3.8.50`, SHA
`84b1e5e12f238269e698f400766230f985f4a07b`. O checkout principal já continha uma alteração do
operador em `CLAUDE.md`, preservada fora do escopo. As worktrees foram recriadas e os upstreams
foram clonados nos HEADs `44b7e1bf4` (nanobot), `4770420ab` (ZeroClaw) e `dfac7e0af` (NanoClaw).
Os três índices Codebase Memory moderate estão ready, sem skipped, e a pesquisa foi delegada a um
agente por repositório. Nenhuma publicação está autorizada; o estado inicial continua: commits `0`,
pushes `0`, forks `0`, PRs `0`, issues `0`, Discussions `0`.
- `CLI-067` nanobot, `CLI-068` ZeroClaw e `CLI-069` NanoClaw: validar providers OpenClaw/Anthropic
e evitar assumir que todos aceitam a mesma base URL.
Resultado P2.9:
- `CLI-067` nanobot: `config-only` pelo provider dinâmico OpenAI-compatible. A base correta inclui
`/api/v1`; `omniroute/auto` seleciona o provider custom e envia `auto` no wire. Chat, SSE, tools,
reasoning, usage, imagens, discovery e retry foram validados. Sem publicação upstream.
- `CLI-068` ZeroClaw: `config-only` pela família `custom`, com `uri=/v1`, modelo `auto`, wire Chat e
`native_tools=true`. Responses é opt-in. Suite de provider, config, fmt e smoke HTTP passaram.
Sem provider nominal ou publicação upstream.
- `CLI-069` NanoClaw: `config-only` pelo provider Claude existente, apontando a raiz Anthropic do
OmniRoute sem `/v1/messages` e usando OneCLI para a credencial. Codex e OpenCode têm bloqueios
upstream reproduzidos (#3155/#1984/#2985) e ficam fora do caminho de produção atual.
Estado final P2.9: commits `0`, pushes `0`, forks `0`, PRs `0`, issues `0`, Discussions `0`.
Progresso da pesquisa: `70/104` (`67,3%`); pendentes: `34/104` (`32,7%`). Próxima fila: P2.10
(`CLI-070` PicoClaw, `CLI-071` IronClaw, `CLI-072` NullClaw).
- `CLI-070` PicoClaw, `CLI-071` IronClaw e `CLI-072` NullClaw: localizar traits/registries e propor
um provider pequeno com testes.
- `CLI-073` Moltis, `CLI-074` GitClaw e `CLI-075` LionClaw: confirmar atividade, provider e comandos
de validacao antes da publicacao.
### Onda 4 - P3, integracoes indiretas
- `CLI-076`, `CLI-077`, `CLI-078`, `CLI-079`, `CLI-080` e `CLI-081`: pesquisar forwarding de
ambiente/configuracao para os agentes filhos;
publicar wrapper ou docs somente quando houver um ponto de extensao real.
- `CLI-082`, `CLI-083`, `CLI-084`, `CLI-085`, `CLI-086`, `CLI-087`, `CLI-088`, `CLI-089` e
`CLI-090`: escolher ACP, MCP, launcher ou integracao do agente filho; nao apresentar uma
integracao de orquestrador como provider de modelo.
- `CLI-091` e `CLI-092`: tratar como interoperabilidade entre proxies; documentar loops, headers,
auth e riscos antes de propor codigo.
- `CLI-093` e `CLI-094`: integrar como broker/ferramenta MCP somente se isso estiver no escopo dos
projetos.
- `CLI-095` e `CLI-096`: configurar o agente filho e revisar a entrada existente de Agent Deck.
### Onda 5 - P4, fechados, EULA e MITM
- `CLI-097` Pool: confirmar o que a EULA permite; priorizar configuracao local e nao presumir PR.
- `CLI-098` Junie CLI: pesquisar canal oficial de feedback; sem repositorio publico confirmado, nao
existe fila de PR.
- `CLI-099` Cursor desktop, `CLI-100` Windsurf, `CLI-101` Amp, `CLI-102` Amazon Q/Kiro CLI e
`CLI-103` Cowork: tratar como MITM, configuracao de produto ou pedido oficial de feature. So mover
para PR se um repositorio publico e uma politica de contribuicao forem comprovados.
## 7. Prompt operacional para cada subagente
O agente principal deve adaptar e enviar este prompt para cada item:
```text
Voce e responsavel exclusivamente por CLI-NNN - <projeto> no repositorio <URL>.
Voce nao esta sozinho no workspace: nao reverta, sobrescreva ou reorganize mudancas de outros
agentes. Trabalhe somente na worktree isolada atribuida dentro de .claude/worktrees/ e nunca use
git stash/pop.
Primeiro pesquise o upstream atual. Leia README, CONTRIBUTING, licenca, templates e instrucoes locais.
Registre commit/release, arquitetura de providers, config/base URL, protocolo, auth, modelos,
streaming, tool calling, issues/PRs existentes e comandos oficiais de build/test. A evidencia inicial
do relatorio e uma hipotese, nao uma conclusao.
Antes de editar, classifique o caso como pr-provider, pr-generic, pr-docs, issue-first, config-only,
adapter-acp, adapter-mcp, wrapper, needs-mitm ou blocked, com justificativa. Execute o baseline e
registre falhas preexistentes. Se houver patch, trabalhe com teste primeiro e implemente somente a
menor integracao coerente com o upstream. Confirme raiz versus /v1 versus /v1beta, autenticacao,
modelo, streaming e tool calling conforme aplicavel.
Nao publique nada antes da revisao do agente principal. Entregue: pesquisa com links/caminhos,
gate, baseline, diff, testes, smoke test sanitizado, riscos, branch/commit local se criados e a
atualizacao proposta para 04-tracker-integracoes-clis.md. Nao invente dados e nao exponha chaves.
```
## 8. Checklist de autorizacao para enviar uma PR
O agente principal somente autoriza a publicacao quando todas as respostas forem `sim` ou houver
uma excecao registrada:
- [ ] O repositorio canonico e a branch-alvo foram confirmados.
- [ ] A politica aceita o tipo de contribuicao planejado.
- [ ] Issues/PRs duplicadas foram pesquisadas.
- [ ] O commit/release de base esta registrado.
- [ ] O gate de contribuicao esta justificado.
- [ ] O baseline foi executado e falhas preexistentes estao separadas.
- [ ] O patch e o menor necessario e segue a arquitetura upstream.
- [ ] A base URL e sua regra de versao foram verificadas no codigo e em runtime.
- [ ] Auth/modelos foram testados sem vazar segredo.
- [ ] Streaming/tool calling foram testados ou marcados explicitamente como nao aplicaveis.
- [ ] Testes, lint, format, typecheck/build relevantes foram executados.
- [ ] A documentacao foi executada e corresponde ao codigo.
- [ ] O diff nao contem caches, builds, logs, credenciais ou refactors sem relacao.
- [ ] O titulo e o corpo seguem o template upstream e nao contêm marketing ou texto de IA.
- [ ] O tracker esta pronto para receber branch, commit e URL reais.
## 9. Campos adicionais recomendados no tracker
O tracker atual deve continuar como fonte principal. Durante a execucao, registrar nas observacoes ou
em uma nota individual:
- commit/release pesquisado;
- decisao `pr-provider`, `pr-generic`, `pr-docs`, `issue-first`, `config-only`, adapter, wrapper,
MITM ou bloqueio;
- protocolo e regra da base URL;
- comandos de baseline e resultado;
- comandos finais e resultado;
- smoke tests realizados;
- arquivos modificados;
- fork, branch e commit;
- PR/issue e estado de CI/review;
- limitacoes e proximo passo.
Campos ainda nao comprovados permanecem `—`.
## 10. Inicio recomendado
O primeiro ciclo de publicacao deve usar o lote P0.1:
1. `CLI-001` - Gemini CLI (`google-gemini/gemini-cli`)
2. `CLI-002` - Claw Code (`ultraworkers/claw-code`)
3. `CLI-003` - Plandex (`plandex-ai/plandex`)
Os tres subagentes fazem pesquisa fresca e implementacao em paralelo, mas nenhuma PR e enviada antes
da revisao individual do agente principal. Ao publicar ou concluir config-only/bloqueio, atualizar o
tracker e liberar os mesmos tres slots para o lote P0.2.
## Lote P2.10 iniciado em 2026-08-03
Base local: `release/v3.8.50` em `84b1e5e12f238269e698f400766230f985f4a07b`. Worktrees isoladas e um agente por upstream foram criadas para `CLI-070` PicoClaw, `CLI-071` IronClaw e `CLI-072` NullClaw. Nenhuma publicação está autorizada; os agentes devem pesquisar o HEAD atual, provar `config-only` ou RED→GREEN e registrar governança, gates, smoke e estado limpo.
Resultado P2.10:
- `CLI-070` PicoClaw: `config-only`, `openai/auto` com base `/api/v1`; Chat/SSE/tools/usage/images/discovery. Go ausente impediu execução local; monitorar #3298, sem PR.
- `CLI-071` IronClaw: `config-only`, `openai_compatible` com `/api/v1` e `auto`; 889 testes do crate LLM, 5 de resolução e fmt passaram. Sem PR; reasoning proprietário segue limitado por #3673.
- `CLI-072` NullClaw: `config-only`, provider custom com Chat Completions recomendado e Responses/Anthropic como alternativas. Zig ausente; CI do mesmo HEAD verde. Sem PR.
Estado final P2.10: commits `0`, pushes `0`, forks `0`, PRs `0`, issues `0`, Discussions `0`.
Pesquisa acumulada: `73/104` (`70,2%`); pendentes: `31/104` (`29,8%`). Próxima fila: P2.11 (`CLI-073` Moltis, `CLI-074` GitClaw, `CLI-075` LionClaw).
Resultado P3.1:
- `CLI-076` VibePod: `config-only` pelo agente Claude Code com raiz Anthropic `/api`; wrapper injeta env no container. Codex sem chave automática permanece não comprovado.
- `CLI-077` zeroshot: `config-only` pelo gateway OpenAI `/api/v1`; 22 testes focados verdes; limitações de streaming JSON, reasoning e MCP registradas.
- `CLI-078` Fractal: `config-only` por Codex Responses em `CODEX_HOME` por node; servidores tmux quentes podem perder `OMNIROUTE_API_KEY`, recomendando fix genérico upstream.
Estado final P3.1: commits `0`, pushes `0`, forks `0`, PRs `0`, issues `0`, Discussions `0`. Pesquisa acumulada: `79/104` (`76,0%`); pendentes: `25/104` (`24,0%`).
Resultado P3.2: Bernstein `config-only` por openai_agents; Traycer `config-only` indireto pelo harness OpenCode; h5i `patch-required` porque auth proxy/egress são fixados em OpenAI. Nenhuma publicação externa. Pesquisa acumulada `82/104` (`78,8%`), pendentes `22/104` (`21,2%`).
Resultado P2.11:
- `CLI-073` Moltis: `config-only`, provider `custom-omniroute`, `/api/v1`, `auto`, Chat/SSE/tools e capacidades multimodais. 401 testes e fmt passaram. Sem publicação.
- `CLI-074` GitClaw/GitAgent: `config-only`, loader OpenAI-compatible com `GITAGENT_MODEL_BASE_URL`, `OPENAI_API_KEY` e `omniroute:auto`. Build, 65 testes e smoke passaram. Sem publicação.
- `CLI-075` LionClaw: `patch-required`/`issue-first`. O runtime Codex confinado não recebe `config.toml`/provider secret; preparar proposta genérica alinhada à [#157](https://github.com/moshthepitt/lionclaw/issues/157), sem PR até revisão do mantenedor.
Estado final P2.11: commits `0`, pushes `0`, forks `0`, PRs `0`, issues `0`, Discussions `0`. Pesquisa acumulada: `76/104` (`73,1%`); pendentes: `28/104` (`26,9%`).
Resultado P3.3: OMK `viable-mcp`; kodo `config-only` indireto; ORCH `needs-wrapper`. Pesquisa acumulada `85/104` (`81,7%`), pendentes `19/104` (`18,3%`). Nenhuma publicação externa.
Resultado P3.4: LoopTroop `config-only` indireto via provider OpenCode; Galley `patch-required` por não possuir transport OpenAI-compatible configurável; Relay `config-only` via provider profile/Codex, condicionado a smoke da Responses API e controles sobre ferramentas nativas. Nenhuma publicação externa. Pesquisa acumulada `88/104` (`84,6%`), pendentes `16/104` (`15,4%`).
Resultado P3.5: SageCLI `config-only` indireto via Codex, com caveat de env plaintext; 5dive `patch-required` por mapas fechados de provider/base; agx `config-only` indireto via Codex e com gates de Responses/sandbox. Pesquisa acumulada `91/104` (`87,5%`), pendentes `13/104` (`12,5%`). Nenhuma publicação externa.
Resultado P3.6: claude-code-router, cc-router e OneCLI são config-only; os dois primeiros oferecem endpoints custom OpenAI-compatible e OneCLI injeta credenciais por proxy MITM. Pesquisa acumulada `94/104` (`90,4%`), pendentes `10/104` (`9,6%`). Nenhuma publicação externa.
Resultado P3.7: agent-browser `config-only` direto por Chat Completions; OpenWork `config-only` via OpenCode custom; Agent Deck `config-only` via CLIs filhos. Pesquisa acumulada `97/104` (`93,3%`), pendentes `7/104` (`6,7%`). Nenhuma publicação externa.
Resultado P4.1: Pool e Junie são `config-only` OpenAI-compatible; Cursor é `config-only` limitado ao BYO chat panel, sem MITM/protocolo privado. Pesquisa acumulada `100/104` (`96,2%`), pendentes `4/104` (`3,8%`). Nenhuma publicação externa.
Resultado P4.2: Windsurf está bloqueado para inferência e permite apenas MCP; Amp depende de confirmação Enterprise; Amazon Q legado requer patch substancial e Kiro atual é MCP-only seguro. Pesquisa acumulada `103/104` (`99,0%`), pendente `1/104` (`1,0%`). Nenhuma publicação externa.
Resultado P4.3: Cowork não permite substituir oficialmente a inferência; Custom Connector MCP remoto é o único caminho suportado e permanece separado do modelo. Pesquisa concluída `104/104` (`100%`), pendentes `0/104` (`0%`). Nenhuma publicação externa nesta fase de pesquisa.

View File

@@ -1,131 +0,0 @@
# Relatório final — campanha de 104 integrações CLI OmniRoute
**Data de fechamento:** 2026-08-03
**Escopo:** `CLI-000` a `CLI-103`
**Resultado:** `104/104` pesquisados (`100%`), `0` pendentes de pesquisa.
## Como consultar o resultado individual
O documento autoritativo, com uma linha para cada caso, é o [tracker completo](./04-tracker-integracoes-clis.md). Ele contém para cada ID:
- prioridade;
- projeto e repositório;
- classificação de integração;
- estado de contribuição upstream;
- branch e commit quando existentes;
- URL de PR e/ou issue quando publicados;
- estado no catálogo OmniRoute;
- observações, limitações, testes e próximo passo.
Além do tracker, existem fichas técnicas individuais em `_tasks/cli-integrations/`. A cobertura foi auditada e agora há uma ficha para cada ID `CLI-000``CLI-103`; o caso `CLI-000` jcode foi adicionado como ficha de referência nesta revisão.
## Resumo quantitativo
| Grupo operacional | Quantidade | Tratamento |
|---|---:|---|
| Configuração direta ou indireta | 76 | Documentar receita, validar smoke e só abrir PR se houver melhoria upstream real |
| Contribuição upstream (PR/issue/docs/patch) | 17 | Preparar diff mínimo, validar, revisar e publicar conforme política do repositório |
| Patch obrigatório | 4 | Implementar genericamente, com RED→GREEN/TDD e revisão do mantenedor |
| Bloqueados/fechados | 4 | Registrar bloqueio; usar apenas MCP ou canal oficial, sem MITM |
| MCP/wrapper/ACP como caminho principal | 2 | Integrar a camada de ferramentas/orquestração, sem falsificar provider de inferência |
| Outros casos híbridos | 1 | Seguir a combinação específica descrita no tracker |
Os números são derivados do campo `Tipo` do tracker; categorias podem se sobrepor em casos híbridos. Atualmente há **7 PRs reais** e **9 issues reais** registrados no tracker, além de cinco entradas locais marcadas como integradas ao catálogo OmniRoute. Nenhum link foi inventado para os 97 casos sem publicação externa.
## O que foi feito na campanha
1. Inventário inicial e busca extensa de CLIs, runtimes, harnesses e control-planes.
2. Priorização P0P4 considerando compatibilidade de protocolo, adoção, licença, maturidade e risco.
3. Pesquisa fresca, uma a uma, em worktrees isoladas, em lotes de no máximo três agentes.
4. Uso de Codebase Memory para índices upstream e verificação de cobertura; faixas parciais foram lidas diretamente quando aplicável.
5. Classificação por configuração, patch, PR documental, issue-first, MCP, wrapper ou bloqueio.
6. Registro de comandos, base URL, autenticação, modelos, streaming, tools, reasoning, imagens, MCP/ACP/A2A, testes e limitações.
7. Consolidação de cada lote com commit separado no OmniRoute e no repositório `_tasks`.
8. Atualização final do tracker, plano de integração, plano de publicação e handoff.
9. Nenhuma credencial real, publicação externa ou técnica de interceptação não autorizada foi utilizada.
## Estratégia para abrir PRs em 100% dos casos
“Abrir PR para 100%” deve ser interpretado como **dar um destino upstream apropriado a 100% dos casos**, e não criar 104 PRs artificiais. Há quatro trilhas:
### Trilha A — PR de código ou documentação
Aplicar aos casos `viable-upstream`, `pr-generic`, `pr-docs`, `patch-required` e híbridos que tenham superfície pública e política de contribuição compatível.
Processo por caso:
1. Reconfirmar HEAD, licença, branch default, política de contribuição e duplicatas.
2. Criar worktree/branch baseada na versão local vigente.
3. Executar baseline upstream e registrar falhas preexistentes.
4. Escrever teste RED que demonstre a lacuna.
5. Implementar o menor patch genérico possível — preferir `openai-compatible`, `base_url` ou provider abstrato a um provider nominal OmniRoute.
6. Executar GREEN: testes focados, suite upstream, lint, format, typecheck/build e smoke com fake server ou OmniRoute local usando placeholder.
7. Revisar segurança: nenhuma chave em argv, logs, fixtures, URL ou artefato; erros sanitizados; streaming/tools/cancelamento cobertos.
8. Abrir PR somente se contribuições externas forem aceitas. O corpo deve explicar problema, solução genérica, compatibilidade, testes, limitações e não conter marketing/texto de IA.
9. Se o repositório bloquear fork/PR ou pedir discussão prévia, abrir issue de proposta com o mesmo patch/reprodução, sem enviar PR prematuramente.
10. Atualizar tracker com branch, commit, URL, CI, revisão e resposta do mantenedor; acompanhar até `accepted`, `merged`, `rejected` ou `awaiting-maintainer`.
### Trilha B — Issue-first, discussão ou suporte ao mantenedor
Aplicar quando a arquitetura é adequada, mas há bloqueio de governança, firewall, CLA, fork fechado, dúvida de protocolo ou necessidade de decisão do autor. A issue deve conter:
- caso de uso OmniRoute;
- configuração atualmente possível;
- lacuna reproduzível;
- proposta genérica;
- impacto de segurança;
- testes/fake server;
- disposição para enviar PR após aprovação.
Não abrir uma PR paralela enquanto a política exigir issue-first.
### Trilha C — Config-only documentado
Aplicar aos casos em que o upstream já suporta a integração e uma mudança de código seria redundante. O entregável é:
- ficha individual;
- receita validada;
- smoke test e limitações;
- eventual documentação externa/local do OmniRoute;
- issue somente se houver pedido de documentação ou descoberta de bug real.
Não criar provider nominal ou PR apenas para adicionar a palavra “OmniRoute”.
### Trilha D — MCP, wrapper ou bloqueio seguro
Aplicar a control-planes, produtos fechados e CLIs sem rota de inferência substituível. O resultado pode ser:
- MCP remoto/stdio do OmniRoute;
- wrapper local claramente identificado como wrapper;
- solicitação oficial de custom provider;
- registro de bloqueio e gate legal/ToS.
Nunca mascarar OmniRoute como Claude/Codex, falsificar executável, interceptar TLS ou reutilizar tokens privados para fabricar uma PR upstream.
## Ordem recomendada de execução
1. **Primeiro:** PRs e issues já preparadas ou com alto retorno e baixo risco — jcode, Gemini CLI, Claw Code, Plandex, Trae Agent, Every Code, VT Code e CoreCoder.
2. **Segundo:** patches genéricos com boa superfície OSS — AutoCodeRover, Galley, 5dive e demais casos `pr-generic`/`patch-required`.
3. **Terceiro:** issues aguardando decisão — Open Codex, Kimi CLI, Devon, g3, Free Code, Claude Engineer e casos com `awaiting-maintainer`.
4. **Quarto:** documentação e receitas config-only agrupadas por ecossistema — OpenCode, Codex, LiteLLM, AI SDK, OpenAI-compatible e Anthropic-compatible.
5. **Quinto:** MCP/plugins para produtos fechados — Windsurf, Amp, Kiro, Cowork e Cursor, sempre pela superfície oficial.
Cada rodada deve manter no máximo três agentes ativos. O agente principal revisa o resultado do trio antes de liberar o próximo.
## Critério de encerramento por caso
Um caso só pode ser marcado como finalizado quando possui: pesquisa, classificação, evidência de protocolo, baseline ou limitação reproduzível, receita/patch/bloqueio, validação proporcional, estado de publicação e próximo passo. Para produtos fechados, `blocked-closed` ou `MCP-only` é um resultado válido e preferível a uma PR não autorizada.
## Estado de publicação atual
Os únicos links de publicação comprovados devem continuar sendo os registrados no tracker. O fato de existir uma branch local de pesquisa não significa que exista PR upstream. A matriz de verdade é:
- PR/issue preenchida: publicação real;
- campo `—`: nenhuma publicação externa comprovada;
- `not-applicable`: configuração ou bloqueio sem contribuição upstream;
- `awaiting-maintainer`: contato feito, aguardando decisão;
- `published-pr`/`published-issue`: URL real presente no tracker.
## Próxima fase
A pesquisa está encerrada. A próxima fase é execução controlada da Trilha A/B/C/D, começando pelos casos com maior retorno e menor risco, com revisão central antes de qualquer push, PR, issue ou contato externo.

View File

@@ -1,115 +0,0 @@
# Devin Claude Bridge Progress
Updated: 2026-07-28
## Baseline
- Fork version: `3.8.49`.
- Starting branch: `release/v3.8.49`.
- Starting commit: `ed7db3ee5f89a144b2d931d8605534522f83de30`.
- Fixed runtime artifacts: Node `26.0.0`, Claude Code `2.1.220`, Devin CLI `3000.2.17`.
- Existing `devin-cli` remains unchanged; the new path is the separate
`devin-cli-agentic` provider.
## Implemented architecture
- Claude Code runs only inside the non-root bridge container with its own empty config
volume and local OmniRoute base URL.
- `devin-cli-agentic` preserves Anthropic messages, tool schemas, `tool_use`, and
`tool_result`, then calls the official Devin CLI over ACP stdio.
- The executor starts `devin acp --agent-type summarizer`. This is the only fixed official
ACP role in the pinned CLI that has no Devin-owned tools.
- The request is framed as an execution trace. Devin can return one strict client tool
envelope; Claude Code executes that tool locally.
- Internal ACP `tool_call` events, unsupported blocks, invalid schemas, narrative actions,
timeouts, cancellation, and process failure all fail closed.
- Provider and network policy prevent combo/auto/Anthropic fallback.
## Offline proof
- Focused serializer, parser, executor, ACP lifecycle, wire-format, environment, and audit
tests pass (39/39).
- The contract suite covers Anthropic JSON/SSE, `tool_use`, `tool_result` continuation,
fragmented ACP frames, stderr, early exit, timeout, cancellation, and fail-closed provider
loss.
- The production bridge image builds with the pinned CLIs.
- Real Claude Code offline E2E loads `CLAUDE.md`, the project skill and slash command, fires
hooks, executes local tools over multiple turns, observes a failed test, repairs the file,
reruns the test, and completes.
- The isolation verifier proves non-root/read-only execution, isolated mounts and config,
blocked Anthropic/Claude access, no host credential mounts, local-only inference, and no
fallback.
Evidence is generated under `.sandbox/evidence` and ignored by Git.
## Regression status
- `typecheck:core`, focused ESLint, Prettier, shell/Node syntax, and the complete documentation
accuracy suite pass.
- The broad `npm run check` is not reported as passed: after its lint phase, the repository
test runner remained alive while an existing `ioredis` client repeatedly retried an
unavailable local Redis endpoint after `quota-redis-store.test.ts`. The bridge-focused
suites, production image build, offline E2E, isolation proof, and live gate do not use that
Redis service and all pass.
## Live Devin proof
Passed with the official in-container login and discovered model
`swe-1-7-lightning`. The terminal live run completed all three scenarios:
1. Claude Code loaded the fixture instructions, issued client-owned `Read` calls, and
returned a correct defect analysis.
2. Claude Code issued a real `Edit` changing subtraction to addition, then a client-owned
`Bash` call running `npm test`; the test reported one pass and zero failures.
3. Claude Code initialization listed `bridge-check` and `bridge-proof`, read the corrected
source and test, executed another client-owned `npm test`, and completed successfully.
The live evidence validator parses stream JSON and requires successful tool results. It does
not accept a textual claim that a tool ran. It also rejects terminal summaries that report a
blocker, incomplete work, or required next steps.
The final live gate reported:
```text
PASS: validated Claude evidence for LIVE_ANALYSIS_COMPLETE
PASS: validated Claude evidence for LIVE_FIX_COMPLETE
PASS: validated Claude evidence for BRIDGE_E2E_COMPLETE
PASS: three live Devin-backed Claude Code scenarios completed
PASS: live model swe-1-7-lightning was discovered and validated by three scenarios
```
The same gate validated the network audit: only the Devin guard path was used, no internal
Devin tool event was accepted, and the Claude egress audit remained empty.
## Investigation conclusion
The initial default-agent hypothesis failed because ACP permission modes do not turn the
default Devin agent into a raw inference backend. Even `ask` mode can emit Devin-owned
`tool_call` events. A discovered `allowed-tools: []` agent configuration was not consumed by
`devin acp` in CLI `3000.2.17`.
The working adaptation uses the official `summarizer` agent because it is structurally
no-tools. Its fixed summarization behavior can produce intermediate prose, so the bridge
frames requests as execution traces, detects future-action narration, performs at most one
strict repair, and otherwise fails. Live validation also exposed transient ACP timeouts;
the harness now spaces independent scenarios rather than weakening routing or retrying into
another provider.
## Safety record
No host Claude executable, configuration, login, OAuth token, Keychain, or Anthropic API was
used. The dedicated Docker volumes remain role-separated. No credential value is written to
the repository or evidence output.
During the early baseline, a focused test without isolated `DATA_DIR` initialized the
repository's normal OmniRoute database at `/Users/lucasisrael/.omniroute/storage.sqlite`.
It was not rolled back or touched again. Every bridge command now pins database and temporary
paths under the worktree's `.sandbox` directory.
## Remaining limits
- The no-tools backend has a summarizer system role rather than a neutral generation role.
- One client tool call per response is supported; parallel tool calls are rejected.
- ACP processes are per-turn and stateless.
- Live Devin availability can still produce explicit `502`/`504` failures.
- Images and unadvertised vision/effort/large-context capabilities remain unsupported.

View File

@@ -1,200 +0,0 @@
---
title: "Incident Response Runbook — OmniRoute (2026-06-18)"
version: 3.8.50
lastUpdated: 2026-08-06
---
# Incident Response Runbook — OmniRoute (2026-06-18)
**Status**: Authoritative. The 71-pillar audit (L61) references this doc
for the `Obs > 2.00` gate.
**Owner**: observability-circle (lead: security-circle lead).
**SLOs**: see `docs/PERF_BUDGETS.md` § 1 (top-level SLOs) and
`ops/slos.yaml` (machine-readable form, generated by the Bifrost team).
**Disclosure policy**: see `SECURITY.md` (vulnerability disclosure only,
separate flow).
This runbook is the operational playbook for **non-security** incidents:
outages, latency regressions, error-budget burn, and provider-side
failures. Vulnerability disclosure stays on `SECURITY.md`; do not route
those through this runbook.
---
## 1. Severity ladder
| Sev | Definition | Examples | Page on | Resolve by |
|---|---|---|---|---|
| **SEV-1** | User-visible outage; > 50 % of requests failing or > 2x SLO breach for 5 min. | Cluster down; auth layer broken; 5xx flood. | On-call P0 (immediate) | 4 h |
| **SEV-2** | Significant degradation; 1.52x SLO breach for 15 min, or single-tenant impact. | Single provider down; p95 > 1.5x budget; rate-limit runaway. | On-call P1 (15 min) | 24 h |
| **SEV-3** | Latent bug or near-miss; no current user impact but error budget at risk. | Memory leak trending up; circuit breaker tripping on one provider. | Slack `#omniroute-ops` (next standup) | 7 d |
| **SEV-4** | Cosmetic / informational. | Log line noise; non-binding UI glitch. | Next weekly review | Next refactor cycle |
**Burn-rate escalation** (per `docs/PERF_BUDGETS.md` § 1): 6x for 5 min
is SEV-1; 2x for 1 h is SEV-2; sustained < 1x for 7 d demotes to SEV-3.
---
## 2. Detection sources
| Source | Signal | Routing |
|---|---|---|
| Prometheus (`/metrics`) | Counter deltas (5xx, latency) | Alertmanager → PagerDuty |
| Grafana SLO dashboards | SLO burn-rate panels | Slack `#omniroute-ops` |
| Uptime probe (`/api/health/ping`) | 3 consecutive failures from 3 regions | Alertmanager → PagerDuty |
| Dependabot | New CVE in dependency | GitHub issue + Slack `#security` |
| User report (support@) | Manual triage | Slack `#omniroute-triage` |
| Error budget burn alert | `slo_burn_rate > threshold` | Alertmanager |
Prometheus and Alertmanager are configured in the deploy repo (see
`docs/operations/DEPLOY.md` once published; currently inline in
`docker-compose.prod.yml`).
---
## 3. First-15-minutes checklist
When paged, the on-call engineer runs this checklist verbatim. **Do
not** skip steps; each is timed.
1. **0:00** — Acknowledge the page in PagerDuty. Stops the escalation
timer and notifies the secondary.
2. **0:02** — Open the [SLO dashboard][dash] and the [incident
channel][chan] (`#inc-YYYY-MM-DD-slug`). Post a single-line ack
with the alert name and the time.
3. **0:05** — Classify severity per § 1. If SEV-1 or SEV-2, declare
the incident in the channel and tag `@incident-commander`.
4. **0:08** — Capture the alert payload, the most recent deploy SHA,
and the top 5 slow / erroring endpoints. Post to the channel.
5. **0:12** — Decide: **mitigate first, root-cause later**. Choose
one of:
- **Roll back** to the last green deploy (`bin/rollback.sh vX.Y.Z`).
- **Failover** to the healthy replicas (Caddy LB removes the bad
replica automatically; verify with `curl /api/health/ping`).
- **Disable** the broken connection(s) via `PUT /api/providers/{connectionId}`
with body `{ "isActive": false }` (per-connection toggle, safe by
default; repeat per key/account — see § 4.1).
6. **0:15** — Post the chosen mitigation in the channel. If the page
is still firing after 5 more minutes, escalate to the secondary.
[chan]: TBD — set to your team's incident-chat channel (e.g. a Discord/Slack `#inc-*` channel); not provisioned by this repo.
[dash]: TBD — set to your Grafana/observability dashboard URL; not provisioned by this repo.
---
## 4. Mitigation runbooks (per failure mode)
### 4.1 Provider outage (single provider down)
1. `PUT /api/providers/{connectionId}` with body `{ "isActive": false }`
deactivates that connection; combo routing and account selection skip it
on the next request (`src/app/api/providers/[id]/route.ts`). There is no
single whole-provider kill switch — if the provider has more than one
key/account, repeat per connection, or let the automatic provider circuit
breaker trip on its own (`src/shared/utils/circuitBreaker.ts`,
`domain_circuit_breakers` table; see `docs/architecture/RESILIENCE_GUIDE.md`).
2. Verify p95 returns to budget within 5 min.
3. If all connections for a model are down, apply the same `isActive: false`
toggle to every connection offering that model — there is no separate
per-model disable endpoint. Combo routing's automatic Model Lockout
(`open-sse/services/accountFallback.ts`; see
`docs/architecture/RESILIENCE_GUIDE.md`) also skips a model that keeps
erroring, without manual action.
4. Update the status page (if one is configured — see § 5) with a banner if
the outage exceeds 15 min.
### 4.2 Cluster-wide latency regression
1. Check the most recent deploy (`/api/monitoring/health` returns `appVersion`).
2. If p95 doubled vs the 7-day baseline, **roll back** to the prior
SHA via `bin/rollback.sh`.
3. If the regression is provider-side, see § 4.1.
### 4.3 Auth layer broken (5xx on /v1/responses for all keys)
1. Check the authz-inventory endpoint:
`curl https://api.omniroute.dev/api/settings/authz-inventory | jq`.
It returns a route-tier inventory (`tiers`, `bypassEnabled`,
`bypassPrefixes`, `spawnCapablePrefixes`, `cors` — see
`src/app/api/settings/authz-inventory/route.ts`); there is no
`policies_active` field. A non-200 response, or a `tiers` array that
fails to populate, means the settings/DB layer the auth pipeline reads
from is down — not just a single bad key.
2. If the endpoint itself errors or returns malformed data, restore the
settings store from the last good backup (`bin/restore-policies.sh <sha>`).
3. If the endpoint is healthy but requests still 5xx for every key, verify
`JWT_SECRET` / `API_KEY_SECRET` are set and unchanged for this deploy,
and that `isValidApiKey` (`src/sse/services/auth.ts`) can reach the DB.
4. Roll back if the cause is unclear.
### 4.4 Data-layer incident (sqlite corruption, audit log gap)
1. **Stop the cluster** (`docker compose -f docker-compose.prod.yml
stop`) — preventing further writes is more important than uptime.
2. Snapshot the data volume (`bin/snapshot-data.sh`).
3. Open a SEV-1; this is data-loss territory. Page the data-team.
4. Restore from the last verified backup (see `docs/BACKUP.md` once
published; currently the runbook is `bin/restore-data.sh <sha>`).
### 4.5 Security incident (vulnerability disclosure)
**Stop.** This is the `SECURITY.md` path, not this runbook. Page the
security on-call (`@security-team`); do not post details to
`#omniroute-ops`.
---
## 5. Communication
| Audience | Channel | Cadence | Owner |
|---|---|---|---|
| Engineering | `#inc-YYYY-MM-DD-slug` | Real-time | Incident commander |
| Status page | TBD — not provisioned by this repo | Every 30 min during SEV-1/2 | On-call |
| Customers (email) | TBD — set your announcement list/address | At SEV-1 start + resolution | Comms lead |
| Upstream providers | Direct contact | At SEV-1 start | Vendor mgmt |
| Postmortem | `docs/postmortem/YYYY-MM-DD-slug.md` | Within 5 business days | Incident commander |
Postmortem template is at `docs/postmortem/TEMPLATE.md` (forthcoming; no
dedicated ADR covers it yet — once written, register it in
`docs/architecture/cluster-decisions.md` following this repo's 71-pillar/ADR
numbering convention, e.g. ADR-041 there).
---
## 6. On-call rotation
| Role | Primary | Secondary | Rotation |
|---|---|---|---|
| Engineering on-call | security-circle lead | @open-sse | Weekly, Mon 09:00 PDT |
| Security on-call | @security-team | — | Weekly |
| Data on-call | @db-team | — | Weekly |
| Comms lead | @comms | — | As needed |
**Handoff**: every Monday 09:00 PDT, the outgoing on-call posts a
written handoff to the incoming in `#omniroute-ops-handoff` covering:
open SEV-3/4 items, scheduled maintenance windows, and any
in-flight mitigations.
---
## 7. Postmortem expectations
- **Blameless**. People did the best they could with the information
they had. Focus on systems, signals, and decision points.
- **Within 5 business days** of resolution. File via
`gh issue create --label postmortem --label SEV-1` (or `--label SEV-2`).
- **Action items** must be assigned, dated, and tracked in
`docs/TECH_DEBT.md` (P0 < 30 d, P1 < 90 d per that doc's SLA).
- **Mandatory attendees**: incident commander, on-call, any engineer
who touched the mitigation, and one person who was *not* involved
(fresh-eyes review).
---
## 8. Review log
| Date | Reviewer | Change |
|---|---|---|
| 2026-06-18 | security-circle lead | Initial runbook; severity ladder + 15-min checklist + 4.14.5 mitigation runbooks. Closes 71-pillar audit L61 (1/3 → 2/3). |
| 2026-07-18 | observability-circle | Corrected § 4.1/4.3 to the real provider-disable (`PUT /api/providers/{connectionId}`) and authz-inventory (`tiers`/`bypassEnabled`/`cors`, no `policies_active`) mechanisms; removed foreign branding and the nonexistent ADR-024/029 references. |
| 2026-07-18 (planned) | observability-circle | Wire on-call rotation into PagerDuty schedule; add the postmortem template. |

View File

@@ -1,233 +0,0 @@
---
title: "Performance Budgets — OmniRoute (2026-06-18)"
version: 3.8.50
lastUpdated: 2026-08-06
---
# Performance Budgets — OmniRoute (2026-06-18)
**Status**: Authoritative. SLO targets that the 71-pillar audit (L13)
references for the `Perf > 2.00` gate.
**Methodology**: per-endpoint p50/p95/p99 latency budgets, plus a
top-level availability SLO. Budgets are derived from the 3-replica
Caddy + Redis topology (commit `038439fa7`); adjust on infra change.
**Enforcement**: none yet. § 6 sketches a `benches/perf-gate.k6.js` k6
script that would assert the SLOs below, but it is a design reference,
not a committed file — no `bench/` or `benches/` directory exists in
this repo today. This doc is a target-setting reference only until a
CI gate is built as follow-up work.
**Re-evaluation cadence**: quarterly, or on any major infra change.
---
## 1. Top-level SLOs
| SLO | Target | Window | Page on breach |
|---|---|---|---|
| **Availability** (2xx or 4xx for /v1/* and /api/settings/*) | 99.9% | rolling 30 days | on-call P2 |
| **Error budget burn rate** (1xx normalized rate) | < 2x for 1h, < 6x for 5m | 1h / 5m windows | on-call P1 |
| **Aggregate p95 latency** (all /v1/*) | ≤ 1.5 s | rolling 5 min | on-call P2 |
| **Aggregate p99 latency** (all /v1/*) | ≤ 4.0 s | rolling 5 min | on-call P2 |
**Error budget**: 30-day window = 43.2 minutes of unavailability at
99.9%. Burn rate > 2x is P2; > 6x is P1.
---
## 2. Per-endpoint latency budgets
All budgets measured **server-side** (Next.js Route Handler entry to
response start, or last byte for streaming). Stream endpoints are
measured to time-of-first-byte (TTFB) since the body is incremental.
### 2.1 Inference endpoints (the hot path)
| Endpoint | Method | p50 | p95 | p99 | Notes |
|---|---|---|---|---|---|
| `/v1/responses` (non-stream) | POST | 800 ms | 1.8 s | 3.5 s | Includes translator + provider roundtrip |
| `/v1/responses` (stream) | POST (TTFB) | 350 ms | 900 ms | 1.8 s | TTFB only; total duration unbounded |
| `/v1/relay/chat/completions` (non-stream) | POST | 1.0 s | 2.2 s | 4.0 s | Includes per-(token,IP) rate-limit check |
| `/v1/relay/chat/completions` (stream) | POST (TTFB) | 400 ms | 1.0 s | 2.0 s | |
| `/v1/embeddings` | POST | 300 ms | 700 ms | 1.4 s | Pure provider roundtrip; cheap |
| `/v1/rerank` | POST | 600 ms | 1.4 s | 2.8 s | |
| `/v1/moderations` | POST | 250 ms | 600 ms | 1.2 s | Lightweight classification |
| `/v1/audio/speech` | POST | 1.2 s | 3.0 s | 6.0 s | Audio synthesis is slow; budget reflects that |
| `/v1/audio/transcriptions` | POST | 2.0 s | 5.0 s | 10.0 s | STT is bounded by audio duration + model size |
| `/v1/images/generations` | POST | 4.0 s | 8.0 s | 15.0 s | Image gen is async-bound by provider |
| `/v1/videos/generations` | POST (TTFB) | 600 ms | 1.5 s | 3.0 s | Async; client polls `/v1/videos/{id}` |
| `/v1/music/generations` | POST | 3.0 s | 6.0 s | 12.0 s | |
### 2.2 Files + batches
| Endpoint | Method | p50 | p95 | p99 | Notes |
|---|---|---|---|---|---|
| `/v1/files` (GET) | GET | 80 ms | 200 ms | 400 ms | Cached list |
| `/v1/files` (POST upload) | POST | 500 ms | 1.2 s | 2.5 s | 25 MB cap; multipart parse |
| `/v1/files/{id}` (GET) | GET | 60 ms | 150 ms | 300 ms | |
| `/v1/files/{id}` (DELETE) | DELETE | 80 ms | 200 ms | 400 ms | |
| `/v1/files/{id}/content` (download) | GET | 100 ms | 300 ms | 600 ms | + per-MB throughput |
| `/v1/batches` (GET) | GET | 150 ms | 400 ms | 800 ms | |
| `/v1/batches` (POST create) | POST | 200 ms | 500 ms | 1.0 s | Validates input file then enqueues |
| `/v1/batches/{id}` (GET) | GET | 100 ms | 300 ms | 600 ms | |
| `/v1/batches/{id}` (DELETE) | DELETE | 100 ms | 300 ms | 600 ms | |
| `/v1/batches/delete-completed` (POST) | POST | 400 ms | 1.0 s | 2.0 s | Mass delete; n rows |
### 2.3 Agents
| Endpoint | Method | p50 | p95 | p99 | Notes |
|---|---|---|---|---|---|
| `/v1/agents/health` | GET | 1.5 s | 4.5 s | 5.0 s | 5s per-provider timeout cap; expect 3-provider total |
| `/v1/agents/credentials` | GET | 100 ms | 250 ms | 500 ms | Metadata only; values never returned |
| `/v1/agents/tasks` (GET list) | GET | 150 ms | 400 ms | 800 ms | |
| `/v1/agents/tasks` (POST create) | POST | 250 ms | 600 ms | 1.2 s | Just enqueues; doesn't run agent |
| `/v1/agents/tasks/{id}` (GET) | GET | 100 ms | 300 ms | 600 ms | |
| `/v1/agents/tasks/{id}` (DELETE) | DELETE | 150 ms | 400 ms | 800 ms | |
### 2.4 Combos / me / providers
| Endpoint | Method | p50 | p95 | p99 |
|---|---|---|---|---|
| `/v1/combos` | GET | 80 ms | 200 ms | 400 ms |
| `/v1/me/status` | GET | 60 ms | 150 ms | 300 ms |
| `/v1/providers/{provider}/models` | GET | 100 ms | 250 ms | 500 ms |
### 2.5 Web / search
| Endpoint | Method | p50 | p95 | p99 | Notes |
|---|---|---|---|---|---|
| `/v1/web/fetch` | POST | 1.5 s | 4.0 s | 8.0 s | 10s timeout cap; recurse depth 3 |
| `/v1/search` | POST | 800 ms | 2.0 s | 4.0 s | Provider search latency varies |
### 2.6 VSCode-CLI shim (token-scoped)
These are the legacy passthrough paths. Budgets are tighter because
they're called frequently by the VSCode-CLI extension in tight loops.
| Endpoint | Method | p50 | p95 | p99 |
|---|---|---|---|---|
| `/v1/vscode/{token}/v1/chat/completions` | POST | 700 ms | 1.6 s | 3.0 s |
| `/v1/vscode/{token}/v1/models` | GET | 60 ms | 150 ms | 300 ms |
| `/v1/vscode/{token}/combos` | GET | 80 ms | 200 ms | 400 ms |
| `/v1/vscode/{token}/chat/completions` (legacy) | POST | 700 ms | 1.6 s | 3.0 s |
| `/v1/vscode/{token}/models` (legacy) | GET | 60 ms | 150 ms | 300 ms |
| `/v1/vscode/{token}/responses` | POST | 800 ms | 1.8 s | 3.5 s |
### 2.7 Management / settings
Management endpoints are operator-only and not part of the hot path.
Budgets are set conservatively; breaches don't page on-call but do
flag in the weekly perf review.
| Endpoint group | p50 | p95 | p99 |
|---|---|---|---|
| `/api/settings/*` (GET) | 100 ms | 300 ms | 600 ms |
| `/api/settings/*` (POST/PATCH/DELETE) | 200 ms | 500 ms | 1.0 s |
| `/api/keys/*` (CRUD) | 150 ms | 400 ms | 800 ms |
| `/api/quota/*` (CRUD) | 150 ms | 400 ms | 800 ms |
| `/api/monitoring/health` (heavy) | 500 ms | 1.5 s | 3.0 s |
### 2.8 Public probes
| Endpoint | Method | p50 | p95 | p99 |
|---|---|---|---|---|
| `/api/health/ping` | GET | 5 ms | 20 ms | 50 ms |
| `/api/monitoring/health` | GET | 5 ms | 20 ms | 50 ms |
| `/api/docs` | GET | 20 ms | 80 ms | 200 ms (HTML shell, no provider call) |
---
## 3. Throughput targets
| Tier | Per-replica RPS | Cluster RPS (3 replicas) | Notes |
|---|---|---|---|
| Inference (non-stream) | 50 RPS | 150 RPS | Bounded by provider quota + translator CPU |
| Inference (stream) | 25 concurrent streams | 75 streams | Bounded by Node event-loop + memory |
| Embeddings | 200 RPS | 600 RPS | Cheap |
| Files (upload) | 10 RPS | 30 RPS | Multipart parse + DB write |
| Files (download) | 100 RPS | 300 RPS | Static-content via Next.js |
| Combos / me / providers | 500 RPS | 1,500 RPS | Cached |
| WebSocket | 100 concurrent connections | 300 | Per-IP cap 5 |
**Cluster ceiling** (all endpoints combined, sustained): ~1,000 RPS
before p95 latency begins to climb. Scale horizontally beyond that
by adding replicas; the Caddy LB is stateless.
---
## 4. Resource budgets
| Resource | Per-replica cap | Notes |
|---|---|---|
| RSS memory | 1.5 GB | Spikes during audio/video gen; expect brief 2 GB |
| Event-loop lag (p99) | 50 ms | Alert via `clinic doctor` regression |
| Heap retained | 800 MB | Old-gen GC tuning in `node --max-old-space-size` |
| File descriptors | 2,000 | `ulimit -n 4096` recommended at host |
| DB connections (sql.js) | 1 per replica | sql.js is in-process; no pool needed |
| Redis connections | 20 per replica | Pooled; idle reaped at 5 min |
---
## 5. Cold-start budget
Next.js App Router cold-start on a fresh container:
| Phase | Budget |
|---|---|
| Container start → HTTP listening | ≤ 800 ms |
| First request TTFB (warm) | ≤ 200 ms |
| Translator registry bootstrap | ≤ 500 ms (one-time, first /v1/responses) |
**Measurement script**: `bin/cold-start-bench.sh` (already in the repo
since v3.8.36; `bin/` is the canonical scripts dir).
---
## 6. Regression gate (k6 reference, not yet implemented)
The sketch below shows how a future `benches/perf-gate.k6.js` script
would assert the SLOs above. Nothing in this section is committed or
wired into CI today — it is a design reference for follow-up work, not
a running gate.
```javascript
// benches/perf-gate.k6.js — pseudo-code; not yet committed
import http from 'k6/http';
import { check, Trend } from 'k6';
const responsesTTFB = new Trend('v1_responses_ttfb', true);
export const options = {
scenarios: {
smoke: {
executor: 'constant-vus',
vus: 10,
duration: '1m',
},
},
thresholds: {
'http_req_duration{endpoint:v1_responses}': ['p(95)<1800', 'p(99)<3500'],
'http_req_failed': ['rate<0.01'],
'v1_responses_ttfb': ['p(95)<900'],
},
};
export default function () {
const res = http.post(`${__ENV.BASE_URL}/api/v1/responses`, JSON.stringify({
model: 'gpt-4o-mini',
input: 'ping',
}), { headers: { 'Authorization': `Bearer ${__ENV.API_KEY}` }});
check(res, { 'status is 200': (r) => r.status === 200 });
responsesTTFB.add(res.timings.waiting);
}
```
---
## 7. Review log
| Date | Reviewer | Change |
|---|---|---|
| 2026-06-18 | security-circle lead | Initial per-endpoint budgets derived from 3-replica Caddy + Redis topology |
| 2026-07-18 | observability-circle | Clarified this doc ships zero enforcement today (no `bench/`/`benches/` dir, no CI gate) and fixed the stale "not yet committed" claim about `bin/cold-start-bench.sh` (present since v3.8.36). |
| 2026-07-18 (planned) | observability-circle | Wire `benches/perf-gate.k6.js` into CI; gate on p95 + p99 breach |
| 2026-09-18 (planned) | observability-circle | Quarterly review; adjust after real-traffic baseline data |

View File

@@ -1,273 +0,0 @@
---
title: "Combo Context Requirements Feature"
version: 3.8.50
lastUpdated: 2026-08-06
---
# Combo Context Requirements Feature
## Overview
The Context Requirements feature allows combo configurations to filter and sort targets based on their context window size. This is useful for use cases requiring large context windows like:
- Long document processing (100k+ tokens)
- Large codebase analysis
- Extensive conversation histories
- Multi-file code reviews
## Configuration
### Schema
Add `contextRequirements` to your combo's runtime config:
```json
{
"contextRequirements": {
"minContextWindow": 128000,
"preferLargeContext": true,
"contextFilterMode": "strict"
}
}
```
### Fields
#### `minContextWindow` (optional)
- **Type**: `number` (0 to 10,000,000)
- **Default**: `undefined` (no filtering)
- **Description**: Filters out models with context windows below this threshold
**Examples**:
- `32000` - Filter out models with <32K context
- `128000` - Require 128K+ context (GPT-4 Turbo, Claude 3)
- `200000` - Require 200K+ context (Claude 3 Opus)
- `1000000` - Require 1M+ context (Gemini 1.5 Pro)
#### `preferLargeContext` (optional)
- **Type**: `boolean`
- **Default**: `false`
- **Description**: When `true`, sorts remaining targets by context size (descending). Large context models are tried first.
#### `contextFilterMode` (optional)
- **Type**: `"strict"` | `"lenient"`
- **Default**: `"lenient"`
- **Description**: How to handle models with unknown context window limits
- `"strict"`: Excludes models with unknown context limits when a known-good target remains; fail-opens to unknowns if the pool would otherwise be empty (#8786)
- `"lenient"`: Includes models with unknown context limits
## Behavior
### Filtering Pipeline
Context requirements are applied after `filterTargetsByRequestCompatibility()`:
1. **Request compatibility filtering** - Removes models incompatible with request (tools, vision, structured output)
2. **Context requirements filtering** - Applies `minContextWindow` and `contextFilterMode`
3. **Context-based sorting** - If `preferLargeContext` is true, sorts by context size descending
### Filter Mode Logic
When `minContextWindow` is set:
**Lenient mode** (default):
- ✅ Includes models with context >= minContextWindow
- ✅ Includes models with unknown context limits
- ❌ Excludes models with context < minContextWindow
**Strict mode**:
- ✅ Includes models with context >= minContextWindow
- ❌ Excludes models with unknown context limits (when at least one known-good target remains)
- ❌ Excludes models with context < minContextWindow
- ⚠️ **Fail-open (#8786)**: if strict filtering would empty the pool and at least one
unknown-context target exists, those unknowns are restored instead of returning
`404 Combo has no executable targets`. Known-too-small targets are never resurrected.
When the pool is still empty (every known target is below `minContextWindow`), the
API returns `terminalReason: "context_requirements_exhausted"` with a recovery hint.
### Sorting Logic
When `preferLargeContext` is true:
- Models are sorted by context window size (descending)
- Unknown context models sort to the end
- Original strategy order is used as a tiebreaker
## Use Cases
### Example 1: Long Document Processing
```json
{
"name": "Document Analysis",
"strategy": "fusion",
"config": {
"contextRequirements": {
"minContextWindow": 128000,
"preferLargeContext": true,
"contextFilterMode": "strict"
}
}
}
```
This configuration:
- Requires 128K+ context window
- Prefers larger context models (Gemini 1.5 Pro > Claude 3 Opus > GPT-4 Turbo)
- Excludes models with unknown context limits
### Example 2: Large Codebase Analysis
```json
{
"name": "Code Review",
"strategy": "auto",
"config": {
"contextRequirements": {
"minContextWindow": 200000,
"preferLargeContext": true,
"contextFilterMode": "lenient"
}
}
}
```
This configuration:
- Requires 200K+ context window
- Prefers larger context models
- Includes models with unknown limits (lenient)
### Example 3: Prefer Large Context Without Strict Requirements
```json
{
"name": "Flexible Chat",
"strategy": "weighted",
"config": {
"contextRequirements": {
"preferLargeContext": true
}
}
}
```
This configuration:
- No minimum requirement (all models eligible)
- Sorts by context size (largest first)
- Useful when large context is preferred but not required
## API Response
When context requirements filter targets, the combo logger outputs:
```
[COMBO] Context requirements: filtered 10 → 3 targets (minContextWindow: 128000, mode: strict)
[COMBO] Context requirements: kept models gemini-1.5-pro, claude-3-opus-20240229, gpt-4-turbo
[COMBO] Context requirements: sorted by context size (descending): gemini-1.5-pro(1000000), claude-3-opus-20240229(200000), gpt-4-turbo(128000)
```
## Implementation Details
### Backend Module
`open-sse/services/combo/contextRequirements.ts`:
- `applyContextRequirements()` - Main filtering function
- `getTargetContextWindow()` - Context lookup helper
- Uses `getModelContextLimit()` from `modelCapabilities.ts`
### Integration Point
`open-sse/services/combo.ts` line 1187:
```typescript
orderedTargets = filterTargetsByRequestCompatibility(orderedTargets, body, log);
orderedTargets = applyContextRequirements(orderedTargets, config.contextRequirements, log);
```
### Schema Definition
`src/shared/validation/schemas/combo.ts`:
```typescript
contextRequirements: z
.object({
minContextWindow: z.coerce.number().int().min(0).max(10_000_000).optional(),
preferLargeContext: z.boolean().optional(),
contextFilterMode: z.enum(["strict", "lenient"]).optional(),
})
.strict()
.optional(),
```
## Testing
### Run Tests
```bash
# Unit tests (schema + logic)
npm test tests/unit/combo-context-requirements.test.ts
# Integration tests (end-to-end)
npm test tests/unit/combo/context-requirements-integration.test.ts
```
### Test Coverage
- Schema validation: 6 tests
- Filtering logic: 6 tests
- Integration: 5 tests
- **Total**: 17/17 passing ✅
## Troubleshooting
### All targets filtered out
**Problem**: All targets removed, combo returns "no compatible models"
**Solutions**:
1. Lower `minContextWindow` threshold
2. Switch to `"lenient"` mode to include unknown context models
3. Remove `minContextWindow` and use only `preferLargeContext`
### Unknown context models excluded
**Problem**: Custom/new models excluded even though they have large context
**Solutions**:
1. Switch to `"lenient"` mode (default)
2. Add model context limit to `modelCapabilities.ts`
3. Remove context filtering and rely on strategy order
### Sorting not applied
**Problem**: `preferLargeContext` doesn't change order
**Check**:
1. Verify `preferLargeContext: true` in config
2. Check if all targets have unknown context (all sort equal)
3. Verify multiple targets remain after filtering
## Related
- [Auto-Combo Routing Strategies](./routing/AUTO-COMBO.md)
- [Resilience Guide](./architecture/RESILIENCE_GUIDE.md)
## Version History
- **v3.8.47**: Initial implementation
- Added `contextRequirements` config
- Created backend filtering module
- Full test coverage (no dedicated dashboard UI yet — configure via combo JSON)

View File

@@ -1,232 +0,0 @@
# Runbook reagowania na incydenty — OmniRoute (2026-06-18)
**Status**: Dokument autorytatywny. Audyt 71 filarów (L61) odwołuje się do tego
dokumentu w bramce `Obs > 2.00`.
**Właściciel**: observability-circle (lead: security-circle lead).
**SLO**: zob. `docs/PERF_BUDGETS.md` § 1 (SLO najwyższego poziomu) oraz
`ops/slos.yaml` (forma maszynowo czytelna, generowana przez zespół Bifrost).
**Polityka ujawniania**: zob. `SECURITY.md` (wyłącznie ujawnianie podatności,
osobny przepływ).
Ten runbook to operacyjny playbook dla incydentów **niezwiązanych z bezpieczeństwem**:
awarie, regresje opóźnień, spalanie budżetu błędów oraz awarie po stronie
dostawców. Ujawnianie podatności pozostaje w `SECURITY.md`; nie kieruj
tych spraw przez ten runbook.
---
## 1. Skala ważności
| Sev | Definicja | Przykłady | Powiadomienie | Rozwiązanie do |
| --------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- | ----------------------------------------- | ---------------------------- |
| **SEV-1** | Awaria widoczna dla użytkownika; > 50 % żądań kończy się niepowodzeniem lub naruszenie SLO > 2x przez 5 min. | Klaster niedostępny; warstwa auth uszkodzona; powódź 5xx. | On-call P0 (natychmiast) | 4 h |
| **SEV-2** | Znacząca degradacja; naruszenie SLO 1,52x przez 15 min lub wpływ na jednego najemcę. | Jeden dostawca niedostępny; p95 > 1,5x budżetu; niekontrolowane rate-limity. | On-call P1 (15 min) | 24 h |
| **SEV-3** | Uśpiony błąd lub near-miss; brak bieżącego wpływu na użytkownika, ale budżet błędów zagrożony. | Wyciek pamięci w trendzie wzrostowym; circuit breaker wyłącza jednego dostawcę. | Slack `#omniroute-ops` (następny standup) | 7 d |
| **SEV-4** | Kosmetyczny / informacyjny. | Szum w logach; nieblokujący glitch UI. | Następny przegląd tygodniowy | Następny cykl refaktoryzacji |
**Eskalacja burn-rate** (zgodnie z `docs/PERF_BUDGETS.md` § 1): 6x przez 5 min
to SEV-1; 2x przez 1 h to SEV-2; utrzymanie < 1x przez 7 d obniża do SEV-3.
---
## 2. Źródła detekcji
| Źródło | Sygnał | Routing |
| --------------------------------- | ------------------------------------ | ------------------------------------- |
| Prometheus (`/metrics`) | Delty liczników (5xx, latency) | Alertmanager → PagerDuty |
| Panele SLO w Grafana | Panele burn-rate SLO | Slack `#omniroute-ops` |
| Sonda uptime (`/api/health/ping`) | 3 kolejne niepowodzenia z 3 regionów | Alertmanager → PagerDuty |
| Dependabot | Nowe CVE w zależności (CVSS ≥ 7) | GitHub Security → security-circle |
| Ręczny raport użytkownika | Zgłoszenie w Discord / GitHub issue | Triage przez dyżurnego (on-call) |
| Chaos-drill (kwartalny) | Wstrzyknięte awarie | Planowany drill; wyniki w `docs/ops/` |
Alerty **nie** idą na prywatne DM. Domyślny kanał to `#omniroute-ops`; PagerDuty
stronicuje rotację on-call. Pełna matryca alertów: `ops/alertmanager/rules.yml`
(gdy jest wdrożona; do tego czasu reguły są w konfiguracji Prometheus w
`deploy/observability/`).
---
## 3. Pierwsze 15 minut (SEV-1 / SEV-2)
1. **Potwierdź**. Otwórz panel SLO i sprawdź, czy alert jest prawdziwy, a nie
flapping. Jeśli flapping — wycisz na 15 min i zbadaj.
2. **Zadeklaruj**. Opublikuj w `#omniroute-ops`:
```
INCIDENT <sev> — <jedna linia objawu>
IC: @you
Status: investigating
Następna aktualizacja: <teraz + 15 min>
```
3. **Stabilizuj** przed diagnozą główną przyczyny. Preferowana kolejność:
- Odetnij zły deploy: `kubectl rollout undo deploy/omniroute` (lub
równoważne dla Twojego środowiska; zob. `docs/ops/DEPLOYMENT.md`).
- Przełącz combo / dostawcę: `POST /api/combos/:id/switch` lub MCP
`switch_combo`.
- Włącz tryb degradacji: ustaw
`OMNIROUTE_DEGRADATION_MODE=lite` (pomija niekrytyczne middleware).
- Rate-limit ruch wejściowy na edge, jeśli to flood.
4. **Aktualizuj** co 15 min do złagodzenia lub rozwiązania.
Nie debuguj w produkcji przy SEV-1. Przywróć ostatni znany dobry stan, potem
rób post-mortem offline.
---
## 4. Macierz runbooków
| Klasa awarii | Pierwszy ruch | Runbook |
| ------------------------------------ | ------------------------------------------------------------- | ---------------------------------------------------------- |
| Całkowity outage (wszystkie regiony) | Rollback ostatniego deployu; sprawdź status edge / DNS | `docs/ops/DEPLOYMENT.md` § rollback |
| Pojedynczy dostawca 5xx / timeout | Wyłącz dostawcę w combo; włącz fallback | `docs/architecture/RESILIENCE_GUIDE.md` |
| Spalanie budżetu błędów (latency) | Sprawdź p95 per-route; włącz compression / cache | `docs/PERF_BUDGETS.md` § 13 |
| Wyczerpanie połączeń SQLite | Zrestartuj z większym pool; sprawdź długotrwałe transakcje | `docs/architecture/CODEBASE_DOCUMENTATION.md` (warstwa DB) |
| Wyciek pamięci / OOM | Heap snapshot; rolling restart; oznacz SEV-3 na follow-up | wewnętrzny runbook profilowania |
| Wygaśnięcie certu / TLS | Wdróż odnowiony cert; sprawdź automatyzację renew | `docs/ops/TLS.md` (gdy jest; w przeciwnym razie ręcznie) |
| Awaria odświeżania tokena OAuth | Wymuś re-auth na dotkniętych kontach; sprawdź status dostawcy | `docs/security/OAUTH.md` |
| Powódź rate-limit (wejście) | Zaciśnij limity na kluczu API; zbanuj obrażający klucz | `docs/architecture/AUTHZ_GUIDE.md` |
| Awaria zależności (npm / CVE) | Pin / patch; w razie potrzeby wyłącz funkcję | `SECURITY.md` + Dependabot |
Każdy runbook musi kończyć się kryteriami **done** i właścicielem follow-upu.
---
## 5. Role w czasie incydentu
| Rola | Kto | Odpowiedzialności |
| --------------------------- | ------------------------------------ | ---------------------------------------------------------------- |
| **Incident Commander (IC)** | Dyżurny on-call (lub delegat) | Deklaruje sev, prowadzi mostek, zatwierdza mitigacje, zamyka |
| **Tech lead** | Inżynier znający dotknięty podsystem | Diagnozuje, proponuje mitigacje, wdraża poprawki |
| **Comms** | IC lub wolontariusz | Aktualizacje na Slacku, status page, odpowiedzi dla użytkowników |
| **Scribe** | Wolontariusz | Notatki z linii czasu na potrzeby post-mortem |
| **Executive sponsor** | Tylko SEV-1 | Escalation path; decyzje o zasobach |
Jedna osoba = jedna rola, gdy to możliwe. IC **nie** debuguje.
---
## 6. Komunikacja
- **Wewnętrzna**: `#omniroute-ops` jest źródłem prawdy. Wątek na incydent na
deklarację; wszystkie aktualizacje w wątku.
- **Zewnętrzna** (gdy dotyczy użytkowników zewnętrznych): status page
(status.omniroute.example — zastąp prawdziwym URL, gdy będzie live). SEV-1
dostaje publiczny post w ≤ 30 min; SEV-2 w ≤ 2 h, jeśli wpływ jest
zewnętrzny.
- **Nie** spekuluj o root cause publicznie. Podawaj objawy i ETA mitigacji.
- Po złagodzeniu: jedna wiadomość „mitigated, monitoring for 30 min”, potem
„resolved” z linkiem do post-mortem (gdy będzie gotowy).
---
## 7. Łagodzenie vs rozwiązanie
| Stan | Znaczenie | Kiedy używać |
| --------------- | -------------------------------------------------------- | ------------------------------------------ |
| `investigating` | Alert potwierdzony, przyczyna nieznana | Pierwsze 15 min |
| `mitigating` | Stosowana poprawka; wpływ powinien spadać | Podczas rollbacku / failover |
| `mitigated` | Wpływ na użytkownika ustał; root cause może być otwarty | Po udanej stabilizacji |
| `resolved` | Root cause znany i trwale naprawiony (lub zaakceptowany) | Po merge poprawki lub decyzji o akceptacji |
| `wontfix` | Zaakceptowane ryzyko; udokumentowane | Tylko SEV-3/4 za zgodą IC |
SEV-1/2 nie mogą pozostać w `mitigated` dłużej niż 7 dni bez eskalacji do
executive sponsora.
---
## 8. Post-mortem (obowiązkowy dla SEV-1/2)
Szablon (skopiuj do `docs/postmortems/YYYY-MM-DD-<slug>.md`):
```markdown
# Post-mortem: <tytuł>
- Data: YYYY-MM-DD
- Sev: SEV-N
- IC: @handle
- Czas trwania: wykrycie → mitigacja → rozwiązanie
- Dotknięci użytkownicy / budżet błędów spalony: <liczby>
## Streszczenie
<5 zdań, bez winy>
## Linia czasu
| Czas (UTC) | Event |
| ---------- | ----- |
| HH:MM | ... |
## Root cause
<co faktycznie się zepsuło; 5× dlaczego jeśli pomocne>
## Co poszło dobrze
- ...
## Co poszło źle
- ...
## Action items
| AI | Właściciel | Termin | Status |
| --- | ---------- | ---------- | ------ |
| ... | @handle | YYYY-MM-DD | open |
## Lekcje
<13 trwałe zmiany procesu lub kodu>
```
Zasady:
- **Bez obwiniania.** System zawiódł, nie osoba.
- Action items mają właściciela i termin; otwarte AI są przeglądane na
cotygodniowym standupie ops.
- Opublikuj w ciągu **5 dni roboczych** od rozwiązania.
- SEV-3 dostaje post-mortem tylko gdy IC uzna to za wartościowe; SEV-4 nigdy.
---
## 9. Kwartalne chaos-drille
Harmonogram (własność: observability-circle):
| Kwartał | Scenariusz | Sukces = |
| ------- | ------------------------------------------- | --------------------------------------------- |
| Q1 | Kill pod główny podczas peak load | Failover < 30 s; zero utraty danych |
| Q2 | Wstrzyknij 5xx u top-1 dostawcy | Combo przełącza się; budżet błędów trzyma się |
| Q3 | Partycja sieci do SQLite (gdy sklastrowany) | Degradacja read-only; brak korupcji |
| Q4 | Wygaśnięcie certu TLS (staging) | Alert odpala; renew w SLO |
Wyniki lądują w `docs/ops/chaos/YYYY-QN.md`. Niezaliczony drill otwiera SEV-3
z AI na lukę.
---
## 10. Powiązane dokumenty
| Dokument | Rola |
| --------------------------------------- | ------------------------------------- |
| `docs/PERF_BUDGETS.md` | SLO, budżety błędów, progi burn-rate |
| `ops/slos.yaml` | Maszynowa forma SLO (Bifrost) |
| `SECURITY.md` | Ujawnianie podatności (osobny flow) |
| `docs/architecture/RESILIENCE_GUIDE.md` | Fallback, circuit breaker, degradacja |
| `docs/ops/DEPLOYMENT.md` | Deploy / rollback |
| `docs/architecture/AUTHZ_GUIDE.md` | Nadużycia kluczy API, rate-limity |
| `docs/postmortems/` | Archiwum wpisów post-mortem |
---
## 11. Historia zmian
| Data | Zmiana |
| ---------- | ---------------------------------------------- |
| 2026-06-18 | Wstępna wersja autorytatywna (L61 / gate Obs). |
---
_Ten dokument jest autorytatywny dla operacyjnego reagowania na incydenty.
Poprawki: PR do `docs/INCIDENT_RESPONSE.md` z recenzją observability-circle._

View File

@@ -1,231 +0,0 @@
# Budżety wydajności — OmniRoute (2026-06-18)
**Status**: Miarodajny. Cele SLO, do których odwołuje się audyt 71 filarów (L13)
przy bramce `Perf > 2.00`.
**Metodyka**: budżety opóźnień p50/p95/p99 per endpoint oraz
nadrzędne SLO dostępności. Budżety wyprowadzono z topologii 3 replik
Caddy + Redis (commit `038439fa7`); korygować przy zmianie infrastruktury.
**Egzekwowanie**: na razie brak. § 6 szkicuje skrypt k6 `benches/perf-gate.k6.js`,
który asertowałby poniższe SLO, lecz jest to odniesienie projektowe,
a nie zacommitowany plik — w repozytorium nie ma dziś katalogu `bench/` ani `benches/`.
Ten dokument służy wyłącznie do ustalania celów, dopóki bramka CI
nie powstanie jako praca następcza.
**Częstotliwość ponownej oceny**: kwartalnie lub przy każdej istotnej zmianie infrastruktury.
---
## 1. Nadrzędne SLO
| SLO | Cel | Okno | Page przy naruszeniu |
| ------------------------------------------------------------- | ------------------------ | --------------- | -------------------- |
| **Dostępność** (2xx lub 4xx dla /v1/* i /api/settings/*) | 99.9% | rolling 30 days | on-call P2 |
| **Tempo spalania error budget** (znormalizowany wskaźnik 1xx) | < 2x for 1h, < 6x for 5m | 1h / 5m windows | on-call P1 |
| **Zagregowane opóźnienie p95** (wszystkie /v1/*) | ≤ 1.5 s | rolling 5 min | on-call P2 |
| **Zagregowane opóźnienie p99** (wszystkie /v1/*) | ≤ 4.0 s | rolling 5 min | on-call P2 |
**Error budget**: okno 30-dniowe = 43,2 minuty niedostępności przy
99.9%. Tempo spalania > 2x to P2; > 6x to P1.
---
## 2. Budżety opóźnień per endpoint
Wszystkie budżety mierzone **po stronie serwera** (od wejścia do Next.js Route Handler
do startu odpowiedzi albo do ostatniego bajtu przy streamingu). Endpointy streamowe
mierzone do time-of-first-byte (TTFB), ponieważ body jest przyrostowe.
### 2.1 Endpointy inferencji (ścieżka krytyczna)
| Endpoint | Method | p50 | p95 | p99 | Notes |
| ----------------------------------------- | ----------- | ------ | ------ | ------ | ------------------------------------------------------------- |
| `/v1/responses` (non-stream) | POST | 800 ms | 1.8 s | 3.5 s | Obejmuje translator + roundtrip do providera |
| `/v1/responses` (stream) | POST (TTFB) | 350 ms | 900 ms | 1.8 s | Tylko TTFB; całkowity czas nieograniczony |
| `/v1/relay/chat/completions` (non-stream) | POST | 1.0 s | 2.2 s | 4.0 s | Obejmuje sprawdzenie rate-limit per-(token,IP) |
| `/v1/relay/chat/completions` (stream) | POST (TTFB) | 400 ms | 1.0 s | 2.0 s | |
| `/v1/embeddings` | POST | 300 ms | 700 ms | 1.4 s | Czysty roundtrip do providera; tani |
| `/v1/rerank` | POST | 600 ms | 1.4 s | 2.8 s | |
| `/v1/moderations` | POST | 250 ms | 600 ms | 1.2 s | Lekka klasyfikacja |
| `/v1/audio/speech` | POST | 1.2 s | 3.0 s | 6.0 s | Synteza audio jest wolna; budżet to odzwierciedla |
| `/v1/audio/transcriptions` | POST | 2.0 s | 5.0 s | 10.0 s | STT ograniczony czasem audio + rozmiarem modelu |
| `/v1/images/generations` | POST | 4.0 s | 8.0 s | 15.0 s | Generacja obrazów ograniczona asynchronicznie przez providera |
| `/v1/videos/generations` | POST (TTFB) | 600 ms | 1.5 s | 3.0 s | Async; klient odpytuje `/v1/videos/{id}` |
| `/v1/music/generations` | POST | 3.0 s | 6.0 s | 12.0 s | |
### 2.2 Pliki + batche
| Endpoint | Method | p50 | p95 | p99 | Notes |
| ------------------------------------- | ------ | ------ | ------ | ------ | ---------------------------------------- |
| `/v1/files` (GET) | GET | 80 ms | 200 ms | 400 ms | Lista z cache |
| `/v1/files` (POST upload) | POST | 500 ms | 1.2 s | 2.5 s | Limit 25 MB; parsowanie multipart |
| `/v1/files/{id}` (GET) | GET | 60 ms | 150 ms | 300 ms | |
| `/v1/files/{id}` (DELETE) | DELETE | 80 ms | 200 ms | 400 ms | |
| `/v1/files/{id}/content` (download) | GET | 100 ms | 300 ms | 600 ms | + przepustowość per-MB |
| `/v1/batches` (GET) | GET | 150 ms | 400 ms | 800 ms | |
| `/v1/batches` (POST create) | POST | 200 ms | 500 ms | 1.0 s | Waliduje plik wejściowy, potem enqueuuje |
| `/v1/batches/{id}` (GET) | GET | 100 ms | 300 ms | 600 ms | |
| `/v1/batches/{id}` (DELETE) | DELETE | 100 ms | 300 ms | 600 ms | |
| `/v1/batches/delete-completed` (POST) | POST | 400 ms | 1.0 s | 2.0 s | Masowe usuwanie; n wierszy |
### 2.3 Agenci
| Endpoint | Method | p50 | p95 | p99 | Notes |
| -------------------------------- | ------ | ------ | ------ | ------ | ------------------------------------------------------------- |
| `/v1/agents/health` | GET | 1.5 s | 4.5 s | 5.0 s | Limit timeout 5s per provider; oczekiwane łącznie 3 providery |
| `/v1/agents/credentials` | GET | 100 ms | 250 ms | 500 ms | Tylko metadane; wartości nigdy nie są zwracane |
| `/v1/agents/tasks` (GET list) | GET | 150 ms | 400 ms | 800 ms | |
| `/v1/agents/tasks` (POST create) | POST | 250 ms | 600 ms | 1.2 s | Tylko enqueuuje; nie uruchamia agenta |
| `/v1/agents/tasks/{id}` (GET) | GET | 100 ms | 300 ms | 600 ms | |
| `/v1/agents/tasks/{id}` (DELETE) | DELETE | 150 ms | 400 ms | 800 ms | |
### 2.4 Combos / me / providers
| Endpoint | Method | p50 | p95 | p99 |
| --------------------------------- | ------ | ------ | ------ | ------ |
| `/v1/combos` | GET | 80 ms | 200 ms | 400 ms |
| `/v1/me/status` | GET | 60 ms | 150 ms | 300 ms |
| `/v1/providers/{provider}/models` | GET | 100 ms | 250 ms | 500 ms |
### 2.5 Web / search
| Endpoint | Method | p50 | p95 | p99 | Notes |
| --------------- | ------ | ------ | ----- | ----- | ---------------------------------------------- |
| `/v1/web/fetch` | POST | 1.5 s | 4.0 s | 8.0 s | Limit timeout 10s; głębokość rekurencji 3 |
| `/v1/search` | POST | 800 ms | 2.0 s | 4.0 s | Opóźnienie wyszukiwania u providera bywa różne |
### 2.6 Shim VSCode-CLI (scoped tokenem)
To ścieżki legacy passthrough. Budżety są ciaśniejsze, bo
rozszerzenie VSCode-CLI wywołuje je często w ciasnych pętlach.
| Endpoint | Method | p50 | p95 | p99 |
| ---------------------------------------------- | ------ | ------ | ------ | ------ |
| `/v1/vscode/{token}/v1/chat/completions` | POST | 700 ms | 1.6 s | 3.0 s |
| `/v1/vscode/{token}/v1/models` | GET | 60 ms | 150 ms | 300 ms |
| `/v1/vscode/{token}/combos` | GET | 80 ms | 200 ms | 400 ms |
| `/v1/vscode/{token}/chat/completions` (legacy) | POST | 700 ms | 1.6 s | 3.0 s |
| `/v1/vscode/{token}/models` (legacy) | GET | 60 ms | 150 ms | 300 ms |
| `/v1/vscode/{token}/responses` | POST | 800 ms | 1.8 s | 3.5 s |
### 2.7 Zarządzanie / settings
Endpointy zarządzania są wyłącznie operatorskie i nie należą do ścieżki krytycznej.
Budżety ustawiono konserwatywnie; naruszenia nie page'ują on-call, ale
są flagowane w tygodniowym przeglądzie wydajności.
| Endpoint group | p50 | p95 | p99 |
| ------------------------------------- | ------ | ------ | ------ |
| `/api/settings/*` (GET) | 100 ms | 300 ms | 600 ms |
| `/api/settings/*` (POST/PATCH/DELETE) | 200 ms | 500 ms | 1.0 s |
| `/api/keys/*` (CRUD) | 150 ms | 400 ms | 800 ms |
| `/api/quota/*` (CRUD) | 150 ms | 400 ms | 800 ms |
| `/api/monitoring/health` (heavy) | 500 ms | 1.5 s | 3.0 s |
### 2.8 Publiczne sondy
| Endpoint | Method | p50 | p95 | p99 |
| ------------------------ | ------ | ----- | ----- | ------------------------------------- |
| `/api/health/ping` | GET | 5 ms | 20 ms | 50 ms |
| `/api/monitoring/health` | GET | 5 ms | 20 ms | 50 ms |
| `/api/docs` | GET | 20 ms | 80 ms | 200 ms (HTML shell, no provider call) |
---
## 3. Cele przepustowości
| Tier | Per-replica RPS | Cluster RPS (3 replicas) | Notes |
| ----------------------- | -------------------------- | ------------------------ | --------------------------------------------------- |
| Inference (non-stream) | 50 RPS | 150 RPS | Ograniczone przez quota providera + CPU translatora |
| Inference (stream) | 25 concurrent streams | 75 streams | Ograniczone przez event-loop Node + pamięć |
| Embeddings | 200 RPS | 600 RPS | Tanie |
| Files (upload) | 10 RPS | 30 RPS | Parsowanie multipart + zapis do DB |
| Files (download) | 100 RPS | 300 RPS | Treść statyczna przez Next.js |
| Combos / me / providers | 500 RPS | 1,500 RPS | Z cache |
| WebSocket | 100 concurrent connections | 300 | Limit per-IP: 5 |
**Sufit klastra** (wszystkie endpointy łącznie, obciążenie ciągłe): ~1 000 RPS,
zanim p95 latency zacznie rosnąć. Powyżej tego skalować horyzontalnie
przez dodawanie replik; Caddy LB jest bezstanowy.
---
## 4. Budżety zasobów
| Resource | Per-replica cap | Notes |
| ----------------------- | --------------- | ------------------------------------------------------ |
| RSS memory | 1.5 GB | Skoki przy gen. audio/wideo; spodziewane chwilowe 2 GB |
| Event-loop lag (p99) | 50 ms | Alert przez regresję `clinic doctor` |
| Heap retained | 800 MB | Strojenie old-gen GC w `node --max-old-space-size` |
| File descriptors | 2,000 | Na hoście zalecane `ulimit -n 4096` |
| DB connections (sql.js) | 1 per replica | sql.js działa in-process; pool nie jest potrzebny |
| Redis connections | 20 per replica | Z poola; idle usuwane po 5 min |
---
## 5. Budżet cold-start
Cold-start Next.js App Router na świeżym kontenerze:
| Phase | Budget |
| -------------------------------- | ---------------------------------------- |
| Container start → HTTP listening | ≤ 800 ms |
| First request TTFB (warm) | ≤ 200 ms |
| Translator registry bootstrap | ≤ 500 ms (one-time, first /v1/responses) |
**Skrypt pomiarowy**: `bin/cold-start-bench.sh` (już w repozytorium
od v3.8.36; `bin/` to kanoniczny katalog skryptów).
---
## 6. Bramka regresji (odniesienie k6, jeszcze niezaimplementowane)
Poniższy szkic pokazuje, jak przyszły skrypt `benches/perf-gate.k6.js`
asertowałby powyższe SLO. Nic z tej sekcji nie jest dziś zacommitowane ani
podpięte do CI — to odniesienie projektowe do pracy następczej, a nie
działająca bramka.
```javascript
// benches/perf-gate.k6.js — pseudo-code; not yet committed
import http from "k6/http";
import { check, Trend } from "k6";
const responsesTTFB = new Trend("v1_responses_ttfb", true);
export const options = {
scenarios: {
smoke: {
executor: "constant-vus",
vus: 10,
duration: "1m",
},
},
thresholds: {
"http_req_duration{endpoint:v1_responses}": ["p(95)<1800", "p(99)<3500"],
http_req_failed: ["rate<0.01"],
v1_responses_ttfb: ["p(95)<900"],
},
};
export default function () {
const res = http.post(
`${__ENV.BASE_URL}/api/v1/responses`,
JSON.stringify({
model: "gpt-4o-mini",
input: "ping",
}),
{ headers: { Authorization: `Bearer ${__ENV.API_KEY}` } }
);
check(res, { "status is 200": (r) => r.status === 200 });
responsesTTFB.add(res.timings.waiting);
}
```
---
## 7. Dziennik przeglądów
| Date | Reviewer | Change |
| -------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 2026-06-18 | security-circle lead | Wstępne budżety per endpoint wyprowadzone z topologii 3 replik Caddy + Redis |
| 2026-07-18 | observability-circle | Doprecyzowano, że dokument dziś nie egzekwuje nic (brak katalogu `bench/`/`benches/`, brak bramki CI) oraz poprawiono nieaktualne twierdzenie „not yet committed” o `bin/cold-start-bench.sh` (obecny od v3.8.36). |
| 2026-07-18 (planned) | observability-circle | Podpięcie `benches/perf-gate.k6.js` do CI; bramka przy naruszeniu p95 + p99 |
| 2026-09-18 (planned) | observability-circle | Przegląd kwartalny; korekta po danych bazowych z ruchu produkcyjnego |

View File

@@ -1,262 +0,0 @@
# Funkcja wymagań kontekstu combo (Context Requirements)
## Przegląd
Funkcja Context Requirements pozwala konfiguracjom combo filtrować i sortować cele (targets) na podstawie rozmiaru okna kontekstu. Jest to przydatne w przypadkach użycia wymagających dużych okien kontekstu, takich jak:
- Przetwarzanie długich dokumentów (100k+ tokenów)
- Analiza dużych baz kodu
- Rozbudowane historie rozmów
- Przeglądy kodu obejmujące wiele plików
## Konfiguracja
### Schemat
Dodaj `contextRequirements` do runtime config swojego combo:
```json
{
"contextRequirements": {
"minContextWindow": 128000,
"preferLargeContext": true,
"contextFilterMode": "strict"
}
}
```
### Pola
#### `minContextWindow` (opcjonalne)
- **Typ**: `number` (0 do 10,000,000)
- **Domyślnie**: `undefined` (bez filtrowania)
- **Opis**: Odfiltrowuje modele z oknami kontekstu poniżej tego progu
**Przykłady**:
- `32000` - Odfiltruj modele z kontekstem <32K
- `128000` - Wymagaj kontekstu 128K+ (GPT-4 Turbo, Claude 3)
- `200000` - Wymagaj kontekstu 200K+ (Claude 3 Opus)
- `1000000` - Wymagaj kontekstu 1M+ (Gemini 1.5 Pro)
#### `preferLargeContext` (opcjonalne)
- **Typ**: `boolean`
- **Domyślnie**: `false`
- **Opis**: Gdy `true`, sortuje pozostałe cele według rozmiaru kontekstu (malejąco). Modele z dużym kontekstem są próbowane jako pierwsze.
#### `contextFilterMode` (opcjonalne)
- **Typ**: `"strict"` | `"lenient"`
- **Domyślnie**: `"lenient"`
- **Opis**: Sposób obsługi modeli z nieznanymi limitami okna kontekstu
- `"strict"`: Wyklucza modele z nieznanymi limitami kontekstu
- `"lenient"`: Uwzględnia modele z nieznanymi limitami kontekstu
## Zachowanie
### Potok filtrowania
Wymagania kontekstu są stosowane po `filterTargetsByRequestCompatibility()`:
1. **Filtrowanie zgodności żądania** - Usuwa modele niekompatybilne z żądaniem (tools, vision, structured output)
2. **Filtrowanie wymagań kontekstu** - Stosuje `minContextWindow` i `contextFilterMode`
3. **Sortowanie według kontekstu** - Jeśli `preferLargeContext` jest true, sortuje malejąco według rozmiaru kontekstu
### Logika trybu filtrowania
Gdy ustawiono `minContextWindow`:
**Tryb lenient** (domyślny):
- ✅ Uwzględnia modele z kontekstem >= minContextWindow
- ✅ Uwzględnia modele z nieznanymi limitami kontekstu
- ❌ Wyklucza modele z kontekstem < minContextWindow
**Tryb strict**:
- ✅ Uwzględnia modele z kontekstem >= minContextWindow
- ❌ Wyklucza modele z nieznanymi limitami kontekstu
- ❌ Wyklucza modele z kontekstem < minContextWindow
### Logika sortowania
Gdy `preferLargeContext` jest true:
- Modele są sortowane według rozmiaru okna kontekstu (malejąco)
- Modele z nieznanym kontekstem trafiają na koniec
- Oryginalna kolejność strategii służy jako rozstrzygnięcie remisów
## Przypadki użycia
### Przykład 1: Przetwarzanie długich dokumentów
```json
{
"name": "Document Analysis",
"strategy": "fusion",
"config": {
"contextRequirements": {
"minContextWindow": 128000,
"preferLargeContext": true,
"contextFilterMode": "strict"
}
}
}
```
Ta konfiguracja:
- Wymaga okna kontekstu 128K+
- Preferuje modele z większym kontekstem (Gemini 1.5 Pro > Claude 3 Opus > GPT-4 Turbo)
- Wyklucza modele z nieznanymi limitami kontekstu
### Przykład 2: Analiza dużej bazy kodu
```json
{
"name": "Code Review",
"strategy": "auto",
"config": {
"contextRequirements": {
"minContextWindow": 200000,
"preferLargeContext": true,
"contextFilterMode": "lenient"
}
}
}
```
Ta konfiguracja:
- Wymaga okna kontekstu 200K+
- Preferuje modele z większym kontekstem
- Uwzględnia modele z nieznanymi limitami (lenient)
### Przykład 3: Preferencja dużego kontekstu bez ścisłych wymagań
```json
{
"name": "Flexible Chat",
"strategy": "weighted",
"config": {
"contextRequirements": {
"preferLargeContext": true
}
}
}
```
Ta konfiguracja:
- Brak minimalnego wymagania (wszystkie modele kwalifikują się)
- Sortuje według rozmiaru kontekstu (największy najpierw)
- Przydatne, gdy duży kontekst jest preferowany, ale nie wymagany
## Odpowiedź API
Gdy wymagania kontekstu filtrują cele, logger combo wypisuje:
```
[COMBO] Context requirements: filtered 10 → 3 targets (minContextWindow: 128000, mode: strict)
[COMBO] Context requirements: kept models gemini-1.5-pro, claude-3-opus-20240229, gpt-4-turbo
[COMBO] Context requirements: sorted by context size (descending): gemini-1.5-pro(1000000), claude-3-opus-20240229(200000), gpt-4-turbo(128000)
```
## Szczegóły implementacji
### Moduł backendu
`open-sse/services/combo/contextRequirements.ts`:
- `applyContextRequirements()` - Główna funkcja filtrowania
- `getTargetContextWindow()` - Pomocnicza funkcja wyszukiwania kontekstu
- Używa `getModelContextLimit()` z `modelCapabilities.ts`
### Punkt integracji
`open-sse/services/combo.ts` linia 1187:
```typescript
orderedTargets = filterTargetsByRequestCompatibility(orderedTargets, body, log);
orderedTargets = applyContextRequirements(orderedTargets, config.contextRequirements, log);
```
### Definicja schematu
`src/shared/validation/schemas/combo.ts`:
```typescript
contextRequirements: z
.object({
minContextWindow: z.coerce.number().int().min(0).max(10_000_000).optional(),
preferLargeContext: z.boolean().optional(),
contextFilterMode: z.enum(["strict", "lenient"]).optional(),
})
.strict()
.optional(),
```
## Testowanie
### Uruchamianie testów
```bash
# Unit tests (schema + logic)
npm test tests/unit/combo-context-requirements.test.ts
# Integration tests (end-to-end)
npm test tests/unit/combo/context-requirements-integration.test.ts
```
### Pokrycie testami
- Walidacja schematu: 6 testów
- Logika filtrowania: 6 testów
- Integracja: 5 testów
- **Razem**: 17/17 przechodzi ✅
## Rozwiązywanie problemów
### Wszystkie cele odfiltrowane
**Problem**: Wszystkie cele usunięte, combo zwraca „no compatible models”
**Rozwiązania**:
1. Obniż próg `minContextWindow`
2. Przełącz na tryb `"lenient"`, aby uwzględnić modele z nieznanym kontekstem
3. Usuń `minContextWindow` i używaj wyłącznie `preferLargeContext`
### Modele z nieznanym kontekstem wykluczone
**Problem**: Niestandardowe/nowe modele wykluczone, mimo że mają duży kontekst
**Rozwiązania**:
1. Przełącz na tryb `"lenient"` (domyślny)
2. Dodaj limit kontekstu modelu w `modelCapabilities.ts`
3. Usuń filtrowanie kontekstu i polegaj na kolejności strategii
### Sortowanie nie jest stosowane
**Problem**: `preferLargeContext` nie zmienia kolejności
**Sprawdź**:
1. Zweryfikuj `preferLargeContext: true` w config
2. Sprawdź, czy wszystkie cele mają nieznany kontekst (wszystkie sortują się równo)
3. Upewnij się, że po filtrowaniu pozostało wiele celów
## Powiązane
- [Strategie routingu Auto-Combo](./routing/AUTO-COMBO.md)
- [Przewodnik po odporności (Resilience)](./architecture/RESILIENCE_GUIDE.md)
## Historia wersji
- **v3.8.47**: Pierwsza implementacja
- Dodano config `contextRequirements`
- Utworzono backendowy moduł filtrowania
- Pełne pokrycie testami (brak jeszcze dedykowanego UI w dashboardzie — konfiguracja przez combo JSON)

View File

@@ -1,83 +0,0 @@
# Analiza konfliktu portów proxy
## Podsumowanie
W systemie proxy auto-select / proxyFallback / proxyEgress **nie ma konfliktu portów**.
Podsystem proxy używa **wcześniej przypisanych portów z rejestru** — nigdy nie bindowuje
się bezpośrednio do portów TCP. Prawdziwa historia EADDRINUSE leży w warstwie
**process supervisor**, gdzie główny port nasłuchu serwera może kolidować podczas
restartów w pętli awarii (crash-loop).
---
## Podsystem proxy: brak bindowania portów
| Moduł | Co robi |
| ---------------------- | ----------------------------------------------------------------------------------------------------- |
| `proxyAutoSelector.ts` | Wybiera konfigurację proxy z DB, stosując health scores i grupy rotacji |
| `proxyFallback.ts` | Implementuje strategie retry/fallback, gdy wybrane proxy zawodzi (spróbuj innego proxy, potem direct) |
| `proxyEgress.ts` | Sondowanie/propagacja informacji o egress IP do logowania — używa HTTP echo, nie bindowania portów |
| `proxyDispatcher.ts` | Tworzy dispatchery `undici.ProxyAgent` — to poziom HTTP (forward proxy), nie gniazda nasłuchu TCP |
| `proxyFetch.ts` | Spatchowany globalny fetch, który stosuje dispatchery proxy na poziomie undici |
Żaden z tych modułów nie wywołuje `net.createServer()`, `http.createServer()` ani `app.listen()`.
Zarządzanie portami odbywa się wyłącznie w cyklu życia żądania — undici zarządza pulą
połączeń TCP wewnętrznie.
**Przepływ fallback** (z `proxyFetch.ts` `runWithProxyContext`):
1. Spróbuj przypisanego proxy → proxy dispatcher
2. Jeśli nieosiągalne → direct fallback (bez dispatchera)
3. Jeśli nadal zawodzi → błąd propagowany w górę
W tym przepływie nie następuje alokacja ani zwalnianie portów.
---
## Prawdziwa przyczyna EADDRINUSE: wyścig restartu w crash-loop
Rzeczywisty konflikt portów był w **process supervisor** (`bin/cli/runtime/`):
| Plik | Rola |
| ----------------------- | --------------------------------------------------------------------------------- |
| `processSupervisor.mjs` | `ServerSupervisor` — uruchamia proces potomny, monitoruje kod wyjścia, restartuje |
| `supervisorPolicy.mjs` | `waitUntilPortFree()`, `isPortFree()`, stałe polityki restartu |
**Przyczyna główna:** Gdy proces potomny serwera ulegał awarii i był natychmiast restartowany,
OS nie zdążył jeszcze zwolnić gniazda nasłuchu (TIME_WAIT / TCP lingering). Próba restartu
bindowała ten sam port i natychmiast kończyła się `EADDRINUSE`, powodując
kolejną awarię → kolejny restart → wyczerpany budżet restartów → gateway martwy.
**Poprawka (#4425, w `supervisorPolicy.mjs`):**
1. Dodano `isPortFree(port)` — próbuje `net.createServer().listen()` na docelowym
porcie; zwraca `false` przy EADDRINUSE.
2. Dodano `waitUntilPortFree(port, timeoutMs=10000, intervalMs=250)` — odpytuje co 250ms
przez maks. 10s, aż port będzie wolny, dopiero potem pozwala na restart.
3. Podniesiono `RESTART_RESET_MS` z 30s → 60s — okno awarii było zbyt krótkie, co powodowało
szybkie kaskadowe restarty w obrębie okna.
4. Podniesiono `DEFAULT_MAX_RESTARTS` z 2 → 3 — większy zapas na przejściowe awarie.
Narzędzia `writePidFile()` / `killAllSubprocesses()` / `cleanupPidFile()` w
`bin/cli/utils/pid.mjs` zapewniają czysty cykl życia pliku PID.
## Powiązane: Live-Dashboard EADDRINUSE (#6324)
Równoległa poprawka (`live-ws-eaddrinuse-6324.test.ts`) gwarantuje, że `startLiveDashboardServer()`
odrzuca z właściwym błędem `EADDRINUSE` (zamiast nieobsłużonego zdarzenia socket 'error',
które crashowałoby proces). Serwer dashboardu używa osobnego portu względem głównego
serwera API, więc gdy oba są skonfigurowane na ten sam port, drugie bindowanie kończy się
niepowodzeniem w sposób kontrolowany (gracefully).
---
## Stan obecny
| Ryzyko | Status | Pozostało |
| -------------------------------------------- | ----------------------- | --------- |
| Supervisor restart EADDRINUSE | **Naprawione** (#4425) | Brak |
| LiveWS port clash | **Naprawione** (#6324) | Brak |
| Proxy selection port clash | **Nigdy nie dotyczyło** | Brak |
| Two Redis CLIENT factories bind no TCP ports | **Nigdy nie dotyczyło** | Brak |
Nie są potrzebne dalsze działania w sprawie konfliktu portów.

View File

@@ -1,370 +0,0 @@
# Subskrypcje proxy operatora (styl Karing)
> Notatki projektowe i implementacyjne dla operatorowego przepływu subskrypcji
> proxy w OmniRoute. To jest cięcie v1: pojedynczy operator wkleja linki
> subskrypcji, wybiera tryb (global lub rule), a OmniRoute wiąże wynikową pulę
> proxy z istniejącą rezolucją scope. Multi-tenant per-API-key, zaawansowane
> reguły ruchu, wagi per-rule sterowane latencją itd. są jawnie poza zakresem
> i wymienione w §7.
---
## 1. Motywacja
Dziś pula proxy OmniRoute jest ręcznie kuratorowana: każdy węzeł żyje w
`proxy_registry` z ręcznie wpisanym host/port/credentials, a każde powiązanie z
upstreamowymi dispatcherami (account → provider → combo → global → direct) to
ręczny wiersz `proxy_assignments`. Operatorzy, którzy już utrzymują subskrypcję
Clash/V2Ray/sing-box (np. z usługi airport), muszą przepisywać każdy węzeł do
OmniRoute i ponownie je wiązać przy każdej zmianie listy upstream.
Celem v1 jest uczynienie OmniRoute first-class dla subskrypcji
**dostarczanych przez operatora**, podobnie jak Karing / Clash / sing-box
pozwalają wkleić URL `https://...` i zostawić zarządzanie cyklem życia klientowi.
## 2. Historie użytkownika
| # | Jako | Chcę | Aby |
| --- | -------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| U1 | Operator | wkleić URL subskrypcji raz | nie przepisywać węzłów przy każdym odświeżeniu airport |
| U2 | Operator | włączać/wyłączać subskrypcję | móc wrócić do direct bez usuwania URL |
| U3 | Operator | wybrać tryb **global** | cały ruch każdego providera wychodził przez subskrypcję |
| U4 | Operator | wybrać tryb **rule** i wskazać konkretnych providerów | tylko wybrani providerzy szli przez proxy; pozostali zostawali direct |
| U5 | Operator | podać lokalny endpoint SOCKS5 sing-box/clash | węzły SS/VMess/Trojan/VLESS (których dispatcher OmniRoute nie mówi natywnie) stawały się używalne przez lokalny mostek kernela |
| U6 | Operator | widzieć status pobrania i niedawną zredagowaną (redacted) sumę węzłów | debugować „dlaczego pusto / błąd” bez wycieku credentials |
## 3. Poza zakresem (v1)
- Nadpisania subskrypcji per-API-key (multi-tenant). v1 jest wyłącznie operatorskie.
- Reguły ruchu per-provider poza `global` / `rule-on-selected-providers`.
- Inteligentny routing oparty o latencję między węzłami subskrypcji a innymi pulami
(istniejące `resolveProxyForConnectionFromRegistry` już to robi dla puli
globalnej; v1 tylko dokłada do niej węzły subskrypcji).
- Auto-import URL/hasła z nagłówków lub query params.
- Mitygacja SSRF poza endpointami local-core wyłącznie na loopback (sam URL
subskrypcji jest kontrolowany przez operatora, więc ufamy mu tak samo jak
dzisiejszym URL-om providerów upstream).
## 4. Architektura
```
┌─────────────────────────────────────────┐
│ dashboard / settings / 代理 / 订阅代理 │
│ (client component, SubscriptionTab) │
└──────────────────┬──────────────────────┘
│ fetch
┌────────────────────────────────────────────────────────┐
│ /api/v1/management/proxy-subscriptions │
│ ├ GET list │
│ ├ POST create │
│ ├ GET /:id │
│ ├ PATCH /:id │
│ ├ DELETE /:id │
│ ├ POST /:id/refresh │
│ └ GET /:id/nodes │
└────────────────────────┬───────────────────────────────┘
│ uses
┌────────────────────────────────────────────────────────┐
│ src/lib/proxySubscription/ │
│ ├ parse.ts (Clash YAML / V2Ray JSON / URIs) │
│ ├ subscriptionService.ts │
│ │ CRUD, sync, apply, unapply, scheduler │
│ └ index.ts (barrel) │
└──────────┬─────────────────────────────┬───────────────┘
│ upsert/scope-bind │ DB
▼ ▼
┌─────────────────────────┐ ┌──────────────────────────┐
│ proxy_registry │ │ proxy_subscriptions │
│ (existing) + │ │ (NEW — subscription │
│ subscription_id column │ │ metadata + scheduler │
│ + status/health checks │ │ state) │
└─────────────────────────┘ └──────────────────────────┘
▼ (existing)
resolveProxyForConnectionFromRegistry
hasBlockingProxyAssignment (fail-closed)
proxyDispatcher (open-sse/utils/proxyDispatcher)
```
Kluczowa decyzja projektowa: **nie wymyślamy nowego scope ani pipelineu routingu**.
Upsertujemy węzły pochodzące z subskrypcji do `proxy_registry` z `source =
'subscription'` + `subscription_id`, a następnie `applySubscription()` przechodzi
istniejące API `addProxyToScopePool(scope, scopeId, proxyId)`. Dzięki temu:
- Istniejąca rotacja, health checki i strażniki fail-closed działają „za darmo”.
- Istniejące dashboardy (ProxyPoolTab, SourceToggleBar, GlobalConfigTab) działają
bez zmian — węzły subskrypcji po prostu pojawiają się w puli z odznaką `source`.
- Usunięcie/wyłączenie subskrypcji czysto usuwa jej powiązania bez
ruszania ręcznych proxy.
## 5. Model danych
### 5.1 Nowa tabela `proxy_subscriptions`
| Column | Type | Notes |
| ------------------------- | -------------------------------- | ---------------------------------------------------------------------- |
| `id` | TEXT PK | UUID |
| `name` | TEXT NOT NULL | nazwa wyświetlana |
| `url` | TEXT NOT NULL | URL subskrypcji |
| `enabled` | INTEGER NOT NULL DEFAULT 0 | 1 = aktywna |
| `mode` | TEXT NOT NULL DEFAULT `'global'` | `'global'` lub `'rule'` |
| `rule_providers` | TEXT NULL | tablica JSON ID providerów (tylko mode='rule') |
| `local_core_endpoint` | TEXT NULL | loopback SOCKS5/HTTP dla SS/VMess/itd. (np. `socks5://127.0.0.1:2080`) |
| `update_interval_minutes` | INTEGER NOT NULL DEFAULT 60 | kadencja odświeżania w tle |
| `last_fetched_at` | TEXT NULL | znacznik czasu ISO ostatniego udanego pobrania |
| `status` | TEXT NOT NULL DEFAULT `'empty'` | `'ok'` / `'error'` / `'empty'` |
| `error` | TEXT NULL | ostatni tekst błędu / ostrzeżenia (zredagowany) |
| `last_nodes` | TEXT NULL | tablica JSON, zredagowane podsumowania węzłów |
| `created_at` | TEXT NOT NULL | ISO |
| `updated_at` | TEXT NOT NULL | ISO |
Indeks: `idx_proxy_subscriptions_enabled (enabled)` na tick schedulera.
### 5.2 Rozszerzone `proxy_registry`
Dodana jedna kolumna:
| Column | Type | Notes |
| ----------------- | --------- | ------------------------------------------------------------------------------------ |
| `subscription_id` | TEXT NULL | FK z konwencji (bez wymuszanego FK; wiersz subskrypcji żyje w `proxy_subscriptions`) |
Istniejące wiersze po upgrade: `subscription_id = NULL`, zachowanie bez zmian.
Migracja: `ALTER TABLE proxy_registry ADD COLUMN subscription_id TEXT;`
(stosowana jako `131_proxy_subscriptions.sql`, idempotentna dzięki semantyce
`ALTER` w migration runnerze).
### 5.3 Izolacja testów rozszerzonego `proxy_subscriptions`
Migration runner stosuje nowe migracje automatycznie; jedyne miejsca, które
muszą znać nową kolumnę, to `types.ts` i `mappers.ts` (po jednym dodatkowym
polu) oraz `proxies.ts` (3 instrukcje SQL: INSERT/UPDATE/SELECT).
## 6. Tryby
### 6.1 Tryb global
- Pula powiązana z `scope='global', scope_id=NULL`.
- Ustawienie `proxyEnabled` wymuszane na `true`, gdy aktywna jest jakakolwiek
subskrypcja (lub jakiekolwiek globalne proxy spoza subskrypcji).
- Cały ruch providerów wychodzi przez pulę subskrypcji, z rotacją/health
stosowanymi przez istniejące `resolveProxyForConnectionFromRegistry`.
### 6.2 Tryb rule
- Pula powiązana z `scope='provider', scope_id=<selected provider id>` dla każdego
wybranego providera.
- Providerzy spoza listy przechodzą na direct (własne proxy na poziomie
providera albo brak proxy).
- Przełączenie subskrypcji z global → rule najpierw wywołuje `unapplySubscription`,
by odłączyć poprzednie powiązania globalne, a potem ponownie synchronizuje.
## 7. Wsparcie protokołów
Istniejący `proxyDispatcher` mówi tylko **http / https / socks5 / vercel /
deno / cloudflare**. v1 idzie za tym:
| Parser-detected type | Goes into pool directly? | Needs `localCoreEndpoint`? |
| --------------------------------- | ------------------------ | -------------------------------------- |
| `http` / `https` | yes | no |
| `socks5` | yes | no |
| `ss` / `ssr` | no | yes (sing-box/clash → loopback SOCKS5) |
| `vmess` / `vless` | no | yes |
| `trojan` | no | yes |
| `hysteria` / `tuic` / `wireguard` | no | yes |
| `relay` (vercel/deno/cloudflare) | yes | no |
Bez `localCoreEndpoint` węzły klasy SS pojawiają się w statusie jako
ostrzeżenie, ale **nie są routowane**. To odpowiada polityce „fail-closed, ale
nie kłam o możliwościach”: nigdy cicho nie gubimy ruchu; raportujemy
nieroutowalne węzły i zostawiamy decyzję operatorowi.
## 8. Parser (`src/lib/proxySubscription/parse.ts`)
Ręcznie napisany, bez zewnętrznej zależności. Akceptowane wejścia:
1. **Clash / Clash.Meta YAML** — tablica `proxies:`, z dispatch po `type`.
2. **Lista URI owinięta Base64**`parseSubscription` wykrywa base64 po długości
i zestawie znaków, dekoduje, potem parsuje URI.
3. **JSON-array-of-URI w stylu V2RayN** — używa URI `vmess://` / `vless://`.
4. **Zwykła lista URI**`ss://`, `vmess://`, `vless://`, `trojan://`,
`hysteria://`, `tuic://`, `wireguard://`, `socks5://`, `http(s)://`.
Wyjście:
```ts
type ParsedSubscription = {
nodes: DirectlyUsableNode[]; // http/https/socks5/relay
needsCore: NeedsCoreNode[]; // ss/vmess/... — redacted summary
rawProtocols: string[]; // for diagnostics
parserWarnings: string[]; // per-line parse errors, redacted
};
type DirectlyUsableNode = {
name: string;
type: "http" | "https" | "socks5" | "vercel" | "deno" | "cloudflare";
host: string;
port: number;
username?: string;
password?: string;
};
```
`redactedNodeSummary` zwraca serializowalną do JSON tablicę `{name, type,
host, port, hasCredentials}` z pominiętymi credentials. To trafia do
`last_nodes` na potrzeby UI operatora.
## 9. Bezpieczeństwo
- **SSRF na `localCoreEndpoint`**: jedyna powierzchnia SSRF to lokalny
endpoint core (sam URL subskrypcji dostarcza operator). Dozwolone
hosty: `127.0.0.1`, `::1`, `localhost`. Każdy inny host jest odrzucany przy
parsowaniu ze statusem `subscription_needs_core_endpoint_invalid`.
- **Brak outboundu do hostów wewnętrznych operatora** z URL subskrypcji. Pobranie
URL idzie przez `fetch` Node (ten sam model zaufania co istniejące
health checki `proxyLatency` i taski ping providerów). Operator
już ufa URL, bo go wkleił.
- **Fail-closed**: jeśli proxy subskrypcji jest martwe, ale nadal powiązane ze
scope, `hasBlockingProxyAssignment` zwraca true i ruch kończy się fail-closed —
zgodnie z istniejącą polityką dla dowolnego proxy z puli. Operator zawsze może
wyłączyć subskrypcję lub usunąć powiązanie.
- **Brak echa sekretów**: `last_nodes` jest zredagowane; UI nigdy nie odsyła
sekretów. `password` / `username` są przechowywane zaszyfrowane at rest przez
istniejący tor szyfrowania `proxy_registry`.
- **Brak zapisu cross-tenant**: trasy API są strzeżone przez `requireManagementAuth`
(sesja dashboardu LUB klucz API ze scope manage). Nadpisania per-API-key są
jawnie poza zakresem.
## 10. UI
Nowa podzakładka **"订阅代理"** w `dashboard / settings / 代理`, umieszczona po
„documentation”. Widok listy pokazuje:
- Name + URL (obcięty, pełny URL w atrybucie `title`)
- Odznaka statusu: `ok` / `error` / `empty`
- Przełącznik Enabled (optimistic toggle)
- Przyciski akcji: edit / refresh / delete
Formularz edycji ma:
- Name (tekst, wymagane)
- URL (tekst, wymagane, walidowane jako URL)
- Przełącznik Mode (global / rule)
- Multi-select providerów (widoczny tylko w trybie rule; zasilany z
`/api/providers`)
- Local core endpoint (tekst, opcjonalny; placeholder `socks5://127.0.0.1:2080`)
- Update interval (liczba, domyślnie 60 minut)
- Przełącznik Enabled
Gdy `status === 'error'`, baner ostrzeżenia inline pokazuje `subscription.error`.
Gdy `status === 'ok'` i są węzły wymagające local core, miękki
baner ostrzeżenia pokazuje, które protokoły pominięto.
## 11. Migracja i rollout
1. Nowa migracja `131_proxy_subscriptions.sql` uruchamia się przy pierwszym otwarciu DB po
upgrade (auto-wykrywana przez istniejący migration runner).
2. Migracja jest **idempotentna**: `ALTER TABLE … ADD COLUMN …` na już
zmigrowanej DB to no-op w SQLite, gdy owinięte w ścieżkę runnera
„ignore duplicate column”. Zob. istniejące precedensy
`040_oneproxy_proxy_fields.sql` i `093_proxy_enable_toggles.sql`.
3. Bez backfill: istniejące wiersze dostają `subscription_id = NULL`, co serwis
traktuje jako „manual, not subscription-managed”.
4. UI ukrywa zakładkę przy zerze subskrypcji, ale API jest zawsze
dostępne — to celowe, by operatorzy headless mogli zarządzać
subskrypcjami wyłącznie przez API.
## 12. Auto-odświeżanie
`startSubscriptionScheduler()` jest idempotentny i:
- Pomija przeglądarkę (`typeof window !== "undefined"`).
- Pomija przy `NODE_ENV=test`.
- W przeciwnym razie startuje 60s `setInterval`, który:
- Listuje włączone subskrypcje.
- Dla każdej liczy `due = now - lastFetchedAt >= updateIntervalMinutes * 60_000`.
- Wywołuje `syncSubscription` dla zaległych, połykając błędy (logowane).
- Timer interwału ma `.unref()`, więc nigdy nie blokuje wyjścia procesu.
Scheduler startuje przy:
- Pierwszym `GET /api/v1/management/proxy-subscriptions` (otwarcie dashboardu).
- Dowolnym wywołaniu `syncSubscription` (defensywnie — dla ścieżek CLI / automacji,
które omijają GET).
## 13. Strategia testów
`tests/unit/proxySubscription.parse.test.ts` — 7 czystych przypadków parsera, bez DB,
uruchamialne w <1s:
1. Clash YAML z węzłami `direct` (http) i `needsCore` (ss).
2. Lista URI owinięta Base64 (poprawnie zdekodowana).
3. V2Ray JSON-array-of-URI (vmess / vless).
4. Zwykła lista URI (mieszane protokoły).
5. Outboundy Clash.Meta (socks5).
6. Puste / nieznane wejście → `nodes=[]`, `needsCore=[]`, parserWarnings wypełnione.
7. `redactedNodeSummary` usuwa credentials.
`tests/unit/proxySubscription.service.test.ts` — 4 testy integracyjne używające
`process.env.DATA_DIR` + `core.resetDbInstance()`:
1. **Global**: utwórz włączoną subskrypcję global → `syncSubscription`
zweryfikuj wiersze puli w `proxy_registry` z ustawionym `subscription_id`
`resolveProxyForConnectionFromRegistry` zwraca jeden z tych wierszy →
`proxyEnabled` jest true.
2. **Rule**: utwórz włączoną subskrypcję rule na providerze P1 → zweryfikuj, że tylko
scope P1 jest powiązany, scope P2 nietknięty.
3. **Fail-closed**: URL pobrania subskrypcji jest nieosiągalny → `status='error'`,
pula pusta, a jeśli kiedykolwiek miała wiersze, są wyczyszczone;
`hasBlockingProxyAssignment` zwraca false (brak martwych proxy w żadnym scope).
4. **Delete**: usuń subskrypcję → wiersze rejestru dla tej subskrypcji są
usuwane z `force: true` (ręczne usunięcia nie mogą zablokować kaskady) →
`proxyEnabled` przeliczone.
Komenda uruchomienia testów:
```bash
node --import tsx/esm \
--import ./open-sse/utils/setupPolyfill.ts \
--import ./tests/_setup/isolateDataDir.ts \
--test \
tests/unit/proxySubscription.parse.test.ts \
tests/unit/proxySubscription.service.test.ts
```
## 14. Prace przyszłe (NIE w v1)
- Nadpisania subskrypcji per-API-key (multi-tenant; wymaga tabeli `key_subscription_overrides`).
- Reguły ruchu per-provider z matcherami domen (weszłyby w istniejącą tabelę `interceptionRules`).
- Rotacja ważona latencją między pulami subskrypcji (mamy już `ProxyRotationStrategy = "latency"`; wystarczy wystawić w UI).
- Proxyowanie samego pobrania subskrypcji przez osobny egress (by operatorzy mogli pobierać zza firmowego firewalla).
- Podgląd sparsowanej subskrypcji po stronie przeglądarki przed zapisem (dziś trzeba save → wait → see nodes).
## 15. Pliki dodane / zmienione
**Dodane (nowe):**
- `src/lib/proxySubscription/parse.ts`
- `src/lib/proxySubscription/subscriptionService.ts`
- `src/lib/proxySubscription/index.ts`
- `src/lib/db/migrations/131_proxy_subscriptions.sql`
- `src/app/api/v1/management/proxy-subscriptions/route.ts`
- `src/app/api/v1/management/proxy-subscriptions/[id]/route.ts`
- `src/app/api/v1/management/proxy-subscriptions/[id]/refresh/route.ts`
- `src/app/api/v1/management/proxy-subscriptions/[id]/nodes/route.ts`
- `src/app/(dashboard)/dashboard/settings/components/proxy/SubscriptionTab.tsx`
- `tests/unit/proxySubscription.parse.test.ts`
- `tests/unit/proxySubscription.service.test.ts`
- `docs/proxy-subscriptions.md` (ten plik)
**Zmodyfikowane (minimalnie):**
- `src/lib/db/proxies/types.ts``+ subscriptionId: string | null` na
`ProxyRegistryRecord`; `+ subscriptionId?: string | null` na `ProxyPayload`.
- `src/lib/db/proxies/mappers.ts``mapProxyRow` czyta
`subscription_id` z wiersza.
- `src/lib/db/proxies.ts` — INSERT / UPDATE / SELECT dodają `subscription_id`.
- `src/app/(dashboard)/dashboard/settings/components/ProxyTab.tsx` — dodaje
jedną nową podzakładkę ("订阅代理") + fallback `literal` dla etykiet, których
jeszcze nie ma w katalogu i18n.

View File

@@ -1,86 +0,0 @@
---
title: "Proxy Port Clash Investigation"
version: 3.8.50
lastUpdated: 2026-08-06
---
# Proxy Port Clash Investigation
## Summary
There is **no port clash** in the proxy auto-select / proxyFallback / proxyEgress system.
The proxy subsystem uses **pre-assigned registry ports** — it never binds to TCP ports
directly. The real EADDRINUSE history is in the **process supervisor** layer, where
the server's main listen port can clash during crash-loop restarts.
---
## Proxy Subsystem: No Port Binding
| Module | What It Does |
|---|---|
| `proxyAutoSelector.ts` | Selects a proxy config from the DB by applying health scores and rotation groups |
| `proxyFallback.ts` | Implements retry/fallback strategies when a selected proxy fails (try another proxy, then direct) |
| `proxyEgress.ts` | Probes/propagates egress IP info for logging — uses HTTP echo, not port binding |
| `proxyDispatcher.ts` | Creates `undici.ProxyAgent` dispatchers — these are HTTP-level (forward proxy), not TCP listen sockets |
| `proxyFetch.ts` | Patched global fetch that applies proxy dispatchers at the undici level |
None of these modules call `net.createServer()`, `http.createServer()`, or `app.listen()`.
Port management is entirely within the request life cycle — undici manages the TCP
connection pool internally.
**Fallback flow** (from `proxyFetch.ts` `runWithProxyContext`):
1. Try assigned proxy → proxy dispatcher
2. If unreachable → direct fallback (no dispatcher)
3. If still failing → error propagated up
No port allocation or release happens in this flow.
---
## Real EADDRINUSE Root Cause: Crash-Loop Restart Race
The actual port clash was in the **process supervisor** (`bin/cli/runtime/`):
| File | Role |
|---|---|
| `processSupervisor.mjs` | `ServerSupervisor` — spawns a child process, monitors exit code, restarts |
| `supervisorPolicy.mjs` | `waitUntilPortFree()`, `isPortFree()`, restart policy constants |
**Root cause:** When the server child process crashed and was immediately restarted, the
OS had not yet released the listen socket (TIME_WAIT / TCP lingering). The restart
attempt would bind to the same port and immediately fail with `EADDRINUSE`, causing
another crash → another restart → exhausted restart budget → gateway dead.
**Fix (#4425, in `supervisorPolicy.mjs`):**
1. Added `isPortFree(port)` — attempts a `net.createServer().listen()` on the target
port; resolves `false` if EADDRINUSE.
2. Added `waitUntilPortFree(port, timeoutMs=10000, intervalMs=250)` — polls every 250ms
for up to 10s until the port is free, then allows the restart.
3. Bumped `RESTART_RESET_MS` from 30s → 60s — the crash window was too short, causing
rapid cascading restarts inside the window.
4. Bumped `DEFAULT_MAX_RESTARTS` from 2 → 3 — more headroom for transient failures.
The `writePidFile()` / `killAllSubprocesses()` / `cleanupPidFile()` utilities in
`bin/cli/utils/pid.mjs` ensure clean PID file lifecycle.
## Related: Live-Dashboard EADDRINUSE (#6324)
A parallel fix (`live-ws-eaddrinuse-6324.test.ts`) ensures `startLiveDashboardServer()`
rejects with a proper `EADDRINUSE` error (instead of an unhandled socket 'error' event
that would crash the process). The dashboard server uses a separate port from the main
API server, so when both are configured on the same port, the second bind fails
gracefully.
---
## Current State
| Risk | Status | Remaining |
|---|---|---|
| Supervisor restart EADDRINUSE | **Fixed** (#4425) | None |
| LiveWS port clash | **Fixed** (#6324) | None |
| Proxy selection port clash | **Never applicable** | None |
| Two Redis CLIENT factories bind no TCP ports | **Never applicable** | None |
No further action needed on port clash.

View File

@@ -1,377 +0,0 @@
---
title: "Operator Proxy Subscriptions (Karing-style)"
version: 3.8.50
lastUpdated: 2026-08-06
---
# Operator Proxy Subscriptions (Karing-style)
> Feature design + implementation notes for OmniRoute's operator-level proxy
> subscription flow. This is the v1 cut: a single operator pastes subscription
> links, picks a mode (global or rule), and OmniRoute binds the resulting proxy
> pool into the existing scope resolution. Multi-tenant per-API-key, advanced
> traffic rules, latency-driven per-rule weights, and so on are explicitly
> out-of-scope and listed in §7.
---
## 1. Motivation
Today, OmniRoute's proxy pool is hand-curated: every node lives in
`proxy_registry` with hand-written host/port/credentials, and every binding to
the upstream dispatchers (account → provider → combo → global → direct) is a
manual `proxy_assignments` row. Operators who already maintain a Clash/V2Ray/
sing-box subscription (e.g. from an airport service) have to retype every node
into OmniRoute and re-bind them whenever the upstream list changes.
The goal of v1 is to make OmniRoute first-class for **operator-supplied**
subscriptions, similar to how Karing / Clash / sing-box let users paste a
`https://...` URL and have the client manage the lifecycle.
## 2. User stories
| # | As a(n) | I want to | So that |
|---|---------|-----------|---------|
| U1 | Operator | paste a subscription URL once | I don't retype nodes every time the airport refreshes |
| U2 | Operator | toggle the subscription on/off | I can fall back to direct without deleting the URL |
| U3 | Operator | pick **global** mode | every provider's traffic exits via the subscription |
| U4 | Operator | pick **rule** mode and select specific providers | only selected providers route through the proxy; others stay direct |
| U5 | Operator | supply a local sing-box/clash SOCKS5 endpoint | SS/VMess/Trojan/VLESS nodes (which OmniRoute's dispatcher can't speak natively) become usable through a local kernel bridge |
| U6 | Operator | see fetch status and a recent redacted node summary | I can debug "why is this empty / erroring" without leaking credentials |
## 3. Non-goals (v1)
- Per-API-key subscription overrides (multi-tenant). v1 is operator-only.
- Per-provider traffic rules beyond `global` / `rule-on-selected-providers`.
- Latency-based smart routing between subscription nodes and other pools
(existing `resolveProxyForConnectionFromRegistry` already does this for the
global pool; v1 just feeds subscription nodes into it).
- Auto-importing URL/password from headers or query params.
- SSRF mitigation beyond loopback-only local-core endpoints (the subscription
URL itself is operator-controlled, so we trust it the same way we trust
upstream provider URLs today).
## 4. Architecture
```
┌─────────────────────────────────────────┐
│ dashboard / settings / 代理 / 订阅代理 │
│ (client component, SubscriptionTab) │
└──────────────────┬──────────────────────┘
│ fetch
┌────────────────────────────────────────────────────────┐
│ /api/v1/management/proxy-subscriptions │
│ ├ GET list │
│ ├ POST create │
│ ├ GET /:id │
│ ├ PATCH /:id │
│ ├ DELETE /:id │
│ ├ POST /:id/refresh │
│ └ GET /:id/nodes │
└────────────────────────┬───────────────────────────────┘
│ uses
┌────────────────────────────────────────────────────────┐
│ src/lib/proxySubscription/ │
│ ├ parse.ts (Clash YAML / V2Ray JSON / URIs) │
│ ├ subscriptionService.ts │
│ │ CRUD, sync, apply, unapply, scheduler │
│ └ index.ts (barrel) │
└──────────┬─────────────────────────────┬───────────────┘
│ upsert/scope-bind │ DB
▼ ▼
┌─────────────────────────┐ ┌──────────────────────────┐
│ proxy_registry │ │ proxy_subscriptions │
│ (existing) + │ │ (NEW — subscription │
│ subscription_id column │ │ metadata + scheduler │
│ + status/health checks │ │ state) │
└─────────────────────────┘ └──────────────────────────┘
▼ (existing)
resolveProxyForConnectionFromRegistry
hasBlockingProxyAssignment (fail-closed)
proxyDispatcher (open-sse/utils/proxyDispatcher)
```
Key design decision: **we do not invent a new scope or routing pipeline**. We
upsert subscription-derived nodes into `proxy_registry` with `source =
'subscription'` + `subscription_id`, and then `applySubscription()` walks the
existing `addProxyToScopePool(scope, scopeId, proxyId)` API. This means:
- Existing rotation, health checks, and fail-closed guards apply for free.
- Existing dashboards (ProxyPoolTab, SourceToggleBar, GlobalConfigTab) work
unchanged — subscription nodes just appear in the pool with a `source`
badge.
- Deleting/disabling a subscription cleanly removes its bindings without
touching manual proxies.
## 5. Data model
### 5.1 New table `proxy_subscriptions`
| Column | Type | Notes |
|---|---|---|
| `id` | TEXT PK | UUID |
| `name` | TEXT NOT NULL | display name |
| `url` | TEXT NOT NULL | subscription URL |
| `enabled` | INTEGER NOT NULL DEFAULT 0 | 1 = active |
| `mode` | TEXT NOT NULL DEFAULT `'global'` | `'global'` or `'rule'` |
| `rule_providers` | TEXT NULL | JSON array of provider IDs (mode='rule' only) |
| `local_core_endpoint` | TEXT NULL | loopback SOCKS5/HTTP for SS/VMess/etc. (e.g. `socks5://127.0.0.1:2080`) |
| `update_interval_minutes` | INTEGER NOT NULL DEFAULT 60 | background refresh cadence |
| `last_fetched_at` | TEXT NULL | ISO timestamp of last successful fetch |
| `status` | TEXT NOT NULL DEFAULT `'empty'` | `'ok'` / `'error'` / `'empty'` |
| `error` | TEXT NULL | last error / warning text (redacted) |
| `last_nodes` | TEXT NULL | JSON array, redacted node summaries |
| `created_at` | TEXT NOT NULL | ISO |
| `updated_at` | TEXT NOT NULL | ISO |
Index: `idx_proxy_subscriptions_enabled (enabled)` for the scheduler tick.
### 5.2 Extended `proxy_registry`
Added one column:
| Column | Type | Notes |
|---|---|---|
| `subscription_id` | TEXT NULL | FK by convention (no enforced FK; subscription row lives in `proxy_subscriptions`) |
Existing rows on upgrade: `subscription_id = NULL`, behavior unchanged.
Migration: `ALTER TABLE proxy_registry ADD COLUMN subscription_id TEXT;`
(applied as `131_proxy_subscriptions.sql`, idempotent via the migration
runner's `ALTER` semantics).
### 5.3 Extended `proxy_subscriptions` test isolation
The migration runner applies new migrations automatically; the only places
that need to know about the new column are `types.ts` and `mappers.ts` (one
extra field each) and `proxies.ts` (3 SQL statements: INSERT/UPDATE/SELECT).
## 6. Modes
### 6.1 Global mode
- Pool bound to `scope='global', scope_id=NULL`.
- `proxyEnabled` setting forced to `true` whenever any subscription (or any
non-subscription global proxy) is active.
- All provider traffic exits via the subscription pool, with rotation/health
applied by the existing `resolveProxyForConnectionFromRegistry`.
### 6.2 Rule mode
- Pool bound to `scope='provider', scope_id=<selected provider id>` for each
selected provider.
- Providers NOT in the list fall through to direct (their own provider-level
proxy or no proxy).
- Toggling a subscription from global → rule first calls `unapplySubscription`
to detach the previous global bindings, then re-syncs.
## 7. Protocol support
The existing `proxyDispatcher` only speaks **http / https / socks5 / vercel /
deno / cloudflare**. v1 follows that:
| Parser-detected type | Goes into pool directly? | Needs `localCoreEndpoint`? |
|---|---|---|
| `http` / `https` | yes | no |
| `socks5` | yes | no |
| `ss` / `ssr` | no | yes (sing-box/clash → loopback SOCKS5) |
| `vmess` / `vless` | no | yes |
| `trojan` | no | yes |
| `hysteria` / `tuic` / `wireguard` | no | yes |
| `relay` (vercel/deno/cloudflare) | yes | no |
Without `localCoreEndpoint`, SS-class nodes are surfaced in the status as a
warning but **not routed**. This matches the "fail-closed, but don't lie about
capability" policy: we never silently drop traffic; we report unrouteable
nodes and let the operator decide.
## 8. Parser (`src/lib/proxySubscription/parse.ts`)
Hand-rolled, no external dependency. Inputs accepted:
1. **Clash / Clash.Meta YAML**`proxies:` array, with `type` dispatch.
2. **Base64-wrapped URI list**`parseSubscription` detects base64 by length
and charset, decodes, then URI-parses.
3. **V2RayN-style JSON-array-of-URI** — uses `vmess://` / `vless://` URIs.
4. **Plain URI list**`ss://`, `vmess://`, `vless://`, `trojan://`,
`hysteria://`, `tuic://`, `wireguard://`, `socks5://`, `http(s)://`.
Output:
```ts
type ParsedSubscription = {
nodes: DirectlyUsableNode[]; // http/https/socks5/relay
needsCore: NeedsCoreNode[]; // ss/vmess/... — redacted summary
rawProtocols: string[]; // for diagnostics
parserWarnings: string[]; // per-line parse errors, redacted
};
type DirectlyUsableNode = {
name: string;
type: "http" | "https" | "socks5" | "vercel" | "deno" | "cloudflare";
host: string;
port: number;
username?: string;
password?: string;
};
```
`redactedNodeSummary` returns a JSON-serializable array of `{name, type,
host, port, hasCredentials}` with credentials omitted. This is what gets
persisted in `last_nodes` for the operator UI.
## 9. Security
- **SSRF on `localCoreEndpoint`**: the only SSRF surface here is the local
core endpoint (the subscription URL itself is operator-supplied). Allowed
hosts: `127.0.0.1`, `::1`, `localhost`. Any other host is rejected at parse
time with a `subscription_needs_core_endpoint_invalid` status.
- **No outbound to operator-internal hosts** from a subscription URL. The URL
fetch goes through Node's `fetch` (same trust model as the existing
`proxyLatency` health checks and the provider ping tasks). The operator
already trusts the URL by pasting it.
- **Fail-closed**: if a subscription's proxy is dead but still bound to a
scope, `hasBlockingProxyAssignment` returns true and traffic fails closed —
matches existing policy for any pool proxy. The operator can always disable
the subscription or remove the binding.
- **No secret echo**: `last_nodes` is redacted; the UI never sends secrets
back. `password` / `username` are stored encrypted at rest by the existing
`proxy_registry` encryption path.
- **No cross-tenant write**: the API routes are gated by `requireManagementAuth`
(dashboard session OR a manage-scope API key). Per-API-key overrides are
explicitly out-of-scope.
## 10. UI
A new sub-tab **"订阅代理"** in `dashboard / settings / 代理`, placed after
"documentation". List view shows:
- Name + URL (truncated, with full URL in `title` attribute)
- Status badge: `ok` / `error` / `empty`
- Enabled switch (optimistic toggle)
- Action buttons: edit / refresh / delete
The edit form has:
- Name (text, required)
- URL (text, required, validated as URL)
- Mode toggle (global / rule)
- Provider multi-select (visible only in rule mode; populated from
`/api/providers`)
- Local core endpoint (text, optional; placeholder `socks5://127.0.0.1:2080`)
- Update interval (number, default 60 minutes)
- Enabled toggle
When `status === 'error'`, an inline warning banner shows `subscription.error`.
When `status === 'ok'` and there are nodes that needed a local core, a soft
warning banner shows which protocols were skipped.
## 11. Migration & rollout
1. New migration `131_proxy_subscriptions.sql` runs on first DB open after
upgrade (auto-discovered by the existing migration runner).
2. The migration is **idempotent**: `ALTER TABLE … ADD COLUMN …` against an
already-migrated DB is a no-op in SQLite when wrapped in the runner's
"ignore duplicate column" path. See the existing
`040_oneproxy_proxy_fields.sql` and `093_proxy_enable_toggles.sql`
precedents.
3. No backfill: existing rows get `subscription_id = NULL`, which the
service treats as "manual, not subscription-managed".
4. UI hides the tab when there are zero subscriptions, but the API is always
available — that's intentional, so headless operators can manage
subscriptions via API only.
## 12. Auto-refresh
`startSubscriptionScheduler()` is idempotent and:
- Skips in the browser (`typeof window !== "undefined"`).
- Skips under `NODE_ENV=test`.
- Otherwise starts a 60s `setInterval` that:
- Lists enabled subscriptions.
- For each, computes `due = now - lastFetchedAt >= updateIntervalMinutes * 60_000`.
- Calls `syncSubscription` for due ones, swallowing errors (logged).
- The interval timer is `.unref()`'d so it never blocks process exit.
The scheduler is started on:
- First `GET /api/v1/management/proxy-subscriptions` (dashboard open).
- Any `syncSubscription` call (defensive — for CLI / automation paths that
bypass the GET).
## 13. Testing strategy
`tests/unit/proxySubscription.parse.test.ts` — 7 pure-parser cases, no DB,
runnable in <1s:
1. Clash YAML with `direct` (http) and `needsCore` (ss) nodes.
2. Base64-wrapped URI list (decoded correctly).
3. V2Ray JSON-array-of-URI (vmess / vless).
4. Plain URI list (mixed protocols).
5. Clash.Meta outbounds (socks5).
6. Empty / unknown input → `nodes=[]`, `needsCore=[]`, parserWarnings filled.
7. `redactedNodeSummary` strips credentials.
`tests/unit/proxySubscription.service.test.ts` — 4 integration tests using
`process.env.DATA_DIR` + `core.resetDbInstance()`:
1. **Global**: create enabled global subscription → `syncSubscription`
verify pool rows in `proxy_registry` with `subscription_id` set →
`resolveProxyForConnectionFromRegistry` returns one of those rows →
`proxyEnabled` is true.
2. **Rule**: create enabled rule subscription on provider P1 → verify only
P1's scope is bound, P2's scope is untouched.
3. **Fail-closed**: subscription fetch URL is unreachable → `status='error'`,
pool is empty, but if pool ever had rows they are cleaned up;
`hasBlockingProxyAssignment` returns false (no dead proxies in any scope).
4. **Delete**: delete subscription → registry rows for that subscription are
removed with `force: true` (manual deletions can't cascade-block it) →
`proxyEnabled` recomputed.
Test runner command:
```bash
node --import tsx/esm \
--import ./open-sse/utils/setupPolyfill.ts \
--import ./tests/_setup/isolateDataDir.ts \
--test \
tests/unit/proxySubscription.parse.test.ts \
tests/unit/proxySubscription.service.test.ts
```
## 14. Future work (NOT in v1)
- Per-API-key subscription overrides (multi-tenant; needs a `key_subscription_overrides` table).
- Per-provider traffic rules with domain matchers (would slot into the existing `interceptionRules` table).
- Latency-weighted rotation across subscription pools (we already have `ProxyRotationStrategy = "latency"`; just expose it in the UI).
- Proxying the subscription fetch itself through a separate egress (so operators can fetch behind a corporate firewall).
- Browser-side preview of a parsed subscription before saving (currently must save → wait → see nodes).
## 15. Files touched / added
**Added (new):**
- `src/lib/proxySubscription/parse.ts`
- `src/lib/proxySubscription/subscriptionService.ts`
- `src/lib/proxySubscription/index.ts`
- `src/lib/db/migrations/131_proxy_subscriptions.sql`
- `src/app/api/v1/management/proxy-subscriptions/route.ts`
- `src/app/api/v1/management/proxy-subscriptions/[id]/route.ts`
- `src/app/api/v1/management/proxy-subscriptions/[id]/refresh/route.ts`
- `src/app/api/v1/management/proxy-subscriptions/[id]/nodes/route.ts`
- `src/app/(dashboard)/dashboard/settings/components/proxy/SubscriptionTab.tsx`
- `tests/unit/proxySubscription.parse.test.ts`
- `tests/unit/proxySubscription.service.test.ts`
- `docs/proxy-subscriptions.md` (this file)
**Modified (minimal):**
- `src/lib/db/proxies/types.ts``+ subscriptionId: string | null` on
`ProxyRegistryRecord`; `+ subscriptionId?: string | null` on `ProxyPayload`.
- `src/lib/db/proxies/mappers.ts``mapProxyRow` reads
`subscription_id` from the row.
- `src/lib/db/proxies.ts` — INSERT / UPDATE / SELECT add `subscription_id`.
- `src/app/(dashboard)/dashboard/settings/components/ProxyTab.tsx` — adds
one new sub-tab ("订阅代理") + the `literal` fallback for labels that
aren't in the i18n catalog yet.

View File

@@ -1,252 +0,0 @@
# Devin Claude Bridge Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Build a fail-closed `devin-cli-agentic` provider that serves local Anthropic Messages requests through Devin CLI ACP stdio while preserving Claude Code tool-use semantics.
**Architecture:** Add a separate Claude-format provider and executor instead of changing the existing OpenAI-format `devin-cli` summarizer. Keep parsing, prompt serialization, Anthropic response rendering, and ACP process handling in focused files under `open-sse/executors/devin-agentic/`, then wire them into the existing provider and executor registries.
**Tech Stack:** TypeScript ES modules, Node child process stdio, Anthropic Messages JSON/SSE, JSON-RPC 2.0 ACP, Node test runner.
---
### Task 1: Agentic Bridge Core
**Files:**
- Create: `open-sse/executors/devin-agentic/types.ts`
- Create: `open-sse/executors/devin-agentic/serializer.ts`
- Create: `open-sse/executors/devin-agentic/toolParser.ts`
- Create: `open-sse/executors/devin-agentic/anthropicResponse.ts`
- Test: `tests/unit/executor-devin-cli-agentic-core.test.ts`
- [ ] **Implement and prove serialization, parsing, validation, and Anthropic rendering**
Interfaces:
```ts
export function serializeAnthropicForDevin(body: unknown): DevinPrompt;
export function parseDevinToolRequest(text: string, tools: AnthropicTool[]): ParsedToolRequest | null;
export function buildClaudeTextResponse(args: ClaudeResponseArgs): Record<string, unknown>;
export function buildClaudeToolUseResponse(args: ClaudeToolUseArgs): Record<string, unknown>;
export function buildClaudeSseFrames(message: Record<string, unknown>): string;
```
Invariants:
- Preserve `text`, `tool_use`, `tool_result`, `thinking`, and `redacted_thinking`.
- Reject `image` with a clear error.
- Reject unknown content block types.
- Allow only one tool request per model turn.
- Validate tool arguments against object JSON Schema with `required`, `type`, `properties`, `additionalProperties`, `enum`, `items`, and scalar types.
- Generate deterministic ids from tool name and canonicalized arguments.
Run: `node --import tsx/esm --test tests/unit/executor-devin-cli-agentic-core.test.ts`
Expected: core tests pass after dependencies are installed.
### Task 2: ACP Executor And Provider Wiring
**Files:**
- Create: `open-sse/executors/devin-cli-agentic.ts`
- Modify: `open-sse/executors/index.ts`
- Create: `open-sse/config/providers/registry/devin-cli-agentic/index.ts`
- Modify: `open-sse/config/providers/index.ts`
- Test: `tests/unit/executor-devin-cli-agentic-acp.test.ts`
- [ ] **Implement and prove fail-closed ACP execution**
Behavior:
- `buildUrl()` returns `devin://acp/stdio`.
- `buildHeaders()` returns `{}`.
- `execute()` spawns only `devin acp` by default or the explicit `CLI_DEVIN_AGENTIC_BIN`/`CLI_DEVIN_BIN` override.
- The child environment removes Anthropic and Claude routing credentials before spawn.
- The executor sends `initialize`, `session/new`, and `session/prompt`.
- The executor collects `agent_message_chunk` text and `session/prompt` final result.
- Non-streaming Claude clients receive native Anthropic JSON.
- Streaming Claude clients receive native Anthropic SSE lifecycle frames.
- Spawn failure, ACP error, timeout, and early exit produce non-2xx responses with sanitized messages.
Run: `node --import tsx/esm --test tests/unit/executor-devin-cli-agentic-acp.test.ts`
Expected: ACP mock tests pass after dependencies are installed.
### Task 3: Isolation Scripts And Documentation
**Files:**
- Create: `scripts/devin-bridge/verify-anthropic-isolation`
- Create: `scripts/devin-bridge/test-unit`
- Create: `scripts/devin-bridge/launch`
- Create: `docs/DEVIN_CLAUDE_BRIDGE.md`
- Modify: `.gitignore`
- [ ] **Implement offline guardrails and operator docs**
Behavior:
- `verify-anthropic-isolation` fails if `CLAUDE_CONFIG_DIR` is missing, points outside an isolated path, or if Anthropic routing env vars are present.
- `test-unit` runs the focused unit tests.
- `launch` refuses to start unless `ENABLE_LIVE_DEVIN_TESTS=1` for live Devin or `DEVIN_BRIDGE_OFFLINE=1` for offline mock mode.
- Documentation distinguishes tested offline behavior from live Devin opt-in behavior.
Run: `./scripts/devin-bridge/verify-anthropic-isolation` with explicit isolated env.
Expected: exits 0 with isolated env and non-zero without it.
### Task 4: Verification
**Files:**
- No additional source files.
- [ ] **Run proportional checks and capture real output**
Commands:
```bash
./scripts/devin-bridge/test-unit
npm test
```
Expected in this workspace before installing dependencies: both commands fail with `ERR_MODULE_NOT_FOUND` for `tsx`. Expected after `npm install`: focused tests pass; `npm test` outcome must be reported from real output.
### Task 5: Close Core Security And Protocol Gaps
**Files:**
- Modify: `open-sse/executors/devin-cli-agentic.ts`
- Modify: `open-sse/executors/devin-agentic/*.ts`
- Modify: `tests/unit/executor-devin-cli-agentic-*.test.ts`
- [ ] **Prove environment allowlisting, response-id correlation, strict standalone tool envelopes, unique ids, bounded repair, size limits, cancellation cleanup, sanitized errors, and explicit `devin://acp/stdio` validation**
Run with `HOME`, `DATA_DIR`, and `SQLITE_FILE` under `.sandbox`; expected: all focused tests pass and an outside-path test fails closed.
### Task 6: Build Reproducible Containers And Network Guard
**Files:**
- Create: `docker/devin-bridge/Dockerfile`
- Create: `docker/devin-bridge/compose.yml`
- Create: `docker/devin-bridge/network-guard/*`
- Create: `docker/devin-bridge/mock-devin/*`
- Create: `.env.devin-bridge.example`
- [ ] **Pin Claude Code 2.1.220 and Devin CLI 3000.2.17, create non-root offline/live profiles, separate auth/config volumes, explicit env allowlist, no host credential mounts, and denied-domain telemetry**
Run: `docker compose -f docker/devin-bridge/compose.yml --profile offline config`; expected: no forbidden mounts/env inheritance and only internal runtime networks.
### Task 7: Deliver Isolation And Operator Scripts
**Files:**
- Create/modify: `scripts/devin-bridge/{build,test-unit,test-contract,test-e2e-mock,verify-anthropic-isolation,login-devin,test-live-devin,launch,clean}`
- [ ] **Make every command idempotent, sandbox-scoped, fail-closed, and secret-safe**
Run: `./scripts/devin-bridge/verify-anthropic-isolation`; expected: positive offline proof passes and each deliberately removed guard returns non-zero.
### Task 8: Real Claude Code Offline E2E
**Files:**
- Create: `tests/fixtures/devin-bridge/e2e-workspace/*`
- Create: `tests/e2e/devin-claude-bridge.e2e.*`
- [ ] **Run pinned Claude Code in the offline container through local `/v1/messages` and mock ACP, proving CLAUDE.md, skill, command, hook, Read/Edit/Bash, tests, multi-turn continuation, and no Anthropic traffic**
Run: `./scripts/devin-bridge/test-e2e-mock`; expected: workspace diff and tests prove Claude Code executed tools while mock Devin only requested them.
### Task 9: Regression, Documentation, Live Gate, And Delivery
**Files:**
- Modify: `docs/DEVIN_CLAUDE_BRIDGE.md`
- Create: `docs/DEVIN_CLAUDE_BRIDGE_PROGRESS.md`
- [ ] **Run focused suites, typecheck, lint, build, docs checks, offline E2E, and isolation proof with fresh output; then run live only after official in-container Devin login**
If login is unavailable, record live as not tested and expose exactly `./scripts/devin-bridge/login-devin` followed by `./scripts/devin-bridge/test-live-devin`. Commit each reversible unit; do not merge or publish until all offline critical checks are green.
### Task 10: Close The Authenticated Live Runtime
**Files:**
- Modify: `open-sse/executors/devin-cli-agentic.ts`
- Modify: `docker/devin-bridge/compose.yml`
- Create: `docker/devin-bridge/network-guard/policy.mjs`
- Modify: `docker/devin-bridge/network-guard/proxy.mjs`
- Modify: `scripts/devin-bridge/select-live-model.mjs`
- Modify: `scripts/devin-bridge/common`
- Modify: `scripts/devin-bridge/login-devin`
- Modify: `scripts/devin-bridge/test-live-devin`
- Modify: `scripts/devin-bridge/verify-anthropic-isolation`
- Modify: `tests/unit/executor-devin-cli-agentic-acp.test.ts`
- Create: `tests/unit/devin-bridge-live-runtime.test.ts`
- [ ] **Implement and prove the authenticated network, auth, and catalog boundaries with block-level TDD**
Invariants:
- The ACP child receives proxy variables only when `DEVIN_BRIDGE_PROXY_URL` is exactly
`http://network-guard:8080`; arbitrary inherited proxy and credential variables stay absent.
- The guard permits suffixes `.devin.ai` and `.cognition.ai`, exact hosts
`server.codeium.com` and `unleash.codeium.com`, and nothing else.
- Claude services cannot mount `devin-auth`; non-Claude services cannot mount the Claude config.
- A zero exit from `devin auth status` is insufficient when output contains a server-fetch failure.
- `family_uid: swe-1.7-lightning` resolves to catalog id `swe-1-7-lightning`; unknown normalized
values fail instead of becoming model ids.
- Login uses the official manual-token flow so no container loopback callback is required.
Run:
```bash
./scripts/devin-bridge/test-unit
node --import tsx/esm --test tests/unit/devin-bridge-live-runtime.test.ts
./scripts/devin-bridge/verify-anthropic-isolation --static
```
Expected: focused tests and static isolation pass; deliberate untrusted proxy, host, mount, auth
status, and model fixtures fail closed.
- [ ] **Commit the reversible live-runtime repair**
```bash
git add open-sse/executors/devin-cli-agentic.ts docker/devin-bridge \
scripts/devin-bridge tests/unit/devin-bridge-live-runtime.test.ts \
tests/unit/executor-devin-cli-agentic-acp.test.ts
git commit -m "fix: close Devin bridge live runtime gaps"
```
### Task 11: Prove Offline And Live Completion
**Files:**
- Modify: `docker/devin-bridge/run-claude-live-e2e.sh`
- Modify: `docs/DEVIN_CLAUDE_BRIDGE.md`
- Modify: `docs/DEVIN_CLAUDE_BRIDGE_PROGRESS.md`
- [ ] **Run the complete deterministic bridge proof before any paid request**
```bash
./scripts/devin-bridge/test-unit
./scripts/devin-bridge/test-contract
./scripts/devin-bridge/test-e2e-mock
./scripts/devin-bridge/verify-anthropic-isolation
npm run typecheck:core
npm run lint
npm run build
npm run check:docs-all
```
Expected: all bridge-specific checks, typecheck, lint, build, and documentation checks pass with
isolated data paths. Any unrelated full-suite infrastructure hang is recorded separately and is
not converted into a pass.
- [ ] **Run exactly the three authorized live scenarios and the no-fallback failure probe**
```bash
ENABLE_LIVE_DEVIN_TESTS=1 ./scripts/devin-bridge/test-live-devin
```
Expected: dynamic discovery selects a returned Devin catalog model; Claude Code reads without
editing, then edits and runs the fixture test, then executes the fixture command. Evidence shows
native tool use by Claude Code, only `devin-cli-agentic` routing, no allowed non-Devin egress,
and an Anthropic-shaped error after the Devin backend is deliberately made unavailable.
- [ ] **Update verified documentation and commit the evidence-backed delivery state**
```bash
git add docker/devin-bridge/run-claude-live-e2e.sh docs/DEVIN_CLAUDE_BRIDGE.md \
docs/DEVIN_CLAUDE_BRIDGE_PROGRESS.md
git commit -m "docs: record verified Devin bridge live delivery"
```

View File

@@ -1,134 +0,0 @@
# Devin Claude Bridge Design
## Baseline
- Branch: `release/v3.8.49`
- HEAD: `ed7db3ee5f89a144b2d931d8605534522f83de30`
- Package version: `3.8.49`
- Node: `v26.0.0`
- npm: `11.12.1`
- Pre-existing worktree state: `.tug/` untracked
- Dependency state: `node_modules` is absent; the first focused test run failed before loading tests because `tsx` was not installed.
- Tugline state: `tug` exists, but `tug search` failed with MCP connection closed and `tug doctor` hung; it was interrupted.
- Upstream check: `git ls-remote` failed because GitHub DNS was unavailable. Web search of the public repository showed the existing `devin-cli` summarizer provider, but no evidence of `devin-cli-agentic`.
## Source Anchors
- `/v1/messages`: `src/app/api/v1/messages/route.ts`
- Existing Devin provider: `open-sse/config/providers/registry/devin-cli/index.ts`
- Existing Devin executor: `open-sse/executors/devin-cli.ts`
- Executor registry: `open-sse/executors/index.ts`
- Provider registry: `open-sse/config/providers/index.ts`
- Format detection: `open-sse/services/provider.ts`
- Claude non-streaming response conversion: `open-sse/handlers/responseTranslator.ts`
- Existing Devin ACP unit test: `tests/unit/executor-devin-cli-acp-protocol-8406.test.ts`
## Findings
The existing `devin-cli` provider is intentionally OpenAI-format and summarizer-oriented. Its executor spawns `devin acp --agent-type summarizer`, flattens the message history into a single text prompt, and emits OpenAI SSE text chunks. It does not preserve Anthropic `tool_use` and `tool_result` blocks.
The safest implementation is a new provider id, `devin-cli-agentic`, with a separate executor. This leaves `devin-cli`, Anthropic OAuth, Claude OAuth, Claude Web, and all host Claude configuration code untouched. The new provider is fail-closed: it only resolves to `devin://acp/stdio`, uses the official Devin CLI ACP stdio path, and has no fallback provider.
## Architecture
Claude Code sends Anthropic Messages requests to local OmniRoute. OmniRoute resolves model ids prefixed with `devin-cli-agentic/` to a new Claude-format provider. The new executor translates the complete Anthropic request into an explicit text prompt for Devin ACP, including system text, structured message history, tool schemas, and prior tool results.
Devin remains a model backend. The executor starts the official fixed no-tools summarizer
role with `devin acp --agent-type summarizer` and frames the serialized request as an
execution trace. Devin must request client-owned tool execution by emitting a strict
XML-wrapped JSON block:
```xml
<tool>
{"name":"Read","arguments":{"file_path":"src/index.ts"}}
</tool>
```
The bridge parses exactly one tool request per model turn, validates that the tool name was supplied in the incoming request, validates arguments against a minimal JSON Schema validator, generates a stable `tool_devin_...` id, and returns a native Anthropic `tool_use` block. If no valid tool request is present, the bridge returns text with `stop_reason: "end_turn"`.
## Error And Safety Rules
- Unsupported Anthropic content blocks fail explicitly; images are rejected.
- Unknown tools fail explicitly.
- Invalid tool arguments fail explicitly.
- Invalid tool XML/JSON fails explicitly.
- Narrative claims that a tool was executed are returned as text, not actions.
- ACP spawn, timeout, early exit, and stderr-only failures return explicit Devin errors.
- The executor never reads `~/.claude`, `~/.claude.json`, macOS Keychain paths, or host Claude config.
- Live Devin is outside normal tests and remains opt-in via `ENABLE_LIVE_DEVIN_TESTS=1`.
## Test Strategy
Focused unit tests cover serialization, tool parsing, validation, Anthropic JSON, Anthropic SSE, malformed tool output, unknown tools, invalid arguments, image rejection, timeout, and spawn failure. Environment scripts provide an offline isolation verifier without reading host Claude credentials.
## Mandatory Runtime Isolation
The bridge runs only through `docker/devin-bridge/compose.yml`. The runtime image is non-root, uses a private `/home/bridge`, and mounts only disposable workspaces, evidence, and bridge harness files. Application source is copied into the image. It never mounts the host home, Docker socket, SSH, cloud credentials, or global Claude configuration. The container receives an explicit environment allowlist; the executor also constructs an allowlisted child environment instead of copying `process.env`.
Build-time network access installs Claude Code `2.1.220` and Devin CLI `3000.2.17` with pinned integrity/checksum. Runtime profiles are separate: `offline` uses only an internal Compose network; `live-devin` exposes egress only through a proxy guard whose allowlist contains Devin/Cognition suffixes and whose default is denial. Devin authentication lives only in the named `devin-auth` volume. Claude configuration lives in a different named volume and is initialized empty.
## Fail-Closed Routing
`devin-cli-agentic` accepts only the synthetic `devin://acp/stdio` target and an explicit Devin binary path inside the container. It cannot use provider combos, auto routing, account fallback, fallback URLs, or an HTTP upstream. Model aliases resolve only to models returned by the Devin catalog or explicitly configured Devin model ids. An ACP failure, timeout, cancellation, invalid frame, unavailable model, or stopped sidecar becomes an Anthropic-shaped error response; no secondary provider is attempted.
## Agentic Contract
The serializer preserves request order, `system`, `tool_choice`, exact tool schemas, `text`, `tool_use`, `tool_result`, `thinking`, and `redacted_thinking`. It rejects unsupported blocks and caps large tool results with an explicit truncation marker and original size. The parser accepts exactly one standalone `<tool>` envelope, validates with Zod/JSON Schema infrastructure already present in OmniRoute, rejects unknown tools and mixed narrative/action output, and performs at most one bounded repair prompt. Tool ids combine a per-request nonce with canonical arguments so repeated identical calls remain unique while their association is stable within the turn.
## Required Proof
The offline profile must prove the ACP lifecycle, fragmented frames, stderr, early exit, hang/cancel, Anthropic JSON/SSE order, no fallback, and a real pinned Claude Code run that reads, edits, runs tests, observes `CLAUDE.md`, loads a skill and command, fires a hook, and completes at least one `tool_use -> tool_result -> continuation` loop. The isolation verifier checks env, mounts, UID, config paths, DNS/connection logs, local inference destination, selected provider, and fail-closed behavior. Live Devin is proved only by official in-container login and three isolated agentic scenarios.
## Safety Incident During Baseline
The first focused test was run without `DATA_DIR` isolation and initialized `/Users/lucasisrael/.omniroute/storage.sqlite`; logs reported schema-column additions. No Anthropic data was accessed. The external database will not be touched again or destructively rolled back. Every bridge command and test now must set `HOME`, `DATA_DIR`, `SQLITE_FILE`, and temporary directories inside `.sandbox`, and an automated guard must reject paths outside the task workspace.
## Live Completion Repair
The first authenticated live attempt disproved four assumptions in the initial container
design. The official CLI reports a valid login even when its server-status request fails;
that request uses the exact hosts `server.codeium.com` and `unleash.codeium.com`, which the
guard denied. The OmniRoute executor also built a fresh allowlisted child environment that
omitted the proxy, so `devin acp` could not leave the internal network. Model discovery emits
family identifiers such as `swe-1.7`, while the OmniRoute catalog uses canonical ids such as
`swe-1-7`. Finally, browser login redirects to a loopback listener inside the one-off
container, which is not reachable from the host browser.
The repair keeps the fully containerized architecture and does not weaken the deny-by-default
network. The guard gains an exact-host allowlist for the two Codeium control-plane hosts while
retaining suffix-based access only for Devin and Cognition; telemetry destinations such as
Sentry remain denied. Compose supplies `DEVIN_BRIDGE_PROXY_URL` with the single accepted value
`http://network-guard:8080`, and the executor derives `HTTP_PROXY` and `HTTPS_PROXY` from that
explicit bridge setting instead of inheriting arbitrary host proxy variables. Claude services
mount only the Claude config volume, and only the OmniRoute live service mounts the Devin auth
volume.
Fresh login uses the official `devin auth login --force-manual-token-flow`, which is intended
for remote environments where localhost redirects cannot work. The credential is pasted only
into the interactive CLI terminal and never appears in arguments, logs, evidence, or Git.
Authentication validation requires both the logged-in marker and the absence of a server-fetch
failure. Model discovery accepts the real `family_uid`/`model_uid` fields, maps punctuation to a
catalog id only after an exact normalized match, and prefers the already-proved lightning model
when available.
Tests first prove the trusted proxy boundary, exact host policy, volume separation, strict auth
status gate, and catalog normalization. The live gate then runs three real Claude Code scenarios
through the authenticated in-container Devin CLI and requires local Read/Edit/Bash activity,
passing fixture tests, Devin-only routing, no allowed non-Devin egress, and an explicit error
when the Devin backend is stopped.
## Final Live Result
The default-agent design was rejected after live evidence showed that `ask` mode can still
emit Devin-owned ACP tool calls. The pinned CLI does not apply its top-level agent
configuration to `devin acp`, so an `allowed-tools: []` configuration could not create a
neutral backend. The fixed summarizer role is the only official ACP role in this version that
is structurally no-tools.
The execution-trace adaptation passed the authenticated live gate with
`swe-1-7-lightning`. Three Claude Code processes completed analysis, edit/test, and local
command/skill scenarios. Structured evidence proved that Claude Code issued `Read`, `Edit`,
and `Bash` tool calls; two client-owned `npm test` calls succeeded. The guard audit proved
Devin-only outbound access and zero Claude egress. Intermediate summary-shaped responses and
transient ACP timeouts remain explicit failure modes; the adapter performs one bounded repair
and the harness spaces scenarios to avoid bursty session creation.

View File

@@ -1,113 +0,0 @@
# Video Generation Through Preset Jobs
Custom provider nodes whose `/videos` surface is an **async submit → poll → fetch-result API** (instead of a synchronous generation endpoint) can be wired into the `/api/v1/videos/generations` route without any new provider code. The model row carries a `generationConfig.preset`, and the dispatcher routes the request through a single job executor that is configured entirely by declarative preset data.
## How dispatch works
1. The route parses `model` as `provider/model` and resolves the provider node's credentials (`POST /api/v1/videos/generations`).
2. `handleVideoGeneration` (in `open-sse/handlers/videoGeneration.ts`) checks whether the provider is a **custom provider node** (no entry in the static video registry).
3. For custom nodes it reads the custom model row via `getCustomModelVideoPreset(provider, model)`:
- The model row has `generationConfig.preset` set (e.g. `"agnes-video-job"`) → dispatch through the **job executor** (`open-sse/handlers/videoGeneration/job.ts`).
- The preset name does not match any known preset → **502** `Unknown video job preset: <preset>` (server-side misconfiguration).
- No preset configured → fall back to the generic OpenAI-compatible sync handler, mirroring the images route.
4. The job executor runs the preset pipeline: **submit** the job, **poll** for terminal status, **read** the finished video URL, and return the standard OpenAI-compatible response shape.
The executor is one handler family; every provider-specific detail (paths, auth, body shape, status/result fields, poll cadence) is data in the preset definition.
## Response contract
Both the sync and job paths return the same shape:
```json
{
"created": 1234567890,
"data": [{ "url": "https://…", "format": "mp4" }]
}
```
This is the shape the media-generation consumer reads (`data.data[0].url`), so preset-job providers are drop-in replacements for sync providers.
## Presets
Presets live in `open-sse/handlers/videoGeneration/job.ts` (`VIDEO_JOB_PRESETS`). Each preset declares:
| Field | Meaning |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `authHeaderName` / `authScheme` | `x-api-key` with `raw` value (Agnes, muapi) or `Authorization` with `Bearer` prefix (Sora). Missing credentials → request goes out without an auth header. |
| `baseUrlFallback` | Default base URL. Overridden by the provider connection's `providerSpecificData.baseUrl` (or top-level `baseUrl`), which wins when set. |
| `submit.path` / `submit.buildBody` | Where and how the job is submitted. `{model}` in the path is substituted with the encoded model id; the body is built from `model`/`prompt`/`duration` plus pass-through of every other request field. |
| `taskIdPath` | Dot path into the submit response identifying the job (e.g. `task_id`, `request_id`, `id`). Missing job id → **502**. |
| `poll.pathTemplate` | Poll URL template; `{taskId}` is substituted. |
| `statusPath` / `statusDone` / `statusFailed` | Where the job status lives and which values are terminal. |
| `resultPath` | Dot path into the poll response holding the finished video URL: a string, a string array, or an array of `{ url }` objects are all accepted. Completed job with no readable URL → **502**. |
| `maxPolls` / `pollIntervalMs` | Poll budget (default 60 polls × 2000 ms). Exhausted → **504** `Video job timed out`. |
### `agnes-video-job` — Agnes Video V2.0
- Auth: `x-api-key: <key>` (raw).
- Base URL fallback: `https://apihub.agnes-ai.com`.
- Submit: `POST /v1/videos` with `{ model, prompt, ...extras }` — image, mode, `num_frames`, `frame_rate` and other provider knobs pass through untouched.
- Job id: `task_id` from the submit response.
- Poll: `GET /v1/videos/{taskId}`; status at `status` (`completed` / `failed`).
- Result: `metadata.url` — the completed video URL is returned as JSON metadata, not a binary body.
### `muapi-video-job` — muapi.ai
- Auth: `x-api-key: <key>` (raw).
- Base URL fallback: `https://api.muapi.ai`.
- Submit: `POST /api/v1/{model}` with `{ prompt, duration?, ...extras }`.
- Job id: `request_id` from the submit response.
- Poll: `GET /api/v1/predictions/{taskId}/result`; status at `status` (`completed` / `failed`).
- Result: `outputs` — an array of video URLs.
### `sora-job` — OpenAI Sora
- Auth: `Authorization: Bearer <key>`.
- Base URL fallback: `https://api.openai.com`.
- Submit: `POST /v1/videos` with `{ model, prompt, seconds?, ...extras }`. `seconds` is a **string** enum (`"4" | "8" | "12"`) in the Sora API, so a numeric `duration` is stringified; size mapping is intentionally not forced.
- Job id: `id` from the submit response.
- Poll: `GET /v1/videos/{taskId}`; status at `status` (`completed` / `failed`).
- Result: `data` — an array whose entries are either a URL string or `{ url: "…" }`.
## Setup
1. **Register the provider node** as an OpenAI-compatible custom provider (`providerSpecificData.baseUrl` optional — the preset's `baseUrlFallback` is used when absent).
2. **Register a custom model** tagged with the `videos` endpoint and a `generationConfig`:
```json
{
"id": "super-video-v1",
"name": "Super Video v1",
"source": "manual",
"apiFormat": "chat-completions",
"supportedEndpoints": ["videos"],
"generationConfig": { "preset": "agnes-video-job" }
}
```
`addCustomModel` (in `src/lib/db/models.ts`) accepts `generationConfig?: { preset: string }` as its final parameter and persists it on the model row; `updateCustomModel` forwards it the same way. The provider-models API accepts `generationConfig` on create and update.
3. **Call the route** as usual:
```bash
curl -X POST http://localhost:8787/api/v1/videos/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $API_KEY" \
-d '{
"model": "my-custom-provider/super-video-v1",
"prompt": "a cat playing piano",
"duration": 5
}'
```
## Troubleshooting
| Symptom | Cause |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| `400 Unknown video provider: …` | Non-custom provider not in the static registry; preset jobs only apply to custom provider nodes. |
| `502 Unknown video job preset: …` | `generationConfig.preset` does not match any preset in `VIDEO_JOB_PRESETS`. Fix the model row. |
| `502 Video provider did not return a job id (…)` | Submit succeeded but the response had no readable value at `taskIdPath`. |
| `502 Video job failed (…)` / `Video job completed but no result URL found (…)` | Poll reached a terminal `statusFailed` state, or `resultPath` held no readable URL. |
| `504 Video job timed out after 60 polls (…)` | Job never reached a terminal status within the poll budget. |
| Upstream 4xx/5xx passthrough | `fetchJson` returns the upstream status when the submit/poll request itself is not OK. |
| Requests go out without auth | No `apiKey`/`accessToken` on the provider connection; the executor sends `Content-Type` only. |

View File

@@ -1,89 +0,0 @@
# OmniRoute Performance Audit — Phase 3 Report
## Measured data
| Metric | Value |
|--------|-------|
| Cold-start open-sse module load | **2,317ms** (first import) |
| proxyFallback.ts import cost | **210ms** (SQLite init + undici re-import) |
| proxyDispatcher.ts import cost | **69ms** |
| Handlers/streaming code | **686ms** |
| Services (token refresh, etc.) | **172ms** |
| Provider registry (211 files, 1.7MB) | **<5ms** (per-file lazy) |
| Provider constants lazy Proxy | **0.24ms** (first access) |
| Provider models lazy Proxy | **0.17ms** (first access) |
| Static provider imports (eager) | **~201 files** (module eval, ~200500ms I/O) |
| Executor singletons at module level | **42** |
| Module-level `setInterval` timers | **24** (many NOT `unref()`-ed) |
| Polyfill/global-patch operations | **5+** |
| DB size | 1.4GB+, usage_history 250K+ rows |
| SQLite cache_size | 16MB (conservative) |
| mmap_size in settings | 256MB (never applied as PRAGMA — **now fixed**) |
| Per-chunk transform layers | 25 `pipeThrough()` calls |
| Chunk transform GC pressure | Moderate (structuredClone removed, TextDecoder lifted) |
| Upstream HTTP | undici 3tier dispatcher (wellpooled) |
| Sync DB writes post-streaming | #1 bottleneck: saveRequestUsage + saveCallLog block event loop |
## Ranked findings (effort × impact)
### Implemented in this PR
| # | Finding | Impact | Effort | Fix |
|---|---------|--------|--------|-----|
| 1 | 🔴 **Proxy fallback loaded eagerly at startup** | **210ms** on first import | Low | Dynamic `import()` in proxyFetch.ts error handler |
| 2 | 🔴 **egressCache memory leak** (never evicts) | HIGH — unbounded growth | Very Low | Lazy TTL cleanup on `getCachedEgressIp` |
| 3 | 🔴 **Missing composite index: usage_history(provider, model, timestamp)** | HIGH — full scan on `getModelLatencyStats` | Very Low | `CREATE INDEX IF NOT EXISTS …` in schemaColumns.ts |
| 4 | 🔴 **Missing composite index: provider_connections(provider, auth_type)** | HIGH — full scan on 6+ queries | Very Low | `CREATE INDEX IF NOT EXISTS …` in schemaColumns.ts |
| 5 | 🔴 **mmap_size PRAGMA never applied** | HIGH — 256MB setting stored but unused | Very Low | PRAGMA applied after `applyStoredDatabaseOptimizationSettings` |
### Already in PR #7893 (pre-Phase 1)
| # | Finding | Impact | Effort |
|---|---------|--------|--------|
| 6 | 🔴 **Startup serialization** | 500+ms serial blocking (early imports + background services) | Low → wrapped in Promise.all / Promise.allSettled |
| 7 | 🟡 **Per-chunk structuredClone in createSSEStream** | GC pressure on every chunk | Low → replaced with minimal object spread |
| 8 | 🟡 **Per-chunk `new TextDecoder()` in progressTracker** | Minor GC churn | Very Low → module-level const |
| 9 | 🟡 **P2C quota re-evaluated per comparison (exponential blowup)** | N² work on each pool filter | Medium → Map cache threaded through pipeline |
| 10 | 🟡 **Dual `.filter()` passes in selectPoolSubset** | Double iteration on active set | Very Low → single `for` loop |
| 11 | 🟢 **Debug-loop re-filters 6 function calls** | No-op in production | Very Low → Map-based string comparisons |
| 12 | 🟢 **Backoff decay loop uses full CRUD update** | SELECT+encrypt+invalidate per unused connection | Low → targeted `resetConnectionBackoff` |
| 13 | 🟢 **Lazy PROVIDERS/PROVIDER_MODELS** | Startup saving per lazy Proxy 0.2ms | Low → Proxy on constants.ts + providerModels.ts |
| 14 | 🟢 **TextEncoder lift (claude-web.ts)** | Eliminates per-chunk instances | Low → module-level encoder |
| 15 | 🟢 **13 route files `getSettings()` → `getCachedSettings()`** | Avoids redundant decrypts | Low → import swap |
| 16 | 🟢 **settingsCache.ts dead file deletion** | Cleanup | Very Low → removed |
### Future opportunities (not yet implemented)
| # | Finding | Impact | Effort | Priority |
|---|---------|--------|--------|----------|
| 17 | 🔴 **`saveRequestUsage` dedup guard uses COALESCE on indexed columns** | FULL TABLE SCAN on every request completion | Medium | **NEXT** |
| 18 | 🔴 **24 module-level `setInterval` timers (many NOT `unref()`-ed)** | Prevent process exit + 2μs/call overhead | Low | Soon |
| 19 | 🔴 **`providerFallback.ts` (2nd path via proxyAutoSelector→transport→validation)** | 210ms but already lazy (route handlers only) | Low | Bonded |
| 20 | 🟡 **Sync DB writes block event loop after every stream** | saveRequestUsage + saveCallLog serialize through single-writer lock | High | Candidate for worker_thread |
| 21 | 🟡 **DB cache_size conservate (16MB)** | For 1.4GB DB, increases page reads | Very Low | PRAGMA change |
| 22 | 🟡 **Enable Redis for auth cache + quota store** | Offloads SQLite read/write pressure | Low | Config change + doc |
| 23 | 🟡 **DashboardLayout is `"use client"` with 7+ heavy children** | Entire dashboard forced to client render | High | Structural layout split |
| 24 | 🟢 **mermaid (84MB unused in src/) in dependencies** | Install bloat, not server-side cost | Very Low | Move to devDeps |
| 25 | 🟢 **3 duplicated deps in root + open-sse** | Redundant install | Very Low | Deduplicate |
| 26 | 🟡 **`SELECT *` unbounded in `getUsageHistory` (admin API)** | Risks scan of 250K+ rows | Low | Add LIMIT |
| 27 | 🟢 **Sync `readFileSync` at module eval in config loading** | Blocks event-loop-startup once | Very Low | Could defer |
| 28 | 🟡 **SetInterval timers: confirm all `unref()`-ed for remaining** | ~12 without `unref()` prevent clean exit | Low | Audit + fix |
## Status summary
| Category | Status |
|----------|--------|
| PR #7893 (original 16 optimizations) | **OPEN** — all core changes verified |
| Phase 1 tangible wins (5 items) | **Implemented** — uncommitted |
| Phase 2 EventLoopHealth | **Completed** — hot path is clean, timers need `unref()` |
| Phase 2 RequestTrace | **Not completed** (agent lost on session boundary) |
| Phase 2 TransitiveDeps | **Not completed** (agent lost on session boundary) |
| Phase 3 Report | **This document** |
## Recommended next actions
1. **Commit Phase 1 wins** (egressCache, mmap_size, indexes, proxyFallback lazy) → push to PR #7893
2. **Complete #17** — fix `COALESCE` defeating index in `saveRequestUsage` dedup guard
3. **Complete #18** — add `unref()` to all 24 module-level `setInterval` timers
4. **Complete #21** — bump `cache_size` PRAGMA to 64-128MB
5. **Document Redis configuration** for auth cache + quota store offload

View File

@@ -1,62 +0,0 @@
# Quality Ratchet
| Métrica | Baseline | Atual | Status |
| ----------------------------------------------------------------- | -------- | ----- | --------------------- |
| eslintWarnings | 0 | 0 | ok |
| eslintErrors | 0 | 0 | ok |
| coverage.statements | 80.8 | — | SKIP (ausente) |
| coverage.lines | 80.8 | — | SKIP (ausente) |
| coverage.functions | 86.42 | — | SKIP (ausente) |
| coverage.branches | 78.1 | — | SKIP (ausente) |
| coverage.chatCore.lines | 72.45 | — | SKIP (ausente) |
| coverage.combo.lines | 85.42 | — | SKIP (ausente) |
| coverage.accountFallback.lines | 96.78 | — | SKIP (ausente) |
| coverage.auth.lines | 92.55 | — | SKIP (ausente) |
| coverage.routeGuard.lines | 98.73 | — | SKIP (ausente) |
| coverage.error.lines | 92.13 | — | SKIP (ausente) |
| coverage.publicCreds.lines | 99.07 | — | SKIP (ausente) |
| coverage.circuitBreaker.lines | 95.09 | — | SKIP (ausente) |
| openapiCoverage.pct | 38 | 38 | ok |
| i18nUiCoverage.pct | 99 | 99 | ok |
| deadExports | 227 | — | SKIP (dedicated gate) |
| cognitiveComplexity | 1223 | — | SKIP (dedicated gate) |
| typeCoveragePct | 92.17 | — | SKIP (dedicated gate) |
| codeqlAlerts | 0 | — | SKIP (dedicated gate) |
| secretFindings | 0 | — | SKIP (dedicated gate) |
| zizmorFindings | 190 | — | SKIP (dedicated gate) |
| vulnCount | 10 | — | SKIP (dedicated gate) |
| bundleSize | 7666 | — | SKIP (dedicated gate) |
| openapiBreaking | 0 | — | SKIP (dedicated gate) |
| mutationScore.src/sse/services/auth.ts | 52.57 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/services/accountFallback.ts | 68.38 | — | SKIP (dedicated gate) |
| mutationScore.src/server/authz/routeGuard.ts | 76.08 | — | SKIP (dedicated gate) |
| mutationScore.src/shared/utils/circuitBreaker.ts | 56.94 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/utils/error.ts | 43.83 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/utils/publicCreds.ts | 59.76 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/services/combo/autoStrategy.ts | 41.33 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/services/combo/comboStructure.ts | 57.82 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/services/combo/validateQuality.ts | 61.33 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/services/combo/comboPredicates.ts | 56.62 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/services/combo/rrState.ts | 70.88 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/services/combo/shadowRouting.ts | 48 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/services/combo/targetSorters.ts | 68.3 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/services/combo/comboData.ts | 76.94 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/services/combo/quotaScoring.ts | 39.73 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/services/combo/quotaStrategies.ts | 50.3 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/passthroughHelpers.ts | 80.89 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/sanitization.ts | 70.15 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/upstreamTimeouts.ts | 33 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/comboContextCache.ts | 13.62 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/idempotency.ts | 42.82 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/responseHeaders.ts | 62.7 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/executorHelpers.ts | 70.39 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/memoryExtraction.ts | 62.06 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/nonStreamingSse.ts | 72.82 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/passthroughToolNames.ts | 66.42 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/headers.ts | 94.29 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/logTruncation.ts | 77.64 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/memorySkillsInjection.ts | 13.49 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/semanticCache.ts | 60.16 | — | SKIP (dedicated gate) |
| mutationScore.open-sse/handlers/chatCore/telemetryHelpers.ts | 83.18 | — | SKIP (dedicated gate) |
**Sem regressões — gate OK.**

View File

@@ -10,14 +10,39 @@
// - coverage/ — relatórios de cobertura gerados pelo c8
// - quality-metrics.json — saída do collect-metrics.mjs (gerado, não-versionado)
// - symlinks rastreados (mode 120000) — indício de `git add -A` em worktree
// - _tasks (exato E prefixo) — repo git SEPARADO; o blob symlink rastreado causou DOIS
// wipes do diretório real (2026-08-08 e 2026-08-10; Hard Rule #23)
// - _references/ _mono_repo/ _ideia/ _cache/ — diretórios privados de raiz (regra /_*/)
// - .claude/worktrees/ — worktrees de sessão nunca entram no repo
// - docs/superpowers/ — artefatos de planejamento vivem em _tasks/, não em docs/
// - .eslintcache* .fakebin-* dist/ .build/ .artifacts/ logs/ — caches e outputs gerados
//
// Todos os prefixos são ancorados na raiz (startsWith sobre paths do `git ls-files`):
// paths aninhados legítimos como `src/lib/logs/` NÃO são atingidos.
import { execFileSync } from "node:child_process";
import { pathToFileURL } from "node:url";
const FORBIDDEN_PREFIXES = ["node_modules/", ".next/", "coverage/"];
const FORBIDDEN_PREFIXES = [
"node_modules/",
".next/",
"coverage/",
// "_" na raiz é GENÉRICO (regra abaixo em checkTrackedArtifacts): _tasks/, _references/,
// _mono_repo/, _ideia/, _cache/ e qualquer _<novo>/ futuro — dirs privados, alguns com
// repo git próprio (_tasks). Nunca rastrear nada dentro deles (Hard Rule #23).
".claude/worktrees/",
"docs/superpowers/",
".eslintcache", // matches .eslintcache, .eslintcache-complexity, .eslintcache-probe, …
".fakebin-", // test executable shim dirs (.fakebin-<pid>/)
"dist/",
".build/",
".artifacts/",
"logs/",
];
const FORBIDDEN_EXACT = new Set([
"quality-metrics.json", // legacy root location (still forbidden if a stale run writes it)
"config/quality/quality-metrics.json", // current generated location (collect-metrics.mjs)
"_tasks", // separate git repo — a tracked blob/symlink here wiped the real dir twice (HR#23)
]);
/**
@@ -36,6 +61,13 @@ export function checkTrackedArtifacts(trackedFiles, trackedSymlinks = []) {
violations.push(`forbidden tracked artifact: ${file}`);
continue;
}
// Regra genérica: NENHUM caminho de raiz prefixado com "_" pode ser rastreado
// (dir ou arquivo). Cobre _tasks, _references, _mono_repo e qualquer _<novo> futuro;
// paths aninhados legítimos (src/lib/_x) não são atingidos.
if (file.startsWith("_")) {
violations.push(`forbidden tracked artifact (root underscore path): ${file}`);
continue;
}
for (const prefix of FORBIDDEN_PREFIXES) {
if (file.startsWith(prefix)) {
violations.push(`forbidden tracked artifact (${prefix}*): ${file}`);

View File

@@ -1,29 +0,0 @@
#!/bin/bash
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLUGIN_SRC="$(dirname "$SCRIPT_DIR")/obsidian-plugin"
DESKTOP_VAULT="${1:-$HOME/Documents/Vault/Omniroute-Test}"
MOBILE_VAULT="${2:-$HOME/Documents/Vault/Test}"
echo "Building plugin..."
cd "$PLUGIN_SRC"
npm run build 2>&1 | tail -3
echo "Installing to desktop vault: $DESKTOP_VAULT"
mkdir -p "$DESKTOP_VAULT/.obsidian/plugins/omniroute-sync"
cp "$PLUGIN_SRC/dist/main.js" "$DESKTOP_VAULT/.obsidian/plugins/omniroute-sync/"
cp "$PLUGIN_SRC/manifest.json" "$DESKTOP_VAULT/.obsidian/plugins/omniroute-sync/"
cp "$PLUGIN_SRC/styles.css" "$DESKTOP_VAULT/.obsidian/plugins/omniroute-sync/"
echo " ✓ Desktop plugin installed"
if [ -d "$MOBILE_VAULT" ]; then
echo "Installing to mobile vault: $MOBILE_VAULT"
mkdir -p "$MOBILE_VAULT/.obsidian/plugins/omniroute-sync"
cp "$PLUGIN_SRC/dist/main.js" "$MOBILE_VAULT/.obsidian/plugins/omniroute-sync/"
cp "$PLUGIN_SRC/manifest.json" "$MOBILE_VAULT/.obsidian/plugins/omniroute-sync/"
cp "$PLUGIN_SRC/styles.css" "$MOBILE_VAULT/.obsidian/plugins/omniroute-sync/"
echo " ✓ Mobile plugin installed"
fi
echo "Done! Restart Obsidian on both devices to load the plugin."

View File

@@ -60,3 +60,87 @@ test("checkTrackedArtifacts: multiple violations reported", () => {
]);
assert.equal(result.length, 3);
});
// --- never-allowed classes added after the _tasks tracked-symlink wipes (2026-08-08/10) ---
test("checkTrackedArtifacts: _tasks tracked as exact entry (blob/symlink) is flagged", () => {
const result = checkTrackedArtifacts(["_tasks"]);
assert.equal(result.length, 1);
assert.ok(result[0].includes("_tasks"));
});
test("checkTrackedArtifacts: _tasks/ prefix is flagged", () => {
const result = checkTrackedArtifacts(["_tasks/pipeline/prs/1-analyzed/plan.md"]);
assert.equal(result.length, 1);
});
test("checkTrackedArtifacts: private root underscore dirs are flagged", () => {
const result = checkTrackedArtifacts([
"_references/_sistemas_cli/relatorio.md",
"_mono_repo/_worktrees/x/file.ts",
"_ideia/draft.md",
"_cache/entry.json",
]);
assert.equal(result.length, 4);
});
test("checkTrackedArtifacts: ANY future root underscore dir is flagged (generic rule)", () => {
const result = checkTrackedArtifacts([
"_nova-pasta-futura/qualquer/arquivo.md",
"_scratch/notes.txt",
]);
assert.equal(result.length, 2);
assert.ok(result[0].includes("root underscore path"));
});
test("checkTrackedArtifacts: root underscore FILE is flagged; nested underscore paths pass", () => {
const flagged = checkTrackedArtifacts(["_notas-soltas.md"]);
assert.equal(flagged.length, 1);
const nested = checkTrackedArtifacts([
"src/lib/_internal/helper.ts",
"open-sse/services/_shared/util.ts",
]);
assert.deepEqual(nested, []);
});
test("checkTrackedArtifacts: .claude/worktrees/ prefix is flagged", () => {
const result = checkTrackedArtifacts([".claude/worktrees/fix-123/src/app.ts"]);
assert.equal(result.length, 1);
});
test("checkTrackedArtifacts: docs/superpowers/ prefix is flagged", () => {
const result = checkTrackedArtifacts(["docs/superpowers/plans/2026-01-01-x.md"]);
assert.equal(result.length, 1);
});
test("checkTrackedArtifacts: .eslintcache family is flagged", () => {
const result = checkTrackedArtifacts([".eslintcache", ".eslintcache-complexity", ".eslintcache-probe"]);
assert.equal(result.length, 3);
});
test("checkTrackedArtifacts: .fakebin-* shim dirs are flagged", () => {
const result = checkTrackedArtifacts([".fakebin-9475/npm"]);
assert.equal(result.length, 1);
});
test("checkTrackedArtifacts: build/log output dirs are flagged", () => {
const result = checkTrackedArtifacts([
"dist/server.js",
".build/next/chunk.js",
".artifacts/eslint-results.json",
"logs/app.log",
]);
assert.equal(result.length, 4);
});
test("checkTrackedArtifacts: new prefixes are root-anchored — nested legit paths pass", () => {
const result = checkTrackedArtifacts([
"src/lib/logs/logger.ts",
"electron/dist-electron.config.ts",
"docs/architecture/ARCHITECTURE.md",
"scripts/check/check-tracked-artifacts.mjs",
"tests/unit/build/check-tracked-artifacts.test.ts",
"bin/cli/locales/en.json",
]);
assert.deepEqual(result, []);
});