AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(ui): group council model picker by provider (#186)
Rufus8b3fb2fdf531
diff --git a/packages/core/openexecutive/api/routes/agents.py b/packages/core/openexecutive/api/routes/agents.pyindex e8b888de..863c7828 100644--- a/packages/core/openexecutive/api/routes/agents.py+++ b/packages/core/openexecutive/api/routes/agents.py@@ -1,7 +1,7 @@from __future__ import annotationsimport logging-from typing import Any+from typing import Any, Literalfrom fastapi import APIRouter, HTTPException, Response, statusfrom pydantic import BaseModel@@ -28,12 +28,23 @@ router = APIRouter()# what the runtime can actually serve — when OPENROUTER_ENABLED is on,# the curated OpenRouter set folds in automatically.from openexecutive.providers import allowed_models_for as _allowed_models_for # noqa: E402+from openexecutive.providers import model_options_for as _model_options_for # noqa: E402def _allowed(agent_id: str | None = None) -> list[str]:return _allowed_models_for(agent_id)+class ModelOption(BaseModel):+ """One allowlisted model, grouped for the Council's Provider → Model picker."""++ id: str+ provider: str+ provider_label: str+ route: Literal["direct", "openrouter", "local"]+ label: str++class AgentMeta(BaseModel):name: strrole: str@@ -327,6 +338,13 @@ def list_models(agent_id: str | None = None) -> list[str]:return _allowed(agent_id)[email protected]("/agents/models/options", response_model=list[ModelOption])+def list_model_options(agent_id: str | None = None) -> list[ModelOption]:+ """The ``/agents/models`` allowlist (same ids, same order) annotated with+ provider, route and a display label so the UI can group it."""+ return [ModelOption(**o) for o in _model_options_for(agent_id)]++def _is_known_agent(agent_id: str) -> bool:return agent_id == EXECUTIVE_ID or agent_id in _agent_registry()diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 6b437864..b90ac1cd 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -301,13 +301,23 @@ providers:- 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 (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.+ ANTHROPIC_DIRECT_MODELS (claude-fable-5-1, claude-opus-5-5, 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; catalog slugs that duplicate a direct id are dropped.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}- validator share this function.+ utility_fast-only free/cheap OpenRouter matrix was removed. The PATCH+ /agents/{id} validator and GET /agents/models share this function.+ The Council UI reads GET /agents/models/options?agent_id= instead —+ registry.model_options_for(), the same ids in the same order, each+ annotated with provider (anthropic for claude-* ids and anthropic/*+ slugs, the vendor prefix otherwise, local for LOCAL_MODELS — local+ checked first), provider_label, route (mirrors get_provider: local /+ direct / openrouter — Claude ids route via OpenRouter whenever+ OPENROUTER_ENABLED is on) and a display label ("Claude Opus 5.5"). The+ UI renders it as a Provider dropdown plus a Model dropdown filtered to+ that provider; a stored model missing from the list (a stale override)+ is kept selectable and marked "not in the current allowlist".scope_caveat: |Non-specialist fast classifiers (workflows.wait_for_human.parse_decision,workflows.inbound_resolver._llm_disambiguate, the Discord responsediff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.jsonindex 06aa11bf..fcac6356 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. Beside it the Executive carries its skill tools; Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. 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 nine 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| `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`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. 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. Six Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), and `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments). The last three share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nThe Executive can also 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.",+ "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. Beside it the Executive carries its skill tools; Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. 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 nine 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| `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`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the 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. Six Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), and `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments). The last three share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nThe Executive can also 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 / 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-09-22T23:07:13.054261+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex b3315487..9c8685aa 100644--- a/packages/core/openexecutive/architecture/prebuilt/api.json+++ b/packages/core/openexecutive/architecture/prebuilt/api.json@@ -1,7 +1,7 @@{"section_id": "api","title": "API Reference",- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List and read saved chat sessions (assistant messages carry their row `id` and any `feedback`). The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it (403 otherwise). The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same owner-or-principal 403 as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List and read saved chat sessions (assistant messages carry their row `id` and any `feedback`). The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it (403 otherwise). The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same owner-or-principal 403 as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |","mermaid": null,"generated_at": "2026-09-23T16:11:27Z"}diff --git a/packages/core/openexecutive/providers/__init__.py b/packages/core/openexecutive/providers/__init__.pyindex 7ed9cdf7..0a559e6b 100644--- a/packages/core/openexecutive/providers/__init__.py+++ b/packages/core/openexecutive/providers/__init__.py@@ -13,6 +13,7 @@ from openexecutive.providers.registry import (allowed_models,allowed_models_for,get_provider,+ model_options_for,model_supports_deep_reasoning,)@@ -23,5 +24,6 @@ __all__ = ["allowed_models","allowed_models_for","get_provider",+ "model_options_for","model_supports_deep_reasoning",]diff --git a/packages/core/openexecutive/providers/registry.py b/packages/core/openexecutive/providers/registry.pyindex c5e9c62d..6f64af5e 100644--- a/packages/core/openexecutive/providers/registry.py+++ b/packages/core/openexecutive/providers/registry.py@@ -15,7 +15,7 @@ the hardcoded ``OPENROUTER_MODELS`` snapshot when nothing has been loaded.from __future__ import annotationsimport re-from typing import Any+from typing import Any, Literal, TypedDictfrom fastapi import HTTPException@@ -30,6 +30,8 @@ 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-fable-5-1",+ "claude-opus-5-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5",@@ -227,6 +229,88 @@ def allowed_models_for(agent_id: str | None) -> list[str]:return allowed_models()+# Display names for the provider keys ``model_options_for`` emits. A vendor+# missing here (a new OPENROUTER_CATALOG_PROVIDERS entry) shows its raw+# OpenRouter prefix, which is still a usable group name.+_PROVIDER_LABELS: dict[str, str] = {+ "anthropic": "Anthropic",+ "openai": "OpenAI",+ "google": "Google",+ "meta-llama": "Meta",+ "deepseek": "DeepSeek",+ "x-ai": "xAI",+ "mistralai": "Mistral",+ "qwen": "Qwen",+ "local": "Local",+}+# ``anthropic/claude-opus-4.8`` → family ``opus``, version ``4.8``.+_OPENROUTER_CLAUDE_SLUG_RE = re.compile(+ r"^anthropic/claude-(?P<family>[a-z]+)-(?P<version>\d{1,3}(?:\.\d{1,3})?)$"+)+++ModelRoute = Literal["direct", "openrouter", "local"]+++class ModelOption(TypedDict):+ id: str+ provider: str+ provider_label: str+ route: ModelRoute+ label: str+++def _claude_label(model: str) -> str | None:+ """``claude-opus-5-5`` / ``anthropic/claude-opus-5.5`` → ``Claude Opus 5.5``."""+ slug = openrouter_slug_for_claude(model) or model+ m = _OPENROUTER_CLAUDE_SLUG_RE.match(slug)+ if m is None:+ return None+ return f"Claude {m.group('family').capitalize()} {m.group('version')}"+++def _model_option(model: str, *, local: bool, openrouter_enabled: bool) -> ModelOption:+ """Provider grouping + display name for one allowlisted model.++ ``route`` mirrors ``get_provider``: local slugs stay local, Claude ids+ go direct unless OpenRouter is on, everything else is OpenRouter.+ """+ route: ModelRoute+ if local:+ provider, route, label = "local", "local", model+ elif _is_claude(model):+ provider = "anthropic"+ route = "openrouter" if openrouter_enabled else "direct"+ label = _claude_label(model) or model+ else:+ vendor, sep, name = model.partition("/")+ provider = vendor if sep else "other"+ route = "openrouter"+ label = (_claude_label(model) if provider == "anthropic" else None) or name or model+ return {+ "id": model,+ "provider": provider,+ "provider_label": _PROVIDER_LABELS.get(provider, provider),+ "route": route,+ "label": label,+ }+++def model_options_for(agent_id: str | None) -> list[ModelOption]:+ """``allowed_models_for(agent_id)`` annotated for the Council's+ Provider → Model picker. Same ids, same order — the flat list stays the+ PATCH validator's source of truth; this only adds grouping and labels.+ """+ settings = get_settings()+ local = set(_local_models(settings))+ return [+ _model_option(+ m, local=m in local, openrouter_enabled=bool(settings.openrouter_enabled)+ )+ for m in allowed_models_for(agent_id)+ ]++def _is_claude(model: str) -> bool:"""Any Anthropic-direct Claude id, not just the current trio.diff --git a/packages/core/tests/unit/test_agents_route.py b/packages/core/tests/unit/test_agents_route.pyindex 6a41d42f..11fb63aa 100644--- a/packages/core/tests/unit/test_agents_route.py+++ b/packages/core/tests/unit/test_agents_route.py@@ -34,6 +34,18 @@ def test_list_models_returns_allowed_models(client: TestClient) -> None:assert "claude-sonnet-5" in res.json()+def test_list_model_options_returns_grouped_allowlist(client: TestClient) -> None:+ flat = client.get("/agents/models").json()+ res = client.get("/agents/models/options", params={"agent_id": "cso"})+ assert res.status_code == 200+ body = res.json()+ assert [o["id"] for o in body] == flat+ opus = next(o for o in body if o["id"] == "claude-opus-5-5")+ assert opus["provider"] == "anthropic"+ assert opus["label"] == "Claude Opus 5.5"+ assert set(opus) == {"id", "provider", "provider_label", "route", "label"}++def test_list_agents_returns_all_specialists(client: TestClient) -> None:res = client.get("/agents")assert res.status_code == 200diff --git a/packages/core/tests/unit/test_provider_registry.py b/packages/core/tests/unit/test_provider_registry.pyindex 98758982..8870ae01 100644--- a/packages/core/tests/unit/test_provider_registry.py+++ b/packages/core/tests/unit/test_provider_registry.py@@ -403,3 +403,120 @@ def test_claude_without_key_or_openrouter_raises_actionable_400(get_provider("claude-sonnet-4-6")assert exc_info.value.status_code == 400assert "ANTHROPIC_API_KEY" in exc_info.value.detail+++# --------------------------------------------------------------------------+# model_options_for — Council Provider → Model picker grouping+# --------------------------------------------------------------------------+++def test_model_options_match_allowlist_ids_and_order(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The grouped view must never drift from the PATCH validator's list."""+ from openexecutive.providers import allowed_models_for, model_options_for+ from openexecutive.providers import openrouter_catalog as catalog++ monkeypatch.setattr(catalog, "_loaded_models", None)+ for stub in (+ _settings_stub(enabled=False),+ _settings_stub(enabled=True),+ _settings_stub(+ enabled=True,+ local_enabled=True,+ local_base_url="http://localhost:11434/v1",+ local_models=["qwen/qwen3-8b"],+ ),+ ):+ monkeypatch.setattr(+ "openexecutive.providers.registry.get_settings", lambda s=stub: s+ )+ ids = [o["id"] for o in model_options_for("cso")]+ assert ids == allowed_models_for("cso")+++def test_model_options_group_claude_direct_under_anthropic(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from openexecutive.providers import model_options_for++ monkeypatch.setattr(+ "openexecutive.providers.registry.get_settings",+ lambda: _settings_stub(enabled=False),+ )+ by_id = {o["id"]: o for o in model_options_for(None)}+ assert by_id["claude-opus-5-5"] == {+ "id": "claude-opus-5-5",+ "provider": "anthropic",+ "provider_label": "Anthropic",+ "route": "direct",+ "label": "Claude Opus 5.5",+ }+ assert by_id["claude-fable-5-1"]["label"] == "Claude Fable 5.1"+ assert by_id["claude-haiku-4-5"]["label"] == "Claude Haiku 4.5"+ assert by_id["claude-sonnet-5"]["label"] == "Claude Sonnet 5"+++def test_model_options_route_and_merge_with_openrouter_on(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """With OpenRouter on, Claude ids route via OpenRouter (mirrors+ get_provider), OpenRouter-only Claude slugs join the same Anthropic group,+ and a catalog duplicate of a direct id is not listed twice."""+ from openexecutive.providers import model_options_for+ from openexecutive.providers import openrouter_catalog as catalog++ monkeypatch.setattr(+ catalog,+ "_loaded_models",+ [+ "anthropic/claude-fable-5.1", # duplicate of claude-fable-5-1+ "anthropic/claude-opus-4.8", # OpenRouter-only generation+ "openai/gpt-6",+ "x-ai/grok-4.6",+ "newvendor/model-1",+ ],+ )+ monkeypatch.setattr(+ "openexecutive.providers.registry.get_settings",+ lambda: _settings_stub(enabled=True),+ )+ opts = model_options_for(None)+ ids = [o["id"] for o in opts]+ by_id = {o["id"]: o for o in opts}+ assert "anthropic/claude-fable-5.1" not in ids+ assert by_id["claude-fable-5-1"]["route"] == "openrouter"+ assert by_id["anthropic/claude-opus-4.8"] == {+ "id": "anthropic/claude-opus-4.8",+ "provider": "anthropic",+ "provider_label": "Anthropic",+ "route": "openrouter",+ "label": "Claude Opus 4.8",+ }+ assert by_id["openai/gpt-6"]["provider_label"] == "OpenAI"+ assert by_id["openai/gpt-6"]["label"] == "gpt-6"+ assert by_id["x-ai/grok-4.6"]["provider_label"] == "xAI"+ # Unknown vendor: grouped under its raw prefix rather than dropped.+ assert by_id["newvendor/model-1"]["provider"] == "newvendor"+ assert by_id["newvendor/model-1"]["provider_label"] == "newvendor"+++def test_model_options_local_wins_over_vendor_shaped_slug(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from openexecutive.providers import model_options_for++ monkeypatch.setattr(+ "openexecutive.providers.registry.get_settings",+ lambda: _settings_stub(+ enabled=False,+ local_enabled=True,+ local_base_url="http://localhost:11434/v1",+ local_models=["qwen/qwen3-8b", "claude-proxy-1"],+ ),+ )+ by_id = {o["id"]: o for o in model_options_for(None)}+ for slug in ("qwen/qwen3-8b", "claude-proxy-1"):+ assert by_id[slug]["provider"] == "local"+ assert by_id[slug]["route"] == "local"+ assert by_id[slug]["label"] == slugdiff --git a/packages/ui/src/app/council/page.tsx b/packages/ui/src/app/council/page.tsxindex 416783a8..d38b6b0d 100644--- a/packages/ui/src/app/council/page.tsx+++ b/packages/ui/src/app/council/page.tsx@@ -1,19 +1,20 @@"use client";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import {AgentDetail,AgentHistoryEntry,AgentMeta,Persona,+ ModelOption,PersonaMeta,createPersona,deletePersona,getAgentDetail,getPersona,listAgentHistory,- listAgentModels,+ listAgentModelOptions,listAgents,listPersonas,patchAgent,@@ -46,6 +47,36 @@ function modelSupportsDeepReasoning(model: string): boolean {return !HAIKU_MODEL_RE.test(model);}+// A model in the picker that the backend allowlist doesn't carry: a stale+// override (claude-opus-4-7) or a default whose family isn't reachable in+// this deployment. It stays selectable so the current value is never hidden.+type PickerOption = ModelOption & { unlisted?: boolean };++function unlistedOption(id: string, known: ModelOption[]): PickerOption {+ const slash = id.indexOf("/");+ const provider = /^(anthropic\/)?claude-/i.test(id)+ ? "anthropic"+ : slash > 0+ ? id.slice(0, slash)+ : "other";+ const sibling = known.find((o) => o.provider === provider);+ const fallbackLabel = provider === "anthropic" ? "Anthropic" : provider === "other" ? "Other" : provider;+ return {+ id,+ provider,+ provider_label: sibling?.provider_label ?? fallbackLabel,+ route: sibling?.route ?? "openrouter",+ label: id,+ unlisted: true,+ };+}++const ROUTE_TEXT: Record<ModelOption["route"], string> = {+ direct: "Anthropic API",+ openrouter: "via OpenRouter",+ local: "local backend",+};+function detailToDraft(d: AgentDetail): DraftState {return {role: d.role,@@ -78,7 +109,7 @@ export default function CouncilPage() {const [selected, setSelected] = useState<string | null>(null);const [detail, setDetail] = useState<AgentDetail | null>(null);const [draft, setDraft] = useState<DraftState | null>(null);- const [models, setModels] = useState<string[]>([]);+ const [modelOptions, setModelOptions] = useState<ModelOption[]>([]);const [history, setHistory] = useState<AgentHistoryEntry[]>([]);const [historyOpen, setHistoryOpen] = useState(false);@@ -135,7 +166,7 @@ export default function CouncilPage() {if (selected) loadDetail(selected);// Refetch the model allowlist when the agent changes (every agent// currently gets the same list).- listAgentModels(selected ?? undefined).then(setModels).catch(() => {});+ listAgentModelOptions(selected ?? undefined).then(setModelOptions).catch(() => {});}, [selected, loadDetail]);useEffect(() => {@@ -157,6 +188,44 @@ export default function CouncilPage() {.catch(() => setPersonaError("Failed to load persona"));}, [selected, draft?.voice_persona_slug]);+ const pickerOptions = useMemo<PickerOption[]>(() => {+ const known = new Set(modelOptions.map((o) => o.id));+ const extra = Array.from(+ new Set([detail?.model_default, draft?.model].filter((m): m is string => !!m))+ )+ .filter((m) => !known.has(m))+ .map((m) => unlistedOption(m, modelOptions));+ return [...modelOptions, ...extra];+ }, [modelOptions, detail?.model_default, draft?.model]);++ // Provider groups in first-seen order (backend order: Anthropic first).+ const providerGroups = useMemo(() => {+ const groups = new Map<string, string>();+ for (const o of pickerOptions) {+ if (!groups.has(o.provider)) groups.set(o.provider, o.provider_label);+ }+ return Array.from(groups, ([provider, label]) => ({ provider, label }));+ }, [pickerOptions]);++ const currentModel = pickerOptions.find((o) => o.id === draft?.model);++ const selectModel = (model: string) => {+ if (!draft) return;+ setDraft({+ ...draft,+ model,+ deep_reasoning: modelSupportsDeepReasoning(model) ? draft.deep_reasoning : false,+ });+ };++ // Switching provider picks the agent's default if it lives there, else the+ // provider's first (newest) model.+ const selectProvider = (provider: string) => {+ const inGroup = pickerOptions.filter((o) => o.provider === provider);+ const next = inGroup.find((o) => o.id === detail?.model_default) ?? inGroup[0];+ if (next) selectModel(next.id);+ };+const dirty = draftIsDirty(detail, draft);const handleSave = async () => {@@ -366,34 +435,48 @@ export default function CouncilPage() {)}</label>- <label className="block text-xs">+ <div className="block text-xs"><span className="text-fg-muted uppercase tracking-widest text-[10px] font-semibold">Model</span>- <select- value={draft.model}- onChange={(e) => {- const model = e.target.value;- setDraft({- ...draft,- model,- deep_reasoning: modelSupportsDeepReasoning(model)- ? draft.deep_reasoning- : false,- });- }}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none text-sm"- >- {Array.from(new Set([detail.model_default, draft.model, ...models])).map(- (m) => (- <option key={m} value={m}>- {m}- {m === detail.model_default ? " (default)" : ""}+ <div className="mt-1 flex gap-2">+ <select+ aria-label="Model provider"+ value={currentModel?.provider ?? ""}+ onChange={(e) => selectProvider(e.target.value)}+ className="w-2/5 min-w-0 px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none text-sm"+ >+ {providerGroups.map((g) => (+ <option key={g.provider} value={g.provider}>+ {g.label}</option>- )- )}- </select>- </label>+ ))}+ </select>+ <select+ aria-label="Model"+ value={draft.model}+ onChange={(e) => selectModel(e.target.value)}+ className="flex-1 min-w-0 px-3 py-2 rounded-lg bg-surface border border-line text-fg focus:border-indigo-500/40 focus:outline-none text-sm"+ >+ {pickerOptions+ .filter((o) => o.provider === currentModel?.provider)+ .map((o) => (+ <option key={o.id} value={o.id}>+ {o.label}+ {o.id === detail.model_default ? " (default)" : ""}+ </option>+ ))}+ </select>+ </div>+ {currentModel && (+ <span className="text-[10px] text-fg-subtle mt-1 block font-mono">+ {currentModel.id} ·{" "}+ {currentModel.unlisted+ ? "not in the current allowlist"+ : ROUTE_TEXT[currentModel.route]}+ </span>+ )}+ </div></div>{detail.name !== "utility_fast" && (diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex 9f5d29fe..3dded4a7 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -1848,9 +1848,20 @@ export async function testAgent(return res.json();}-export async function listAgentModels(agentId?: string): Promise<string[]> {+// One allowlisted model, grouped for the Council's Provider → Model picker.+// Mirrors ModelOption in api/routes/agents.py. `route` says which backend+// actually serves the id (it mirrors providers.registry.get_provider).+export interface ModelOption {+ id: string;+ provider: string;+ provider_label: string;+ route: "direct" | "openrouter" | "local";+ label: string;+}++export async function listAgentModelOptions(agentId?: string): Promise<ModelOption[]> {const qs = agentId ? `?agent_id=${encodeURIComponent(agentId)}` : "";- const res = await fetch(`${API_BASE}/agents/models${qs}`);+ const res = await fetch(`${API_BASE}/agents/models/options${qs}`);if (!res.ok) throw new Error("Failed to list models");return res.json();}