Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

feat: populate Council model dropdown from OpenRouter's live catalog

Claude7fd80b8266b1
diff --git a/.env.example b/.env.example
index 068ac926..ce47a862 100644
--- a/.env.example
+++ b/.env.example
@@ -39,9 +39,9 @@ BACKEND_SHARED_SECRET=
BACKEND_ALLOWED_ORIGINS=
# Model configuration (defaults shown)
-DEFAULT_MODEL=claude-sonnet-4-6
-DEEP_REASONING_MODEL=claude-opus-4-7
-ROUTING_MODEL=claude-haiku-4-5-20251001
+DEFAULT_MODEL=claude-sonnet-5
+DEEP_REASONING_MODEL=claude-opus-5
+ROUTING_MODEL=claude-haiku-4-5
# Data paths (defaults shown — relative to repo root, override with absolute paths if needed)
# VECTOR_STORE_PATH=./chroma_db
@@ -60,6 +60,17 @@ ENABLE_CACHING=true
OPENROUTER_ENABLED=false
# Required when OPENROUTER_ENABLED=true. Get one at https://openrouter.ai.
OPENROUTER_API_KEY=
+# Live model catalog. With OpenRouter enabled the API fetches OpenRouter's
+# public /models list at startup (and every OPENROUTER_CATALOG_REFRESH_S) to
+# fill the non-Anthropic entries of the Council dropdown, so new releases
+# show up without a code change. Filtered to tool-capable, paid, text-only
+# models from the vendors below — newest N per vendor. A failed fetch keeps
+# the built-in fallback list. Defaults shown.
+# OPENROUTER_CATALOG_ENABLED=true
+# OPENROUTER_CATALOG_PROVIDERS=openai,google,anthropic,meta-llama,deepseek,x-ai
+# OPENROUTER_CATALOG_PER_PROVIDER=6
+# OPENROUTER_CATALOG_TIMEOUT_S=10
+# OPENROUTER_CATALOG_REFRESH_S=21600
# --- Local / self-hosted models ----------------------------------------------
# Route selected model slugs to a local OpenAI-compatible server (Ollama,
diff --git a/CLAUDE.md b/CLAUDE.md
index adc64703..9fc1d1ea 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -70,7 +70,7 @@ RAG context goes in the **user turn**, not the system prompt.
class YourAgent(BaseAgent):
name = "your_agent"
domain = "your_domain"
- model = "claude-sonnet-4-6"
+ model = "claude-sonnet-5"
def get_system_prompt(self) -> str:
from openexecutive.prompts.domain_prompts import YOUR_AGENT_PROMPT
@@ -149,6 +149,10 @@ See `.env.example`. Required: `ANTHROPIC_API_KEY`. Optional integrations: `SLACK
> `env -u BACKEND_SHARED_SECRET uv run pytest tests/unit/` — to match CI (CI
> does not set it).
+> **Ad-hoc scripts:** `get_settings()` requires `EXEC_EMAIL_ADDRESS` (no
+> default), so a one-off `uv run python` snippet needs it exported alongside
+> `ANTHROPIC_API_KEY` — the test suite sets both in `tests/conftest.py`.
+
> **UI lint:** `packages/ui` has no ESLint config — `npm run lint` opens an
> interactive setup prompt. `npm run build` (`next build`) is the UI's
> lint/type gate.
diff --git a/README.md b/README.md
index b7d6a1e9..eac870ba 100644
--- a/README.md
+++ b/README.md
@@ -33,7 +33,7 @@ All responses come from one consistent executive voice. The internal agent archi
```
User message
↓
-Executive Orchestrator (claude-sonnet-4-6)
+Executive Orchestrator (claude-sonnet-5)
↓ tool use → parallel specialist calls
CSO / CFO / CHRO / GC / COO / CMO / CPO / Board
↓ each specialist retrieves relevant context from ChromaDB
@@ -57,8 +57,8 @@ See [docs/architecture.md](docs/architecture.md) for the full design.
| Layer | Choice |
|---|---|
| LLM backbone | Anthropic Claude API |
-| Default model | `claude-sonnet-4-6` (Executive + most specialists) |
-| Deep reasoning | `claude-opus-4-7` (CSO, CFO, GC, Board — with extended thinking) |
+| Default model | `claude-sonnet-5` (Executive + most specialists) |
+| Deep reasoning | `claude-opus-5` (CSO, CFO, GC, Board — with extended thinking) |
| Backend | Python 3.11 + FastAPI |
| Package manager | `uv` |
| Vector store | ChromaDB (local, embedded) |
@@ -281,13 +281,13 @@ the app refuses to start.
| Variable | Required | Default | Description |
|---|---|---|---|
| `ANTHROPIC_API_KEY` | Yes¹ | — | Anthropic API key |
-| `DEFAULT_MODEL` | No | `claude-sonnet-4-6` | Executive + most specialists |
-| `DEEP_REASONING_MODEL` | No | `claude-opus-4-7` | CSO, CFO, GC, Board |
+| `DEFAULT_MODEL` | No | `claude-sonnet-5` | Executive + most specialists |
+| `DEEP_REASONING_MODEL` | No | `claude-opus-5` | CSO, CFO, GC, Board |
| `VECTOR_STORE_PATH` | No | `./chroma_db` | ChromaDB directory |
| `EPISODIC_DB_PATH` | No | `./episodic_memory.db` | SQLite for episodic memory |
| `COMPANY_PROFILE_PATH` | No | `./company/profile.yaml` | Company profile |
| `ENABLE_CACHING` | No | `true` | Anthropic prompt caching |
-| `ROUTING_MODEL` | No | `claude-haiku-4-5-20251001` | Model for intent routing |
+| `ROUTING_MODEL` | No | `claude-haiku-4-5` | Model for intent routing |
| `SLACK_BOT_TOKEN` | No | — | Slack bot OAuth token |
| `SLACK_APP_TOKEN` | No | — | Slack socket mode token |
| `EXEC_EMAIL_ADDRESS` | No | — | Executive Gmail address (Gmail MCP OAuth) |
@@ -304,6 +304,10 @@ the app refuses to start.
| `GOOGLE_OAUTH_CLIENT_SECRET` | No | — | Google OAuth client secret (Gmail MCP) |
| `OPENROUTER_ENABLED` | No | `false` | Route Claude calls through OpenRouter and unlock non-Anthropic models per-agent in the Council UI |
| `OPENROUTER_API_KEY` | No | — | Required when `OPENROUTER_ENABLED=true` |
+| `OPENROUTER_CATALOG_ENABLED` | No | `true` | Fetch OpenRouter's live `/models` catalog at startup to populate the Council dropdown; falls back to a built-in list on failure |
+| `OPENROUTER_CATALOG_PROVIDERS` | No | `openai,google,anthropic,meta-llama,deepseek,x-ai` | Vendor prefixes surfaced from the live catalog |
+| `OPENROUTER_CATALOG_PER_PROVIDER` | No | `6` | Newest tool-capable paid models per vendor (`0` = no cap) |
+| `OPENROUTER_CATALOG_REFRESH_S` | No | `21600` | Background re-fetch cadence in seconds (`0` = startup only) |
| `LOCAL_MODELS_ENABLED` | No | `false` | Route selected slugs to a local OpenAI-compatible server (Ollama, LM Studio, vLLM, llama.cpp) |
| `LOCAL_BASE_URL` | No | — | Local server URL incl. version path, e.g. `http://localhost:11434/v1`. Required when `LOCAL_MODELS_ENABLED=true` |
| `LOCAL_API_KEY` | No | — | Optional bearer token (vLLM / gateways); Ollama & LM Studio need none |
diff --git a/packages/core/README.md b/packages/core/README.md
index 084f3910..1e1eee3b 100644
--- a/packages/core/README.md
+++ b/packages/core/README.md
@@ -74,7 +74,7 @@ curl -X POST http://localhost:8000/documents \
```
User message
↓
-Executive Orchestrator (claude-sonnet-4-6)
+Executive Orchestrator (claude-sonnet-5)
↓ tool use → parallel specialist calls
CSO / CFO / CHRO / GC / COO / CMO / CPO / Board
↓ each specialist retrieves relevant context from ChromaDB
diff --git a/packages/core/openexecutive/agents/executive_proxy.py b/packages/core/openexecutive/agents/executive_proxy.py
index b550c7f9..5d2aaa2f 100644
--- a/packages/core/openexecutive/agents/executive_proxy.py
+++ b/packages/core/openexecutive/agents/executive_proxy.py
@@ -16,7 +16,7 @@ from openexecutive.agents.base import BaseAgent
class ExecutiveProxy(BaseAgent):
name = "executive"
domain = "orchestration"
- model = "claude-sonnet-4-6" # matches DEFAULT_MODEL default
+ model = "claude-sonnet-5" # matches DEFAULT_MODEL default
use_deep_reasoning = False
def get_system_prompt(self) -> str:
diff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.py
index 5e5e4a73..070e7546 100644
--- a/packages/core/openexecutive/api/main.py
+++ b/packages/core/openexecutive/api/main.py
@@ -301,6 +301,21 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
email_poller_task: asyncio.Task[None] | None = None
scheduler_task: asyncio.Task[None] | None = None
resumer_task: asyncio.Task[None] | None = None
+ catalog_refresh_task: asyncio.Task[None] | None = None
+
+ # Live OpenRouter model catalog for the Council dropdown. Awaited so the
+ # first /agents/models call already sees it; the fetch carries its own
+ # total deadline (OPENROUTER_CATALOG_TIMEOUT_S, default 10s) and body cap,
+ # and a failure just leaves the hardcoded fallback in place — startup
+ # can be delayed by at most that timeout, never blocked.
+ if settings.openrouter_enabled and settings.openrouter_catalog_enabled:
+ from openexecutive.providers.openrouter_catalog import (
+ refresh_openrouter_catalog,
+ run_catalog_refresher,
+ )
+
+ await refresh_openrouter_catalog(settings)
+ catalog_refresh_task = asyncio.create_task(run_catalog_refresher(settings))
discord_bot: Any = None
discord_bot_task: asyncio.Task[None] | None = None
@@ -422,6 +437,11 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
with contextlib.suppress(asyncio.CancelledError, Exception):
await resumer_task
+ if catalog_refresh_task is not None:
+ catalog_refresh_task.cancel()
+ with contextlib.suppress(asyncio.CancelledError, Exception):
+ await catalog_refresh_task
+
if getattr(app.state, "mcp_gateway", None) is not None:
from openexecutive.orchestrator.mcp_gateway import set_active_gateway
set_active_gateway(None)
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 45564b35..4b220ffb 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -17,22 +17,35 @@ system:
backend: Python 3.11+ · FastAPI · Anthropic Claude SDK · ChromaDB · SQLite
frontend: Next.js 15 · React 19 · TailwindCSS · Mermaid.js
models:
- default: claude-sonnet-4-6
- deep_reasoning: claude-opus-4-7
+ default: claude-sonnet-5
+ deep_reasoning: claude-opus-5
routing: claude-haiku-4-5
provider_routing: |
All LLM calls go through openexecutive.providers.get_provider(model).
The registry returns the Anthropic SDK by default. When
OPENROUTER_ENABLED=true (plus OPENROUTER_API_KEY), Claude calls are
proxied through OpenRouter so usage is billed to the operator's
- OpenRouter account, and a curated set of non-Anthropic slugs is
- added to the Council UI dropdown:
- • Paid only: openai/gpt-5, openai/gpt-5-mini, openai/gpt-5-nano,
- google/gemini-2.5-pro, google/gemini-2.5-flash,
- google/gemini-2.5-flash-lite, meta-llama/llama-3.3-70b-instruct,
- deepseek/deepseek-r1, x-ai/grok-4. The two cheapest/fastest tiers
- (gpt-5-nano, gemini-2.5-flash-lite) are intended primarily for the
- utility_fast knob.
+ OpenRouter account, and non-Anthropic slugs are added to the Council
+ UI dropdown from OpenRouter's LIVE catalog:
+ • openexecutive.providers.openrouter_catalog fetches the public
+ GET {OPENROUTER_BASE_URL}/models at API startup (awaited, bounded
+ by OPENROUTER_CATALOG_TIMEOUT_S) and again every
+ OPENROUTER_CATALOG_REFRESH_S in a background task, then filters
+ to: vendor prefix in OPENROUTER_CATALOG_PROVIDERS (default
+ openai, google, anthropic, meta-llama, deepseek, x-ai), "tools"
+ in supported_parameters, text-only output, no ":variant" suffix
+ (:free / :batch / :thinking …), paid pricing, newest
+ OPENROUTER_CATALOG_PER_PROVIDER (default 6) per vendor.
+ • registry.openrouter_models() serves that cache; when nothing has
+ loaded (fetch failed, OPENROUTER_CATALOG_ENABLED=false, CLI paths
+ that skip the lifespan) it serves the hardcoded snapshot
+ registry.OPENROUTER_MODELS instead — so a bad fetch degrades to
+ the previous behaviour, never to an empty dropdown.
+ • Catalog entries that are the same Claude model as an
+ Anthropic-direct id (e.g. anthropic/claude-opus-5) are dropped to
+ avoid duplicates; Claude generations that exist only on OpenRouter
+ (e.g. anthropic/claude-opus-4.8) stay in and get the Claude feature
+ spec.
The rate-limited ``:free`` tier (and the utility_fast-only free-model
matrix) was removed — its 429s surfaced as user-visible errors and the
per-agent free-model surface was more than it earned; BYO-model routing
@@ -48,13 +61,14 @@ system:
Settings validator just requires that at least one provider is
reachable. Requesting a Claude model with no key and OpenRouter off
returns an actionable 400.
- Non-Claude slugs route through OpenRouter, except those listed in
- LOCAL_MODELS (which route to the local backend); selecting an
+ Slugs listed in LOCAL_MODELS route to the local backend before any
+ other rule is consulted; remaining non-Claude slugs route through
+ OpenRouter; selecting an
OpenRouter-only slug with OPENROUTER_ENABLED=false is rejected at the
API layer.
Provider selection is per-call by model, not global — so the
- Executive can be on GPT-5 while the CFO specialist stays on
- claude-opus-4-7 within the same turn.
+ Executive can be on GPT-6 while the CFO specialist stays on
+ claude-opus-5 within the same turn.
invariants:
- The internal sub-agent architecture is NEVER exposed to the end user — there is one voice (the Executive).
- The Executive never signs messages under the name of company personnel or impersonates them. An identity addendum in system block 0 instructs the model to use its own exec name/email only.
@@ -153,13 +167,16 @@ providers:
fragmented tool_call argument deltas into a single tool_use block
at stream close.
routing_rules:
+ - Slug listed in LOCAL_MODELS (with LOCAL_MODELS_ENABLED=true) → local OpenAI-compatible backend. Checked FIRST, before the Claude-id regex, so an operator's explicit local slug (even one shaped like ``claude-proxy-1``) is never re-routed to a hosted vendor.
- Claude model + OPENROUTER_ENABLED=false → AnthropicProvider.
- - Claude model + OPENROUTER_ENABLED=true → OpenRouterProvider with the curated Claude OpenRouter slugs (anthropic/claude-opus-4.7, claude-sonnet-4.6, claude-haiku-4.5).
- - Non-Claude model + OPENROUTER_ENABLED=true → OpenRouterProvider with the curated non-Anthropic slugs.
+ - Claude model + OPENROUTER_ENABLED=true → OpenRouterProvider. The slug is DERIVED, not looked up — registry.openrouter_slug_for_claude maps ``claude-<family>-<major>[-<minor>][-<yyyymmdd>]`` to ``anthropic/claude-<family>-<major>[.<minor>]`` (claude-sonnet-5 → anthropic/claude-sonnet-5, claude-haiku-4-5-20251001 → anthropic/claude-haiku-4.5). The same regex defines "is a Claude model" for routing, so a previous-generation id persisted in agent_overrides (claude-opus-4-7) still routes to Anthropic instead of falling through to the non-Claude path.
+ - Non-Claude model + OPENROUTER_ENABLED=true → OpenRouterProvider with the slug passed through verbatim (live catalog or the hardcoded fallback). A ``model_resolver`` callback (registry._openrouter_model_resolver) hands Claude ids and ``anthropic/claude-*`` catalog slugs the Claude feature spec; everything else gets the non-Claude default — so a catalog refresh after the provider singleton is built needs no rebuild.
- Non-Claude model + OPENROUTER_ENABLED=false → HTTP 400 at the API boundary. No silent fallback.
council_ui_dropdown_source: |
openexecutive.providers.allowed_models_for(agent_id) — returns
- ANTHROPIC_DIRECT_MODELS plus OPENROUTER_MODELS when the toggle is on.
+ ANTHROPIC_DIRECT_MODELS (claude-opus-5, claude-sonnet-5, claude-haiku-4-5)
+ plus registry.openrouter_models() (live catalog, else the OPENROUTER_MODELS
+ fallback snapshot) when the toggle is on.
Every agent (including utility_fast) gets the same list; the
utility_fast-only free/cheap OpenRouter matrix was removed. The Council
UI dropdown (GET /agents/models?agent_id=) and the PATCH /agents/{id}
@@ -1406,7 +1423,7 @@ external_monitoring:
The research turn's model + deep-reasoning are controlled by the
`research` virtual Council agent (get_research_model() /
get_research_use_deep_reasoning(): Council override → `RESEARCH_MODEL`
- env, default claude-sonnet-4-6 with deep reasoning OFF) — pinned
+ env, default claude-sonnet-5 with deep reasoning OFF) — pinned
per-call via analyze_with_tools' overrides, NOT the agent's chat-time
deep_reasoning_model (Opus 4.7). The research turn is
retrieve-from-web-search + summarize, so the cheaper tier is the
diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.json
index 16f5a61c..448116e1 100644
--- a/packages/core/openexecutive/architecture/prebuilt/agents.json
+++ b/packages/core/openexecutive/architecture/prebuilt/agents.json
@@ -1,7 +1,7 @@
{
"section_id": "agents",
"title": "Agent Council",
- "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `board_comms` | `BoardCommsAgent` | board |\n| `talent` | `TalentAgent` | talent |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-4-6`; a deep-reasoning tier uses `claude-opus-4-7` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. Four Council-only agents (`quality_judge`, `utility_fast`, `research`, `fixture_generator`) are model/prompt-overridable in the UI but not callable via `consult_specialist`.\n\nMost specialists only *advise* \u2014 they return analysis the Executive synthesizes. The `talent` specialist (Head of Talent & Executive Search) additionally backs a vertical the Executive can *act* on: `orchestrator.talent_tools` gives the main tool loop read access to the live search pipeline (`list_engagements`, `list_candidates`, `get_candidate`, `match_candidates`) plus two side-effecting tools (`set_candidate_stage`, `start_talent_workflow`), so a chat turn can move a candidate or fire a screen/outreach workflow, not just opine. See the Talent section.\n\nBeyond the talent vertical, the Executive can launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat \u2014 see the Workflows section.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions \u2014 the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",
+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `board_comms` | `BoardCommsAgent` | board |\n| `talent` | `TalentAgent` | talent |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. With `OPENROUTER_ENABLED`, the Council dropdown's non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Four Council-only agents (`quality_judge`, `utility_fast`, `research`, `fixture_generator`) are model/prompt-overridable in the UI but not callable via `consult_specialist`.\n\nMost specialists only *advise* — they return analysis the Executive synthesizes. The `talent` specialist (Head of Talent & Executive Search) additionally backs a vertical the Executive can *act* on: `orchestrator.talent_tools` gives the main tool loop read access to the live search pipeline (`list_engagements`, `list_candidates`, `get_candidate`, `match_candidates`) plus two side-effecting tools (`set_candidate_stage`, `start_talent_workflow`), so a chat turn can move a candidate or fire a screen/outreach workflow, not just opine. See the Talent section.\n\nBeyond the talent vertical, the Executive can launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",
"mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo<br/>board_comms / talent / triage\"]\n Cso --> Claude[\"Claude (Anthropic)\"]\n Cfo --> Claude\n Gc --> Claude\n More --> Claude\n Claude --> Exec\n class User entry\n class Exec compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external",
"generated_at": "2026-06-11T00:00:00+00:00"
-}
\ No newline at end of file
+}
diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.py
index f62c1699..38eee9da 100644
--- a/packages/core/openexecutive/config.py
+++ b/packages/core/openexecutive/config.py
@@ -34,6 +34,35 @@ def _blank_or_comment(v: Any) -> bool:
)
+# Vendor prefixes surfaced from the live OpenRouter catalog when
+# OPENROUTER_CATALOG_PROVIDERS is unset. Lives here (not in providers/) so
+# providers.openrouter_catalog can import it without a config→providers cycle.
+_DEFAULT_OPENROUTER_CATALOG_PROVIDERS: tuple[str, ...] = (
+ "openai",
+ "google",
+ "anthropic",
+ "meta-llama",
+ "deepseek",
+ "x-ai",
+)
+# Six hours: OpenRouter adds models a few times a month, so anything tighter
+# is wasted requests; a restart also refreshes.
+_DEFAULT_OPENROUTER_CATALOG_REFRESH_S = 6 * 60 * 60.0
+
+
+def _parse_csv_list(v: Any) -> list[str]:
+ """Env-var list parsing shared by the comma-separated ``*_MODELS`` /
+ ``*_PROVIDERS`` settings: accepts a real list or ``"a, b,,c"``, strips
+ whitespace, drops empties. Anything else → ``[]``."""
+ if isinstance(v, (list, tuple)):
+ items = [str(x) for x in v]
+ elif isinstance(v, str):
+ items = v.split(",")
+ else:
+ return []
+ return [x.strip() for x in items if x.strip()]
+
+
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=str(_ENV_FILE),
@@ -52,16 +81,16 @@ class Settings(BaseSettings):
# while this is unset.
anthropic_api_key: str | None = Field(None, alias="ANTHROPIC_API_KEY")
- default_model: str = Field("claude-sonnet-4-6", alias="DEFAULT_MODEL")
- deep_reasoning_model: str = Field("claude-opus-4-7", alias="DEEP_REASONING_MODEL")
- routing_model: str = Field("claude-haiku-4-5-20251001", alias="ROUTING_MODEL")
+ default_model: str = Field("claude-sonnet-5", alias="DEFAULT_MODEL")
+ deep_reasoning_model: str = Field("claude-opus-5", alias="DEEP_REASONING_MODEL")
+ routing_model: str = Field("claude-haiku-4-5", alias="ROUTING_MODEL")
# Model for the executive_research specialist fan-out (research-mode turn
# only — the chat path still uses each agent's deep_reasoning_model). The
# research turn is retrieve-from-web-search + summarize, which does not
# need Opus-tier reasoning; running 7 specialists on Sonnet (deep reasoning
- # off) instead of Opus 4.7 is the dominant cost lever for the workflow.
- # Set RESEARCH_MODEL=claude-opus-4-7 to restore the prior behavior.
- research_model: str = Field("claude-sonnet-4-6", alias="RESEARCH_MODEL")
+ # off) instead of Opus is the dominant cost lever for the workflow.
+ # Set RESEARCH_MODEL=claude-opus-5 to restore the prior behavior.
+ research_model: str = Field("claude-sonnet-5", alias="RESEARCH_MODEL")
vector_store_path: Path = Field(_ROOT / "chroma_db", alias="VECTOR_STORE_PATH")
company_profile_path: Path = Field(
@@ -106,6 +135,39 @@ class Settings(BaseSettings):
openrouter_referer: str | None = Field(None, alias="OPENROUTER_REFERER")
openrouter_timeout_s: float = Field(180.0, alias="OPENROUTER_TIMEOUT_S")
+ # ---- OpenRouter live model catalog ---------------------------------
+ # With OPENROUTER_ENABLED on, the API fetches OpenRouter's public
+ # /models catalog at startup (and every OPENROUTER_CATALOG_REFRESH_S)
+ # to populate the non-Anthropic entries of the Council UI dropdown, so
+ # newly released models appear without a code change. A failed fetch
+ # falls back to the hardcoded snapshot in providers.registry. Only
+ # consulted when OPENROUTER_ENABLED=true.
+ openrouter_catalog_enabled: bool = Field(True, alias="OPENROUTER_CATALOG_ENABLED")
+ # Vendor prefixes (the part before "/" in an OpenRouter slug) to surface.
+ openrouter_catalog_providers: Annotated[list[str], NoDecode] = Field(
+ default_factory=lambda: list(_DEFAULT_OPENROUTER_CATALOG_PROVIDERS),
+ alias="OPENROUTER_CATALOG_PROVIDERS",
+ )
+ # Newest N tool-capable paid models per vendor. 0 = no cap.
+ openrouter_catalog_per_provider: int = Field(
+ 6, alias="OPENROUTER_CATALOG_PER_PROVIDER"
+ )
+ # Startup fetch is awaited, so keep this short — it bounds boot latency.
+ openrouter_catalog_timeout_s: float = Field(
+ 10.0, alias="OPENROUTER_CATALOG_TIMEOUT_S"
+ )
+ # Background re-fetch cadence. 0 disables the refresher (startup only).
+ openrouter_catalog_refresh_s: float = Field(
+ _DEFAULT_OPENROUTER_CATALOG_REFRESH_S, alias="OPENROUTER_CATALOG_REFRESH_S"
+ )
+
+ @field_validator("openrouter_catalog_providers", mode="before")
+ @classmethod
+ def _parse_openrouter_catalog_providers(cls, v: Any) -> list[str]:
+ # An explicitly empty value falls back to the default set rather than
+ # surfacing zero vendors (which would blank the dropdown).
+ return _parse_csv_list(v) or list(_DEFAULT_OPENROUTER_CATALOG_PROVIDERS)
+
# Per-call wall-clock cap for the utility_fast paths (Discord response
# gate, wait_for_human decision parser, inbound_resolver disambiguation).
# Anthropic-direct haiku usually returns in <1s, but routing utility_fast
@@ -158,11 +220,7 @@ class Settings(BaseSettings):
@field_validator("local_models", mode="before")
@classmethod
def _parse_local_models(cls, v: Any) -> list[str]:
- if isinstance(v, list):
- return [str(x).strip() for x in v if str(x).strip()]
- if isinstance(v, str) and v.strip():
- return [x.strip() for x in v.split(",") if x.strip()]
- return []
+ return _parse_csv_list(v)
@model_validator(mode="after")
def _validate_local_models(self) -> "Settings":
@@ -426,7 +484,7 @@ class Settings(BaseSettings):
)
# Cheap model for the per-finding verify call (read scraped page → verdict).
research_verify_model: str = Field(
- "claude-haiku-4-5-20251001", alias="RESEARCH_VERIFY_MODEL"
+ "claude-haiku-4-5", alias="RESEARCH_VERIFY_MODEL"
)
# Hard cap on findings verified per research run (each = 1 scrape + 1 cheap
# LLM call). Bounds added cost; verified in severity order.
diff --git a/packages/core/openexecutive/providers/openai_compatible.py b/packages/core/openexecutive/providers/openai_compatible.py
index 1ce3adad..1b496e8d 100644
--- a/packages/core/openexecutive/providers/openai_compatible.py
+++ b/packages/core/openexecutive/providers/openai_compatible.py
@@ -30,7 +30,7 @@ from __future__ import annotations
import contextlib
import json
import logging
-from collections.abc import AsyncIterator, Awaitable
+from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import AbstractAsyncContextManager
from types import SimpleNamespace
from typing import Any
@@ -63,6 +63,7 @@ class OpenAICompatibleProvider:
timeout_s: float = 180.0,
slug_lookup: dict[str, str] | None = None,
spec_lookup: dict[str, FeatureSpec] | None = None,
+ model_resolver: Callable[[str], tuple[str, FeatureSpec] | None] | None = None,
) -> None:
self._api_key = api_key
self._base_url = base_url.rstrip("/")
@@ -76,12 +77,21 @@ class OpenAICompatibleProvider:
# through unchanged (the common case for local model names).
self._slug_lookup = slug_lookup or {}
self._spec_lookup = spec_lookup or {}
+ # Optional rule-based resolver consulted BEFORE the static lookups —
+ # lets the registry map whole model families (e.g. every Claude id)
+ # without enumerating them, so a catalog refresh after construction
+ # needs no provider rebuild. Returning None defers to the lookups.
+ self._model_resolver = model_resolver
# ------------------------------------------------------------------
# internal helpers
# ------------------------------------------------------------------
def _resolve(self, anthropic_model: str) -> tuple[str, FeatureSpec]:
+ if self._model_resolver is not None:
+ resolved = self._model_resolver(anthropic_model)
+ if resolved is not None:
+ return resolved
slug = self._slug_lookup.get(anthropic_model, anthropic_model)
spec = self._spec_lookup.get(
anthropic_model,
diff --git a/packages/core/openexecutive/providers/openrouter_catalog.py b/packages/core/openexecutive/providers/openrouter_catalog.py
new file mode 100644
index 00000000..bf2cdf58
--- /dev/null
+++ b/packages/core/openexecutive/providers/openrouter_catalog.py
@@ -0,0 +1,252 @@
+"""Live OpenRouter model catalog for the Council UI dropdown.
+
+OpenRouter publishes its full model list at ``GET /api/v1/models`` (no API
+key required). Instead of hand-maintaining the non-Anthropic slug list in
+``registry.OPENROUTER_MODELS`` — which goes stale every time a vendor ships
+a model — the API fetches that catalog once at startup (and re-fetches on a
+slow timer), filters it down to a dropdown-sized set, and caches the result
+in this module. ``registry.openrouter_models()`` reads the cache and falls
+back to the hardcoded list whenever nothing has been loaded, so a failed or
+disabled fetch degrades to exactly the pre-existing behaviour.
+
+Selection rules (``select_models``), all env-tunable via ``Settings``:
+
+* provider allowlist — ``id`` prefix before the ``/`` must be listed;
+* tool calling required — every agent path issues tool_use, so a model
+ without ``"tools"`` in ``supported_parameters`` would fail on first turn;
+* text output only — image / audio generators are not chat models;
+* slug must match ``<vendor>/<name>`` in ``[A-Za-z0-9._-]`` — which also
+ excludes every ``:variant`` suffix (``:free`` 429s under load, ``:batch``
+ is async, ``:thinking`` / ``:online`` change request semantics);
+* paid only — a zero-priced entry is the rate-limited free tier by another
+ name;
+* newest ``per_provider`` entries per provider by ``created``, so the
+ dropdown tracks the current generation instead of listing 50 GPT slugs.
+
+Nothing here imports ``registry`` (which imports this module) — the cache
+is plain module state so the two can't form an import cycle.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import re
+import time
+from collections.abc import Iterable, Mapping
+from typing import Any
+
+import httpx
+
+from openexecutive.config import _DEFAULT_OPENROUTER_CATALOG_PROVIDERS
+
+logger = logging.getLogger(__name__)
+
+# Providers surfaced when OPENROUTER_CATALOG_PROVIDERS is unset. Matches the
+# vendor set the original hardcoded list covered.
+DEFAULT_CATALOG_PROVIDERS: tuple[str, ...] = _DEFAULT_OPENROUTER_CATALOG_PROVIDERS
+DEFAULT_PER_PROVIDER = 6
+
+# Hard cap on the /models response body. The real payload is well under
+# 1 MB; anything near this is not a catalog. Bounds memory at boot.
+MAX_CATALOG_BYTES = 16 * 1024 * 1024
+# Floor on the background re-fetch cadence so a mis-set env var can't turn
+# into a tight loop against OpenRouter's public endpoint.
+MIN_REFRESH_INTERVAL_S = 60.0
+# Slugs are used as identifiers downstream (allowlist, SQLite override
+# column, outbound request body). Accept only the shape OpenRouter actually
+# emits; anything else from the remote catalog is dropped, not sanitised.
+_SLUG_RE = re.compile(r"^[A-Za-z0-9._-]{1,64}/[A-Za-z0-9._-]{1,96}$")
+
+# Module-level cache. ``None`` means "never loaded" — the registry then
+# serves its hardcoded fallback. An empty list is a *loaded* result (the
+# filter matched nothing) and is served as-is so a misconfigured allowlist
+# is visible rather than silently masked by the fallback.
+_loaded_models: list[str] | None = None
+_loaded_at: float | None = None
+
+
+def loaded_models() -> list[str] | None:
+ """Slugs from the last successful fetch, or ``None`` if none succeeded."""
+ return None if _loaded_models is None else list(_loaded_models)
+
+
+def loaded_at() -> float | None:
+ """``time.time()`` of the last successful fetch, for diagnostics."""
+ return _loaded_at
+
+
+def _price(entry: Mapping[str, Any], key: str) -> float:
+ pricing = entry.get("pricing")
+ if not isinstance(pricing, Mapping):
+ return 0.0
+ try:
+ return float(pricing.get(key, 0) or 0)
+ except (TypeError, ValueError):
+ return 0.0
+
+
+def _is_candidate(entry: Mapping[str, Any], providers: frozenset[str]) -> bool:
+ model_id = entry.get("id")
+ if not isinstance(model_id, str) or _SLUG_RE.match(model_id) is None:
+ return False
+ provider, _, _rest = model_id.partition("/")
+ if provider not in providers:
+ return False
+ if "tools" not in (entry.get("supported_parameters") or []):
+ return False
+ arch = entry.get("architecture")
+ outputs = arch.get("output_modalities") if isinstance(arch, Mapping) else None
+ if list(outputs or []) != ["text"]:
+ return False
+ # Paid only. OpenRouter reports the router pseudo-models with -1.
+ return _price(entry, "prompt") > 0 or _price(entry, "completion") > 0
+
+
+def select_models(
+ entries: Iterable[Mapping[str, Any]],
+ *,
+ providers: Iterable[str] = DEFAULT_CATALOG_PROVIDERS,
+ per_provider: int = DEFAULT_PER_PROVIDER,
+) -> list[str]:
+ """Pure filter over raw catalog entries → ordered dropdown slugs.
+
+ Output is grouped in ``providers`` order, newest-first within each
+ group, capped at ``per_provider`` per group. ``per_provider <= 0`` means
+ no cap.
+ """
+ # Ordered + de-duplicated: a repeated vendor in OPENROUTER_CATALOG_PROVIDERS
+ # must not append that vendor's models twice.
+ ordered_providers = list(dict.fromkeys(p.strip() for p in providers if p and p.strip()))
+ allow = frozenset(ordered_providers)
+ by_provider: dict[str, list[tuple[float, str]]] = {p: [] for p in ordered_providers}
+ seen: set[str] = set()
+ for entry in entries:
+ if not _is_candidate(entry, allow):
+ continue
+ model_id = str(entry["id"])
+ if model_id in seen:
+ continue
+ seen.add(model_id)
+ created = entry.get("created") or 0
+ try:
+ created_f = float(created)
+ except (TypeError, ValueError):
+ created_f = 0.0
+ by_provider[model_id.partition("/")[0]].append((created_f, model_id))
+
+ selected: list[str] = []
+ for provider in ordered_providers:
+ rows = sorted(by_provider[provider], key=lambda r: (-r[0], r[1]))
+ if per_provider > 0:
+ rows = rows[:per_provider]
+ selected.extend(model_id for _, model_id in rows)
+ return selected
+
+
+async def fetch_catalog(
+ *,
+ base_url: str,
+ timeout_s: float,
+ client: httpx.AsyncClient | None = None,
+ max_bytes: int = MAX_CATALOG_BYTES,
+) -> list[dict[str, Any]]:
+ """GET ``{base_url}/models`` and return the raw ``data`` list.
+
+ Bounded two ways: ``timeout_s`` is a *total* deadline (httpx's own
+ timeout is per-read, so a trickling server would otherwise hold the
+ caller open indefinitely), and the body is streamed with a ``max_bytes``
+ cap. Raises on any transport / HTTP / size / shape error — callers
+ decide whether that means "keep the previous cache" or "use the
+ fallback".
+ """
+ url = base_url.rstrip("/") + "/models"
+ owns_client = client is None
+ http = client or httpx.AsyncClient(timeout=timeout_s)
+
+ async def _get() -> bytes:
+ buf = bytearray()
+ async with http.stream("GET", url) as resp:
+ resp.raise_for_status()
+ async for chunk in resp.aiter_bytes():
+ buf += chunk
+ if len(buf) > max_bytes:
+ raise ValueError(
+ f"OpenRouter /models response exceeds {max_bytes} bytes"
+ )
+ return bytes(buf)
+
+ try:
+ raw = await asyncio.wait_for(_get(), timeout=timeout_s)
+ finally:
+ if owns_client:
+ await http.aclose()
+ payload = json.loads(raw)
+ data = payload.get("data") if isinstance(payload, dict) else None
+ if not isinstance(data, list):
+ raise ValueError("OpenRouter /models response has no 'data' list")
+ return [d for d in data if isinstance(d, dict)]
+
+
+async def refresh_openrouter_catalog(settings: Any) -> bool:
+ """Fetch + filter + cache. Returns True on success.
+
+ Never raises: a failure logs a warning and leaves the previous cache
+ (or the never-loaded state → registry fallback) untouched.
+ """
+ global _loaded_models, _loaded_at
+ try:
+ entries = await fetch_catalog(
+ base_url=settings.openrouter_base_url,
+ timeout_s=settings.openrouter_catalog_timeout_s,
+ )
+ models = select_models(
+ entries,
+ providers=settings.openrouter_catalog_providers,
+ per_provider=settings.openrouter_catalog_per_provider,
+ )
+ except Exception as exc: # noqa: BLE001 — degrade, never crash startup
+ logger.warning(
+ "OpenRouter catalog fetch failed (%s: %s); Council dropdown keeps "
+ "%s",
+ type(exc).__name__,
+ exc,
+ "the previous catalog" if _loaded_models is not None else "the built-in fallback list",
+ )
+ return False
+ _loaded_models = models
+ _loaded_at = time.time()
+ logger.info(
+ "OpenRouter catalog loaded: %d model(s) from %d catalog entries "
+ "(providers=%s, per_provider=%d)",
+ len(models),
+ len(entries),
+ ",".join(settings.openrouter_catalog_providers),
+ settings.openrouter_catalog_per_provider,
+ )
+ return True
+
+
+async def run_catalog_refresher(settings: Any) -> None:
+ """Background loop: re-fetch every ``openrouter_catalog_refresh_s``.
+
+ Started by the API lifespan after the initial fetch so a long-lived
+ process picks up newly released models without a restart. Cancelled
+ on shutdown.
+ """
+ interval = float(settings.openrouter_catalog_refresh_s)
+ if interval <= 0:
+ return
+ interval = max(interval, MIN_REFRESH_INTERVAL_S)
+ while True:
+ await asyncio.sleep(interval)
+ # refresh_openrouter_catalog swallows Exception but not
+ # CancelledError (a BaseException), so shutdown still cancels us
+ # cleanly mid-fetch.
+ await refresh_openrouter_catalog(settings)
+
+
+def _reset_for_tests() -> None:
+ global _loaded_models, _loaded_at
+ _loaded_models = None
+ _loaded_at = None
diff --git a/packages/core/openexecutive/providers/openrouter_provider.py b/packages/core/openexecutive/providers/openrouter_provider.py
index b1549e1b..6e09ddc4 100644
--- a/packages/core/openexecutive/providers/openrouter_provider.py
+++ b/packages/core/openexecutive/providers/openrouter_provider.py
@@ -11,6 +11,8 @@ for backward compatibility with existing imports.
"""
from __future__ import annotations
+from collections.abc import Callable
+
from openexecutive.providers.feature_gate import FeatureSpec
from openexecutive.providers.openai_compatible import (
OpenAICompatibleProvider,
@@ -34,6 +36,7 @@ class OpenRouterProvider(OpenAICompatibleProvider):
timeout_s: float = 180.0,
slug_lookup: dict[str, str] | None = None,
spec_lookup: dict[str, FeatureSpec] | None = None,
+ model_resolver: Callable[[str], tuple[str, FeatureSpec] | None] | None = None,
) -> None:
# OpenRouter attribution headers — surfaced in your dashboard alongside
# the cost data so you can attribute usage back to this app.
@@ -47,4 +50,5 @@ class OpenRouterProvider(OpenAICompatibleProvider):
timeout_s=timeout_s,
slug_lookup=slug_lookup,
spec_lookup=spec_lookup,
+ model_resolver=model_resolver,
)
diff --git a/packages/core/openexecutive/providers/registry.py b/packages/core/openexecutive/providers/registry.py
index f05ad9f5..f1da5f74 100644
--- a/packages/core/openexecutive/providers/registry.py
+++ b/packages/core/openexecutive/providers/registry.py
@@ -1,19 +1,26 @@
"""Model registry + per-call provider routing.
-``MODEL_SPECS`` is the single source of truth for: what we ship to the
-Council UI, which OpenRouter slug each Claude model maps to, and which
-Anthropic-only features each model tolerates. ``get_provider(model)``
-picks the backend per call so the user can flip an agent's model in the
-Council UI and have requests for that agent — and only that agent —
-route differently.
+This module is the single source of truth for: what we ship to the
+Council UI (``allowed_models``), how a Claude model name maps to its
+OpenRouter slug (``openrouter_slug_for_claude``), and which Anthropic-only
+features each model tolerates. ``get_provider(model)`` picks the backend
+per call so the user can flip an agent's model in the Council UI and have
+requests for that agent — and only that agent — route differently.
+
+The non-Anthropic OpenRouter set is no longer a hand-maintained constant:
+``openrouter_models()`` serves the live catalog cached by
+``providers.openrouter_catalog`` (fetched at API startup) and falls back to
+the hardcoded ``OPENROUTER_MODELS`` snapshot when nothing has been loaded.
"""
from __future__ import annotations
+import re
from typing import Any
from fastapi import HTTPException
from openexecutive.config import get_settings
+from openexecutive.providers import openrouter_catalog
from openexecutive.providers.anthropic_provider import AnthropicProvider
from openexecutive.providers.feature_gate import FeatureSpec
from openexecutive.providers.openai_compatible import OpenAICompatibleProvider
@@ -23,37 +30,71 @@ from openexecutive.providers.provider import LLMProvider
# Anthropic-direct slugs — used as canonical model names everywhere in
# the codebase (config defaults, agent class defaults, override DB).
ANTHROPIC_DIRECT_MODELS: list[str] = [
- "claude-opus-4-7",
- "claude-sonnet-4-6",
- "claude-haiku-4-5-20251001",
+ "claude-opus-5",
+ "claude-sonnet-5",
+ "claude-haiku-4-5",
]
-# Models reachable only through OpenRouter. These strings ARE the
-# OpenRouter slug — we don't translate them on the way through. Curated
-# PAID models only: the rate-limited ``:free`` tier (and the utility_fast-
-# only free-model matrix) was removed — its 429s surfaced as user-visible
-# errors and the per-agent free-model surface was more than it earned.
-# BYO-model routing through OpenRouter is unchanged — add a slug here to
-# surface it in the Council UI dropdown.
+# Hardcoded FALLBACK for the non-Anthropic OpenRouter set. The live list
+# comes from ``providers.openrouter_catalog`` (fetched from OpenRouter's
+# public /models endpoint at API startup); this snapshot is served only
+# when that fetch has not succeeded (disabled, offline, CLI paths that skip
+# the lifespan). These strings ARE OpenRouter slugs — we don't translate
+# them on the way through. Curated PAID models only: the rate-limited
+# ``:free`` tier was removed because its 429s surfaced as user-visible
+# errors. Refresh this snapshot occasionally from a successful catalog
+# load; it is not the primary source anymore.
OPENROUTER_MODELS: list[str] = [
- "openai/gpt-5",
- "openai/gpt-5-mini",
- "openai/gpt-5-nano",
- "google/gemini-2.5-pro",
- "google/gemini-2.5-flash",
- "google/gemini-2.5-flash-lite",
- "meta-llama/llama-3.3-70b-instruct",
- "deepseek/deepseek-r1",
- "x-ai/grok-4",
+ "openai/gpt-6-astra",
+ "openai/gpt-6-astra-pro",
+ "openai/gpt-5.6-terra",
+ "openai/gpt-5.6-luna",
+ "google/gemini-3.8-flash",
+ "google/gemini-3.5-flash-lite",
+ "meta-llama/llama-4-maverick",
+ "meta-llama/llama-4-scout",
+ "deepseek/deepseek-v4-pro",
+ "deepseek/deepseek-v4-flash",
+ "x-ai/grok-4.6",
+ "x-ai/grok-4.5",
]
-# Per-Claude OpenRouter slug. The Anthropic-direct name is the registry
-# key; the value is what we send when OPENROUTER_ENABLED is on.
+# Anthropic model ids look like ``claude-<family>-<major>[-<minor>][-<yyyymmdd>]``
+# (``claude-opus-5``, ``claude-haiku-4-5``, or a dated pin such as
+# ``claude-haiku-4-5-20251001`` / ``claude-opus-5-20260315``).
+# OpenRouter's slug for the same model is ``anthropic/claude-<family>-<major>[.<minor>]``
+# with the date snapshot dropped. Deriving the slug mechanically means any
+# Claude id — including older ones still stored in agent overrides, and
+# newer ones set via env before this file is touched — routes correctly.
+# ``minor`` is capped at 3 digits so an 8-digit date snapshot following a
+# major-only id (``claude-opus-5-20260315``) can't be swallowed as the minor
+# version — that would derive ``anthropic/claude-opus-5.20260315``.
+_CLAUDE_ID_RE = re.compile(
+ r"^claude-(?P<family>[a-z]+)-(?P<major>\d{1,3})(?:-(?P<minor>\d{1,3}))?(?:-\d{8})?$"
+)
+# Slugs on the OpenRouter side that are Claude models (either derived from an
+# Anthropic id above, or listed verbatim by the live catalog).
+_OPENROUTER_CLAUDE_PREFIX = "anthropic/claude-"
+
+
+def openrouter_slug_for_claude(model: str) -> str | None:
+ """``claude-sonnet-4-6`` → ``anthropic/claude-sonnet-4.6``; None if not a Claude id."""
+ m = _CLAUDE_ID_RE.match(model)
+ if m is None:
+ return None
+ version = m.group("major")
+ if m.group("minor") is not None:
+ version = f"{version}.{m.group('minor')}"
+ return f"anthropic/claude-{m.group('family')}-{version}"
+
+
+# Retained as a derived view for readers of the old constant. The registry
+# itself no longer consults it — ``openrouter_slug_for_claude`` is the rule.
_CLAUDE_OPENROUTER_SLUGS: dict[str, str] = {
- "claude-opus-4-7": "anthropic/claude-opus-4.7",
- "claude-sonnet-4-6": "anthropic/claude-sonnet-4.6",
- "claude-haiku-4-5-20251001": "anthropic/claude-haiku-4.5",
+ m: slug
+ for m in ANTHROPIC_DIRECT_MODELS
+ if (slug := openrouter_slug_for_claude(m)) is not None
}
@@ -86,6 +127,22 @@ def _local_models(settings: Any) -> list[str]:
return list(getattr(settings, "local_models", []) or [])
+def openrouter_models() -> list[str]:
+ """Non-Anthropic-direct slugs offered when ``OPENROUTER_ENABLED`` is on.
+
+ Live catalog when one has been loaded, else the hardcoded fallback.
+ Catalog entries that duplicate an Anthropic-direct model (the same
+ Claude model under its OpenRouter slug) are dropped so the dropdown
+ doesn't list ``claude-opus-5`` twice; Claude models that exist ONLY on
+ OpenRouter (e.g. an older or newer generation) stay in.
+ """
+ loaded = openrouter_catalog.loaded_models()
+ if loaded is None:
+ return list(OPENROUTER_MODELS)
+ direct_slugs = set(_CLAUDE_OPENROUTER_SLUGS.values())
+ return [m for m in loaded if m not in direct_slugs]
+
+
def allowed_models() -> list[str]:
"""Flat allowlist the Council UI's dropdown reads.
@@ -94,7 +151,8 @@ def allowed_models() -> list[str]:
* Anthropic-direct trio — when an ``ANTHROPIC_API_KEY`` is set, OR when
``OPENROUTER_ENABLED`` is on (Claude is then reachable via OpenRouter).
- * OpenRouter set — when ``OPENROUTER_ENABLED`` is on.
+ * OpenRouter set (live catalog or fallback) — when ``OPENROUTER_ENABLED``
+ is on.
* Local models — when ``LOCAL_MODELS_ENABLED`` is on.
"""
settings = get_settings()
@@ -102,7 +160,7 @@ def allowed_models() -> list[str]:
if getattr(settings, "anthropic_api_key", None) or settings.openrouter_enabled:
models.extend(ANTHROPIC_DIRECT_MODELS)
if settings.openrouter_enabled:
- models.extend(OPENROUTER_MODELS)
+ models.extend(openrouter_models())
models.extend(_local_models(settings))
return models
@@ -120,7 +178,30 @@ def allowed_models_for(agent_id: str | None) -> list[str]:
def _is_claude(model: str) -> bool:
- return model in _CLAUDE_OPENROUTER_SLUGS
+ """Any Anthropic-direct Claude id, not just the current trio.
+
+ Agent overrides persisted in SQLite may still name a previous
+ generation (``claude-opus-4-7``); those must keep routing to the
+ Anthropic SDK rather than falling through to the non-Claude path.
+ """
+ return _CLAUDE_ID_RE.match(model) is not None
+
+
+def _openrouter_model_resolver(model: str) -> tuple[str, FeatureSpec] | None:
+ """Slug + feature spec for a model on the OpenRouter path.
+
+ * Anthropic id (``claude-sonnet-5``) → derived OpenRouter slug, Claude spec.
+ * Verbatim Claude slug from the catalog (``anthropic/claude-opus-4.8``) →
+ unchanged, Claude spec — OpenRouter forwards cache_control / thinking
+ to Anthropic for these, so stripping them would only cost money.
+ * Anything else → None; the provider applies the non-Claude default.
+ """
+ slug = openrouter_slug_for_claude(model)
+ if slug is not None:
+ return slug, _CLAUDE_FEATURE_SPEC
+ if model.startswith(_OPENROUTER_CLAUDE_PREFIX):
+ return model, _CLAUDE_FEATURE_SPEC
+ return None
# Module-level singletons — providers pool their own HTTP connections and
@@ -191,22 +272,17 @@ def _openrouter() -> OpenRouterProvider:
status_code=400,
detail="OpenRouter routing requires OPENROUTER_API_KEY",
)
- # Pre-build the slug + spec lookup so the provider can resolve a
- # Claude model to its OpenRouter slug + feature spec on each call.
- slug_lookup = dict(_CLAUDE_OPENROUTER_SLUGS)
- spec_lookup: dict[str, FeatureSpec] = {
- m: _CLAUDE_FEATURE_SPEC for m in ANTHROPIC_DIRECT_MODELS
- }
- for m in OPENROUTER_MODELS:
- spec_lookup[m] = _DEFAULT_NON_CLAUDE_SPEC
+ # Claude ids and catalog Claude slugs resolve through the derivation
+ # rule; every other slug (curated fallback or live catalog) gets the
+ # provider's non-Claude default spec, so a catalog refresh after
+ # construction needs no rebuild.
_openrouter_provider = OpenRouterProvider(
api_key=settings.openrouter_api_key,
base_url=settings.openrouter_base_url,
app_title=settings.openrouter_app_title,
referer=settings.openrouter_referer,
timeout_s=settings.openrouter_timeout_s,
- slug_lookup=slug_lookup,
- spec_lookup=spec_lookup,
+ model_resolver=_openrouter_model_resolver,
)
return _openrouter_provider
@@ -214,26 +290,29 @@ def _openrouter() -> OpenRouterProvider:
def get_provider(model: str) -> LLMProvider:
"""Return the provider that should serve calls for ``model``.
- Routing rules:
+ Routing rules (in precedence order):
- * Claude family — Anthropic direct by default; OpenRouter when
- ``OPENROUTER_ENABLED`` is on.
* Local models (slugs listed in ``LOCAL_MODELS`` with
``LOCAL_MODELS_ENABLED`` on) — the self-hosted OpenAI-compatible
- backend at ``LOCAL_BASE_URL``.
- * Other non-Claude (anything in ``OPENROUTER_MODELS``, or any unknown
- slug) — OpenRouter only. Raises HTTP 400 when ``OPENROUTER_ENABLED``
+ backend at ``LOCAL_BASE_URL``. Always wins for its configured slugs.
+ * Claude family (any ``claude-<family>-<version>`` id) — Anthropic
+ direct by default; OpenRouter when ``OPENROUTER_ENABLED`` is on.
+ * Other non-Claude (anything from ``openrouter_models()``, or any
+ unknown slug) — OpenRouter only. Raises HTTP 400 when ``OPENROUTER_ENABLED``
is off, since we have no other backend that speaks those models.
"""
settings = get_settings()
+ # Explicit operator config wins: a slug listed in LOCAL_MODELS never
+ # leaves the local backend, even if it happens to look like a Claude id
+ # (``claude-proxy-1`` on an on-prem gateway). Checked BEFORE the Claude
+ # regex so widening ``_is_claude`` can't silently re-route local traffic
+ # to a hosted vendor.
+ if model in _local_models(settings):
+ return _local()
if _is_claude(model):
if settings.openrouter_enabled:
return _openrouter()
return _anthropic()
- # Local models take precedence for their configured slugs — a local
- # endpoint can serve them with no external dependency.
- if model in _local_models(settings):
- return _local()
# Other non-Claude slugs require OpenRouter to be enabled.
if not settings.openrouter_enabled:
raise HTTPException(
diff --git a/packages/core/tests/unit/test_agents_route.py b/packages/core/tests/unit/test_agents_route.py
index 2dfd4af6..6a41d42f 100644
--- a/packages/core/tests/unit/test_agents_route.py
+++ b/packages/core/tests/unit/test_agents_route.py
@@ -30,8 +30,8 @@ def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
def test_list_models_returns_allowed_models(client: TestClient) -> None:
res = client.get("/agents/models")
assert res.status_code == 200
- assert "claude-opus-4-7" in res.json()
- assert "claude-sonnet-4-6" in res.json()
+ assert "claude-opus-5" in res.json()
+ assert "claude-sonnet-5" in res.json()
def test_list_agents_returns_all_specialists(client: TestClient) -> None:
@@ -79,12 +79,12 @@ def test_patch_rejects_unknown_model(client: TestClient) -> None:
def test_patch_rejects_openrouter_model_when_openrouter_disabled(
client: TestClient, monkeypatch: pytest.MonkeyPatch
) -> None:
- """``openai/gpt-5`` is a known OpenRouter slug, but with
+ """``openai/gpt-6-astra`` is a known OpenRouter slug, but with
``OPENROUTER_ENABLED=false`` it is NOT in the runtime's allowed list
— the runtime has no backend that can serve it, so the API rejects
the override at PATCH time rather than 500-ing on first chat call."""
# The default config in conftest leaves OPENROUTER_ENABLED unset (False).
- res = client.patch("/agents/cso", json={"model": "openai/gpt-5"})
+ res = client.patch("/agents/cso", json={"model": "openai/gpt-6-astra"})
assert res.status_code == 400
assert "allowed" in res.json()["detail"].lower()
@@ -92,9 +92,10 @@ def test_patch_rejects_openrouter_model_when_openrouter_disabled(
def test_patch_accepts_openrouter_model_when_openrouter_enabled(
client: TestClient, monkeypatch: pytest.MonkeyPatch
) -> None:
- """With ``OPENROUTER_ENABLED=true`` the curated OpenRouter slugs are
- allowed values — operators can flip an agent to GPT-5 via the
- Council UI without a code change."""
+ """With ``OPENROUTER_ENABLED=true`` the OpenRouter slugs (live catalog,
+ or the built-in fallback when none is loaded) are allowed values —
+ operators can flip an agent to GPT-6 via the Council UI without a code
+ change."""
# Patch the registry's settings reader so allowed_models() folds the
# OpenRouter set in. We can't toggle a real Settings() instance from
# inside the test process because pydantic-settings caches behavior.
@@ -112,10 +113,10 @@ def test_patch_accepts_openrouter_model_when_openrouter_enabled(
openrouter_timeout_s=180.0,
),
)
- res = client.patch("/agents/cso", json={"model": "openai/gpt-5"})
+ res = client.patch("/agents/cso", json={"model": "openai/gpt-6-astra"})
# 200 means the model passed the allowlist; the override was persisted.
assert res.status_code == 200, res.text
- assert res.json()["model"] == "openai/gpt-5"
+ assert res.json()["model"] == "openai/gpt-6-astra"
def test_reset_clears_override(client: TestClient) -> None:
@@ -158,14 +159,14 @@ def test_test_endpoint_passes_draft_to_analyze(client: TestClient) -> None:
json={
"query": "Hi",
"prompt": "DRAFT_PROMPT",
- "model": "claude-sonnet-4-6",
+ "model": "claude-sonnet-5",
"use_deep_reasoning": False,
},
)
assert res.status_code == 200, res.text
assert res.json()["response"] == "draft answer"
kw = create_mock.await_args.kwargs
- assert kw["model"] == "claude-sonnet-4-6"
+ assert kw["model"] == "claude-sonnet-5"
assert kw["system"][0]["text"] == "DRAFT_PROMPT"
# And no DB row was written.
@@ -208,19 +209,19 @@ def test_get_executive_detail_uses_persona_default(client: TestClient) -> None:
def test_patch_executive_persists_override(client: TestClient) -> None:
res = client.patch(
"/agents/executive",
- json={"prompt": "You are a calm Executive.", "model": "claude-opus-4-7"},
+ json={"prompt": "You are a calm Executive.", "model": "claude-opus-5"},
)
assert res.status_code == 200
detail = res.json()
assert detail["prompt"] == "You are a calm Executive."
- assert detail["model"] == "claude-opus-4-7"
+ assert detail["model"] == "claude-opus-5"
assert detail["has_override"] is True
assert set(detail["overridden_fields"]) >= {"prompt", "model"}
# Re-fetch confirms persistence.
again = client.get("/agents/executive").json()
assert again["prompt"] == "You are a calm Executive."
- assert again["model"] == "claude-opus-4-7"
+ assert again["model"] == "claude-opus-5"
def test_reset_executive_override_clears_it(client: TestClient) -> None:
@@ -257,13 +258,13 @@ def test_executive_test_endpoint_uses_draft_prompt(client: TestClient) -> None:
json={
"query": "Hello",
"prompt": "DRAFT_EXEC_PROMPT",
- "model": "claude-sonnet-4-6",
+ "model": "claude-sonnet-5",
},
)
assert res.status_code == 200, res.text
assert res.json()["response"] == "exec preview"
kw = create_mock.await_args.kwargs
- assert kw["model"] == "claude-sonnet-4-6"
+ assert kw["model"] == "claude-sonnet-5"
assert kw["system"][0]["text"] == "DRAFT_EXEC_PROMPT"
# Test endpoint must not persist.
assert client.get("/agents/executive").json()["has_override"] is False
diff --git a/packages/core/tests/unit/test_fixture_generator_council.py b/packages/core/tests/unit/test_fixture_generator_council.py
index 434e7cc6..81a69aa7 100644
--- a/packages/core/tests/unit/test_fixture_generator_council.py
+++ b/packages/core/tests/unit/test_fixture_generator_council.py
@@ -53,12 +53,12 @@ def test_fixture_generator_detail(client: TestClient) -> None:
def test_override_propagates_to_effective_model(client: TestClient) -> None:
res = client.patch(
"/agents/fixture_generator",
- json={"model": "claude-haiku-4-5-20251001"},
+ json={"model": "claude-haiku-4-5"},
)
assert res.status_code == 200
- assert res.json()["model"] == "claude-haiku-4-5-20251001"
+ assert res.json()["model"] == "claude-haiku-4-5"
# The generator reads effective_model() at call time → picks up the override.
- assert FixtureGeneratorAgent().effective_model() == "claude-haiku-4-5-20251001"
+ assert FixtureGeneratorAgent().effective_model() == "claude-haiku-4-5"
def test_effective_model_defaults_to_settings(client: TestClient) -> None:
@@ -69,7 +69,7 @@ def test_effective_model_defaults_to_settings(client: TestClient) -> None:
def test_reset_clears_override(client: TestClient) -> None:
- client.patch("/agents/fixture_generator", json={"model": "claude-haiku-4-5-20251001"})
+ client.patch("/agents/fixture_generator", json={"model": "claude-haiku-4-5"})
res = client.delete("/agents/fixture_generator/override")
assert res.status_code == 204
assert client.get("/agents/fixture_generator").json()["has_override"] is False
diff --git a/packages/core/tests/unit/test_openrouter_catalog.py b/packages/core/tests/unit/test_openrouter_catalog.py
new file mode 100644
index 00000000..7090fb91
--- /dev/null
+++ b/packages/core/tests/unit/test_openrouter_catalog.py
@@ -0,0 +1,452 @@
+"""Live OpenRouter catalog → Council dropdown, with hardcoded fallback.
+
+Pins:
+
+1. ``select_models`` filtering: provider allowlist, tool-calling required,
+ text output only, no ``:variant`` suffixes, paid only, newest-N per
+ provider in allowlist order.
+2. ``registry.openrouter_models()`` serves the fallback until a catalog is
+ loaded, then the catalog — minus slugs that duplicate the Anthropic-direct
+ trio.
+3. ``refresh_openrouter_catalog`` never raises: transport / HTTP / shape
+ errors keep the previous state and return False.
+4. Claude id → OpenRouter slug derivation, and the routing rule that any
+ Claude id (not just the current trio) still resolves to the Anthropic
+ backend.
+5. The OpenRouter provider hands catalog Claude slugs the Claude feature
+ spec and everything else the non-Claude default.
+"""
+from __future__ import annotations
+
+import os
+from types import SimpleNamespace
+from typing import Any
+
+os.environ.setdefault("ANTHROPIC_API_KEY", "sk-test-not-used")
+
+import httpx # noqa: E402
+import pytest # noqa: E402
+
+from openexecutive.providers import openrouter_catalog as catalog # noqa: E402
+from openexecutive.providers import registry as registry_mod # noqa: E402
+from openexecutive.providers.registry import ( # noqa: E402
+ ANTHROPIC_DIRECT_MODELS,
+ OPENROUTER_MODELS,
+ get_provider,
+ openrouter_models,
+ openrouter_slug_for_claude,
+)
+
+
[email protected](autouse=True)
+def _reset() -> Any:
+ catalog._reset_for_tests()
+ registry_mod._reset_for_tests()
+ yield
+ catalog._reset_for_tests()
+ registry_mod._reset_for_tests()
+
+
+def _entry(
+ model_id: str,
+ *,
+ created: int = 1_700_000_000,
+ tools: bool = True,
+ prompt_price: str = "0.000001",
+ completion_price: str = "0.000002",
+ outputs: list[str] | None = None,
+) -> dict[str, Any]:
+ return {
+ "id": model_id,
+ "created": created,
+ "supported_parameters": ["tools", "temperature"] if tools else ["temperature"],
+ "pricing": {"prompt": prompt_price, "completion": completion_price},
+ "architecture": {"output_modalities": outputs if outputs is not None else ["text"]},
+ }
+
+
+def _catalog_settings(**overrides: Any) -> Any:
+ base = dict(
+ openrouter_base_url="https://openrouter.example/api/v1",
+ openrouter_catalog_timeout_s=1.0,
+ openrouter_catalog_providers=["openai", "anthropic"],
+ openrouter_catalog_per_provider=6,
+ openrouter_catalog_refresh_s=0.0,
+ )
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+
+def _registry_settings(*, enabled: bool) -> Any:
+ return SimpleNamespace(
+ anthropic_api_key="sk-test",
+ openrouter_enabled=enabled,
+ openrouter_api_key="sk-or-test",
+ openrouter_base_url="https://openrouter.example/api/v1",
+ openrouter_app_title="Open Executive",
+ openrouter_referer=None,
+ openrouter_timeout_s=180.0,
+ local_models_enabled=False,
+ local_base_url=None,
+ local_models=[],
+ local_api_key=None,
+ local_timeout_s=300.0,
+ )
+
+
+# --------------------------------------------------------------------------
+# select_models
+# --------------------------------------------------------------------------
+
+
+def test_select_models_applies_every_filter() -> None:
+ entries = [
+ _entry("openai/gpt-6", created=10),
+ _entry("openai/gpt-6:free", created=11, prompt_price="0", completion_price="0"),
+ _entry("openai/gpt-6:batch", created=12),
+ _entry("openai/gpt-6-notools", created=13, tools=False),
+ _entry("openai/gpt-image", created=14, outputs=["image", "text"]),
+ _entry("openai/gpt-zero-priced", created=15, prompt_price="0", completion_price="0"),
+ _entry("openrouter/auto", created=16, prompt_price="-1", completion_price="-1"),
+ _entry("mistralai/mistral-large", created=17), # provider not allowlisted
+ _entry("bare-slug-no-provider", created=18),
+ _entry("anthropic/claude-opus-5", created=19),
+ # Remote text that isn't a well-formed slug is dropped, not sanitised.
+ _entry("openai/gpt with space", created=20),
+ _entry("openai/gpt-6\nX-Injected: 1", created=21),
+ _entry("openai/../gpt-6", created=22),
+ _entry("openai/" + "x" * 97, created=23),
+ ]
+ assert catalog.select_models(entries, providers=["openai", "anthropic"]) == [
+ "openai/gpt-6",
+ "anthropic/claude-opus-5",
+ ]
+
+
+def test_select_models_orders_by_provider_then_newest_and_caps() -> None:
+ entries = [
+ _entry("google/gemini-old", created=1),
+ _entry("openai/gpt-a", created=5),
+ _entry("openai/gpt-c", created=7),
+ _entry("openai/gpt-b", created=6),
+ _entry("google/gemini-new", created=9),
+ ]
+ out = catalog.select_models(entries, providers=["openai", "google"], per_provider=2)
+ # openai group first (allowlist order), newest-first within it, capped at 2.
+ assert out == ["openai/gpt-c", "openai/gpt-b", "google/gemini-new", "google/gemini-old"]
+ # 0 disables the cap.
+ assert len(catalog.select_models(entries, providers=["openai"], per_provider=0)) == 3
+ # A repeated vendor in the allowlist doesn't duplicate its models.
+ assert catalog.select_models(entries, providers=["openai", "openai"], per_provider=0) == [
+ "openai/gpt-c", "openai/gpt-b", "openai/gpt-a",
+ ]
+
+
+def test_select_models_dedups_and_tolerates_bad_entries() -> None:
+ entries: list[Any] = [
+ _entry("openai/gpt-6", created=1),
+ _entry("openai/gpt-6", created=2),
+ {"id": None},
+ {"id": "openai/", "supported_parameters": ["tools"]},
+ {"id": "openai/gpt-broken", "supported_parameters": ["tools"], "pricing": "n/a",
+ "architecture": {"output_modalities": ["text"]}},
+ ]
+ assert catalog.select_models(entries, providers=["openai"]) == ["openai/gpt-6"]
+
+
+# --------------------------------------------------------------------------
+# registry.openrouter_models — fallback vs. loaded catalog
+# --------------------------------------------------------------------------
+
+
+def test_openrouter_models_serves_fallback_until_loaded() -> None:
+ assert catalog.loaded_models() is None
+ assert openrouter_models() == OPENROUTER_MODELS
+ # A copy — callers can't mutate the module constant through it.
+ assert openrouter_models() is not OPENROUTER_MODELS
+
+
+def test_openrouter_models_serves_catalog_minus_direct_claude_duplicates() -> None:
+ catalog._loaded_models = [
+ "openai/gpt-6",
+ "anthropic/claude-opus-5", # same model as claude-opus-5 → dropped
+ "anthropic/claude-opus-4.8", # OpenRouter-only generation → kept
+ ]
+ assert openrouter_models() == ["openai/gpt-6", "anthropic/claude-opus-4.8"]
+
+
+def test_loaded_empty_catalog_is_served_not_masked_by_fallback() -> None:
+ """An allowlist that matches nothing is a visible misconfiguration, not
+ silently replaced by the hardcoded list."""
+ catalog._loaded_models = []
+ assert openrouter_models() == []
+
+
+def test_allowed_models_folds_catalog_in_only_when_enabled(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from openexecutive.providers import allowed_models
+
+ catalog._loaded_models = ["openai/gpt-6"]
+ monkeypatch.setattr(
+ "openexecutive.providers.registry.get_settings",
+ lambda: _registry_settings(enabled=False),
+ )
+ assert allowed_models() == ANTHROPIC_DIRECT_MODELS
+ monkeypatch.setattr(
+ "openexecutive.providers.registry.get_settings",
+ lambda: _registry_settings(enabled=True),
+ )
+ assert allowed_models() == [*ANTHROPIC_DIRECT_MODELS, "openai/gpt-6"]
+
+
+# --------------------------------------------------------------------------
+# refresh_openrouter_catalog — fetch + degrade
+# --------------------------------------------------------------------------
+
+
+def _mock_transport(handler: Any) -> None:
+ """Route every httpx.AsyncClient the module builds through ``handler``."""
+ real_client = httpx.AsyncClient
+
+ def _factory(**kwargs: Any) -> httpx.AsyncClient:
+ kwargs["transport"] = httpx.MockTransport(handler)
+ return real_client(**kwargs)
+
+ catalog.httpx.AsyncClient = _factory # type: ignore[misc]
+
+
+def restore_httpx() -> Any:
+ real = catalog.httpx.AsyncClient
+ yield
+ catalog.httpx.AsyncClient = real # type: ignore[misc]
+
+
[email protected]("restore_httpx")
+async def test_refresh_loads_filtered_catalog() -> None:
+ seen: dict[str, str] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen["url"] = str(request.url)
+ return httpx.Response(
+ 200,
+ json={"data": [
+ _entry("openai/gpt-6", created=2),
+ _entry("openai/gpt-5:free", prompt_price="0", completion_price="0"),
+ _entry("anthropic/claude-sonnet-5", created=1),
+ _entry("qwen/qwen-x", created=3), # not allowlisted
+ ]},
+ )
+
+ _mock_transport(handler)
+ ok = await catalog.refresh_openrouter_catalog(_catalog_settings())
+ assert ok is True
+ assert seen["url"] == "https://openrouter.example/api/v1/models"
+ assert catalog.loaded_models() == ["openai/gpt-6", "anthropic/claude-sonnet-5"]
+ assert catalog.loaded_at() is not None
+
+
[email protected]("restore_httpx")
+ "handler",
+ [
+ lambda _r: httpx.Response(503, text="down"),
+ lambda _r: httpx.Response(200, json={"unexpected": True}),
+ lambda _r: httpx.Response(200, text="not json"),
+ lambda _r: (_ for _ in ()).throw(httpx.ConnectError("refused")),
+ ],
+ ids=["http-5xx", "no-data-key", "not-json", "connect-error"],
+)
+async def test_refresh_failure_keeps_previous_state(handler: Any) -> None:
+ _mock_transport(handler)
+ # Never loaded → still None → registry serves the fallback.
+ assert await catalog.refresh_openrouter_catalog(_catalog_settings()) is False
+ assert catalog.loaded_models() is None
+ assert openrouter_models() == OPENROUTER_MODELS
+ # Previously loaded → the old catalog survives a failed refresh.
+ catalog._loaded_models = ["openai/gpt-6"]
+ assert await catalog.refresh_openrouter_catalog(_catalog_settings()) is False
+ assert catalog.loaded_models() == ["openai/gpt-6"]
+
+
[email protected]("restore_httpx")
+async def test_refresh_is_bounded_by_a_total_deadline() -> None:
+ """httpx's timeout is per-read; a server that trickles bytes forever must
+ still be cut off at ``openrouter_catalog_timeout_s`` so startup can't hang."""
+ import asyncio
+ import time
+
+ async def _trickle() -> Any:
+ while True:
+ yield b" "
+ await asyncio.sleep(0.05)
+
+ def handler(_request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, content=_trickle())
+
+ _mock_transport(handler)
+ t0 = time.monotonic()
+ ok = await catalog.refresh_openrouter_catalog(
+ _catalog_settings(openrouter_catalog_timeout_s=0.3)
+ )
+ elapsed = time.monotonic() - t0
+ assert ok is False
+ assert elapsed < 2.0, f"deadline not enforced: {elapsed:.2f}s"
+ assert catalog.loaded_models() is None
+
+
[email protected]("restore_httpx")
+async def test_refresh_rejects_oversized_body(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(catalog, "MAX_CATALOG_BYTES", 64)
+ # fetch_catalog's default binds at def time — pass the cap explicitly via
+ # a wrapper so the module constant patch is honoured.
+ real_fetch = catalog.fetch_catalog
+
+ async def _capped(**kw: Any) -> Any:
+ return await real_fetch(max_bytes=catalog.MAX_CATALOG_BYTES, **kw)
+
+ monkeypatch.setattr(catalog, "fetch_catalog", _capped)
+ big = {"data": [_entry(f"openai/gpt-{i}") for i in range(50)]}
+ _mock_transport(lambda _r: httpx.Response(200, json=big))
+ assert await catalog.refresh_openrouter_catalog(_catalog_settings()) is False
+ assert catalog.loaded_models() is None
+
+
+async def test_refresher_loop_is_a_noop_when_interval_is_zero() -> None:
+ # Returns immediately rather than sleeping forever / fetching.
+ await catalog.run_catalog_refresher(_catalog_settings(openrouter_catalog_refresh_s=0))
+ assert catalog.loaded_models() is None
+
+
+# --------------------------------------------------------------------------
+# Claude id ↔ OpenRouter slug derivation + routing
+# --------------------------------------------------------------------------
+
+
+ ("model", "slug"),
+ [
+ ("claude-opus-5", "anthropic/claude-opus-5"),
+ ("claude-sonnet-5", "anthropic/claude-sonnet-5"),
+ ("claude-haiku-4-5", "anthropic/claude-haiku-4.5"),
+ ("claude-haiku-4-5-20251001", "anthropic/claude-haiku-4.5"),
+ ("claude-opus-4-7", "anthropic/claude-opus-4.7"),
+ ("claude-sonnet-4-6", "anthropic/claude-sonnet-4.6"),
+ ("claude-fable-5-1", "anthropic/claude-fable-5.1"),
+ # Dated pin of a major-only id: the date must not be read as a minor.
+ ("claude-opus-5-20260315", "anthropic/claude-opus-5"),
+ ("claude-sonnet-5-20260101", "anthropic/claude-sonnet-5"),
+ ],
+)
+def test_openrouter_slug_for_claude(model: str, slug: str) -> None:
+ assert openrouter_slug_for_claude(model) == slug
+
+
+ "model",
+ [
+ "openai/gpt-6",
+ "anthropic/claude-opus-5",
+ "llama3.3",
+ "claude",
+ "claude-opus",
+ "claude-opus-5-2026", # malformed date
+ "claude-3-5-sonnet-20241022", # legacy shape, family not first
+ "",
+ ],
+)
+def test_openrouter_slug_for_claude_rejects_non_claude_ids(model: str) -> None:
+ assert openrouter_slug_for_claude(model) is None
+
+
+def test_every_direct_model_has_a_derived_slug() -> None:
+ for m in ANTHROPIC_DIRECT_MODELS:
+ assert openrouter_slug_for_claude(m) is not None
+
+
+def test_previous_generation_claude_id_still_routes_to_anthropic(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """An agent override persisted before the trio was refreshed must not
+ fall through to the non-Claude path (which 400s with OpenRouter off)."""
+ from openexecutive.providers.anthropic_provider import AnthropicProvider
+
+ monkeypatch.setattr(
+ "openexecutive.providers.registry.get_settings",
+ lambda: _registry_settings(enabled=False),
+ )
+ monkeypatch.setattr(
+ "openexecutive.providers.anthropic_provider.anthropic.AsyncAnthropic",
+ lambda **_kw: SimpleNamespace(),
+ )
+ assert isinstance(get_provider("claude-opus-4-7"), AnthropicProvider)
+ assert isinstance(get_provider("claude-haiku-4-5-20251001"), AnthropicProvider)
+
+
+def test_local_slug_that_looks_like_claude_stays_local(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A slug the operator listed in LOCAL_MODELS must never be re-routed
+ to a hosted vendor just because it matches the Claude id shape."""
+ from openexecutive.providers.openai_compatible import OpenAICompatibleProvider
+ from openexecutive.providers.openrouter_provider import OpenRouterProvider
+
+ settings = _registry_settings(enabled=True)
+ settings.local_models_enabled = True
+ settings.local_base_url = "http://localhost:11434/v1"
+ settings.local_models = ["claude-proxy-1", "llama3.3"]
+ monkeypatch.setattr("openexecutive.providers.registry.get_settings", lambda: settings)
+
+ provider = get_provider("claude-proxy-1")
+ assert isinstance(provider, OpenAICompatibleProvider)
+ assert not isinstance(provider, OpenRouterProvider)
+ # A real Claude id NOT in LOCAL_MODELS still takes the Claude path.
+ assert isinstance(get_provider("claude-sonnet-5"), OpenRouterProvider)
+
+
+def test_every_direct_model_keeps_cache_spec_on_openrouter_path(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Losing cache_control on a Claude model is a ~10x cost regression that
+ would otherwise fail silently — pin it for every Anthropic-direct id."""
+ monkeypatch.setattr(
+ "openexecutive.providers.registry.get_settings",
+ lambda: _registry_settings(enabled=True),
+ )
+ provider = get_provider(ANTHROPIC_DIRECT_MODELS[0])
+ for model in ANTHROPIC_DIRECT_MODELS:
+ slug, spec = provider._resolve(model)
+ assert slug.startswith("anthropic/claude-"), model
+ assert spec.supports_cache_control and spec.supports_thinking, model
+
+
+def test_openrouter_provider_resolves_specs_by_rule(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from openexecutive.providers.openrouter_provider import OpenRouterProvider
+
+ monkeypatch.setattr(
+ "openexecutive.providers.registry.get_settings",
+ lambda: _registry_settings(enabled=True),
+ )
+ provider = get_provider("openai/gpt-6")
+ assert isinstance(provider, OpenRouterProvider)
+
+ slug, spec = provider._resolve("claude-sonnet-5")
+ assert slug == "anthropic/claude-sonnet-5"
+ assert spec.supports_cache_control and spec.supports_thinking
+
+ # Verbatim catalog Claude slug: unchanged, but still the Claude spec.
+ slug, spec = provider._resolve("anthropic/claude-opus-4.8")
+ assert slug == "anthropic/claude-opus-4.8"
+ assert spec.supports_cache_control and spec.supports_thinking
+
+ # Anything else: passthrough slug, non-Claude default (Anthropic-only
+ # fields stripped).
+ slug, spec = provider._resolve("openai/gpt-6")
+ assert slug == "openai/gpt-6"
+ assert not spec.supports_cache_control
+ assert not spec.supports_thinking
+ assert not spec.supports_web_search
+ assert spec.supports_tool_use
diff --git a/packages/core/tests/unit/test_quality_judge_council.py b/packages/core/tests/unit/test_quality_judge_council.py
index 5e5ef1fc..c5aaab4d 100644
--- a/packages/core/tests/unit/test_quality_judge_council.py
+++ b/packages/core/tests/unit/test_quality_judge_council.py
@@ -63,13 +63,13 @@ def test_quality_judge_override_propagates_to_committee(
new_prompt = "You are a custom quality reviewer. Return JSON only."
res = client.patch(
"/agents/quality_judge",
- json={"prompt": new_prompt, "model": "claude-haiku-4-5-20251001"},
+ json={"prompt": new_prompt, "model": "claude-haiku-4-5"},
)
assert res.status_code == 200
detail = res.json()
assert detail["has_override"] is True
assert detail["prompt"] == new_prompt
- assert detail["model"] == "claude-haiku-4-5-20251001"
+ assert detail["model"] == "claude-haiku-4-5"
# Now the Committee should pick up both overrides.
from openexecutive.orchestrator.committee_reviewers import build_quality_reviewer
@@ -77,7 +77,7 @@ def test_quality_judge_override_propagates_to_committee(
reviewer = build_quality_reviewer(model="claude-opus-4-7")
assert reviewer.name == "quality_judge"
assert reviewer.system_prompt == new_prompt
- assert reviewer.model == "claude-haiku-4-5-20251001"
+ assert reviewer.model == "claude-haiku-4-5"
def test_build_quality_reviewer_uses_agent_model_not_passed_arg(