Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(inference): surface the managed OpenRouter catalog in the model picker

Ghost Scripterfcb810c3f51e
diff --git a/app/src/components/chat/ModelQualityPill.tsx b/app/src/components/chat/ModelQualityPill.tsx
index fbf0986e7a..2c81906c2f 100644
--- a/app/src/components/chat/ModelQualityPill.tsx
+++ b/app/src/components/chat/ModelQualityPill.tsx
@@ -21,8 +21,35 @@ interface ModelQualityPillProps {
onValueChange?: (value: string | null, contextWindow?: number | null) => void;
}
+/**
+ * A managed passthrough model id: `openrouter/<author>/<slug>`, optionally with
+ * a `:tag` variant suffix (`:free`, `:nitro`).
+ *
+ * These are encoded BARE (no `slug:` prefix) because the managed backend
+ * addresses its own models directly. Both round-trip helpers below must special
+ * case them: a BYOK value is `providerSlug:model` where the slug never contains
+ * `/`, so splitting a passthrough id on `:` would parse
+ * `openrouter/nex-agi/nex-n2.5-mini:free` as provider
+ * `openrouter/nex-agi/nex-n2.5-mini` + model `free`, and one without any `:`
+ * would decode to null and silently drop the selection on reopen.
+ */
+/**
+ * Stable empty list. An inline `[]` prop is a new identity on every render,
+ * which re-triggered the picker's catalog effect each render.
+ */
+const NO_LOCAL_MODELS: never[] = [];
+
+function isManagedPassthroughId(value: string): boolean {
+ if (!value.startsWith('openrouter/')) return false;
+ const rest = value.slice('openrouter/'.length).split(':')[0];
+ return rest.split('/').filter(Boolean).length === 2;
+}
+
function selectionFromValue(value: string | null | undefined): ProviderModelSelection | null {
if (!value || value.startsWith('hint:')) return null;
+ if (isManagedPassthroughId(value)) {
+ return { source: { kind: 'managed' }, model: value };
+ }
const separator = value.indexOf(':');
if (separator <= 0 || separator === value.length - 1) return null;
return {
@@ -34,9 +61,13 @@ function selectionFromValue(value: string | null | undefined): ProviderModelSele
function selectionValue(selection: ProviderModelSelection): string | null {
const { source, model } = selection;
switch (source.kind) {
- // Managed has no model id to encode — clearing the override IS the choice.
+ // Managed with no model keeps the original contract: clearing the override
+ // IS the choice, and the product routes per workload. A pinned catalog id
+ // (e.g. `openrouter/deepseek/deepseek-v4-flash`) is sent bare — no
+ // `slug:` prefix — because the managed backend addresses its own models
+ // directly, and a prefix would be parsed as a BYOK provider selector.
case 'managed':
- return null;
+ return model.trim() ? model.trim() : null;
case 'cloud':
return `${source.providerSlug}:${model}`;
case 'local':
@@ -48,6 +79,12 @@ function selectionValue(selection: ProviderModelSelection): string | null {
function displayValue(value: string | null | undefined): string {
if (!value || value.startsWith('hint:')) return 'OpenHuman';
+ // Managed ids carry no `providerSlug:` prefix to strip, and slicing on `:`
+ // would reduce `…/nex-n2.5-mini:free` to just `free`. Show the model name.
+ if (isManagedPassthroughId(value)) {
+ const rest = value.slice('openrouter/'.length);
+ return rest.split('/').slice(1).join('/');
+ }
const separator = value.indexOf(':');
return separator >= 0 ? value.slice(separator + 1) : value;
}
@@ -122,7 +159,7 @@ export default function ModelQualityPill({
{open && !loading && (
<ProviderModelPickerDialog
cloudProviders={providers}
- localModels={[]}
+ localModels={NO_LOCAL_MODELS}
ollamaRunning={false}
claudeCodeEnabled={false}
initial={initial}
diff --git a/app/src/components/chat/__tests__/ModelQualityPill.test.tsx b/app/src/components/chat/__tests__/ModelQualityPill.test.tsx
index 177530b0ef..da2a9e1ac1 100644
--- a/app/src/components/chat/__tests__/ModelQualityPill.test.tsx
+++ b/app/src/components/chat/__tests__/ModelQualityPill.test.tsx
@@ -11,6 +11,27 @@ describe('ModelQualityPill', () => {
expect(screen.getByText('OpenHuman')).toBeInTheDocument();
});
+ /**
+ * Managed passthrough ids are encoded bare (no `providerSlug:` prefix). The
+ * label must not split them on `:` — doing so rendered
+ * `openrouter/nex-agi/nex-n2.5-mini:free` as just "free".
+ */
+ it('labels a managed passthrough model without stripping at the colon', () => {
+ render(<ModelQualityPill value="openrouter/nex-agi/nex-n2.5-mini:free" />);
+ expect(screen.getByText('nex-n2.5-mini:free')).toBeInTheDocument();
+ });
+
+ it('labels a managed passthrough model with no variant tag', () => {
+ render(<ModelQualityPill value="openrouter/deepseek/deepseek-v4-flash" />);
+ expect(screen.getByText('deepseek-v4-flash')).toBeInTheDocument();
+ });
+
+ /** A BYOK value still shows just the model, as before. */
+ it('still strips the provider prefix from a BYOK value', () => {
+ render(<ModelQualityPill value="openai:gpt-4o-mini" />);
+ expect(screen.getByText('gpt-4o-mini')).toBeInTheDocument();
+ });
+
it('has chevron icon', () => {
const { container } = render(<ModelQualityPill />);
const svg = container.querySelector('svg');
diff --git a/app/src/components/settings/panels/ai/ProviderModelPickerDialog.test.tsx b/app/src/components/settings/panels/ai/ProviderModelPickerDialog.test.tsx
index 8993445b2b..ef0656ba61 100644
--- a/app/src/components/settings/panels/ai/ProviderModelPickerDialog.test.tsx
+++ b/app/src/components/settings/panels/ai/ProviderModelPickerDialog.test.tsx
@@ -89,6 +89,138 @@ describe('ProviderModelPickerDialog', () => {
);
});
+ /**
+ * The managed backend's OpenRouter passthrough catalog is offered under
+ * "Managed by OpenHuman" so a specific model can be pinned while still
+ * billing through managed credits. Automatic stays the default.
+ */
+ it('lists the managed catalog and forwards a pinned model', async () => {
+ vi.mocked(listProviderModels).mockResolvedValue([
+ {
+ id: 'openrouter/deepseek/deepseek-v4-flash',
+ owned_by: 'openrouter',
+ context_window: 1_000_000,
+ display_name: 'DeepSeek V4 Flash',
+ input_per_1m: 0.0886,
+ output_per_1m: 0.1772,
+ },
+ ]);
+ const onSelect = vi.fn();
+
+ render(
+ <ProviderModelPickerDialog
+ cloudProviders={[]}
+ localModels={[]}
+ ollamaRunning={false}
+ claudeCodeEnabled={false}
+ initial={null}
+ onClose={() => {}}
+ onSelect={onSelect}
+ />
+ );
+
+ // Fetched with the managed slug, not a BYOK provider id.
+ await waitFor(() => expect(listProviderModels).toHaveBeenCalledWith('openhuman'));
+
+ const select = await screen.findByTestId('model-picker-managed-select');
+ // Display name and charged price are surfaced, not the bare slug.
+ expect(select).toHaveTextContent('DeepSeek V4 Flash');
+ expect(select).toHaveTextContent('per 1M');
+
+ fireEvent.change(select, { target: { value: 'openrouter/deepseek/deepseek-v4-flash' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Use this model' }));
+
+ await waitFor(() =>
+ expect(onSelect).toHaveBeenCalledWith({
+ source: { kind: 'managed' },
+ model: 'openrouter/deepseek/deepseek-v4-flash',
+ contextWindow: 1_000_000,
+ })
+ );
+ });
+
+ /**
+ * Pinning must be reversible: an "Automatic" option is always present, unlike
+ * ModelEntryField's empty option which disappears once a model is chosen.
+ */
+ it('can clear a pinned managed model back to automatic', async () => {
+ vi.mocked(listProviderModels).mockResolvedValue([
+ { id: 'openrouter/a/b', owned_by: 'openrouter', context_window: 1000 },
+ ]);
+ const onSelect = vi.fn();
+
+ render(
+ <ProviderModelPickerDialog
+ cloudProviders={[]}
+ localModels={[]}
+ ollamaRunning={false}
+ claudeCodeEnabled={false}
+ initial={{ source: { kind: 'managed' }, model: 'openrouter/a/b' }}
+ onClose={() => {}}
+ onSelect={onSelect}
+ />
+ );
+
+ const select = await screen.findByTestId('model-picker-managed-select');
+ fireEvent.change(select, { target: { value: '' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Use this model' }));
+
+ await waitFor(() =>
+ expect(onSelect).toHaveBeenCalledWith({
+ source: { kind: 'managed' },
+ model: '',
+ contextWindow: null,
+ })
+ );
+ });
+
+ /**
+ * Regression: the fetch effect depended on the `source` object and the
+ * `localModels` array. Callers pass those inline (`localModels={[]}`), so
+ * their identity changed every render and the effect re-ran each time —
+ * one network fetch per render, with the dropdown visibly thrashing.
+ * The effect now keys off a derived slug string.
+ */
+ it('fetches the managed catalog once, not once per render', async () => {
+ vi.mocked(listProviderModels).mockResolvedValue([
+ { id: 'openrouter/a/b', owned_by: 'openrouter', context_window: 1000 },
+ ]);
+
+ const { rerender } = render(
+ <ProviderModelPickerDialog
+ cloudProviders={[]}
+ localModels={[]}
+ ollamaRunning={false}
+ claudeCodeEnabled={false}
+ initial={null}
+ onClose={() => {}}
+ onSelect={() => {}}
+ />
+ );
+
+ await screen.findByTestId('model-picker-managed-select');
+
+ // Re-render with fresh inline props, exactly as the real callers do.
+ for (let i = 0; i < 3; i += 1) {
+ rerender(
+ <ProviderModelPickerDialog
+ cloudProviders={[]}
+ localModels={[]}
+ ollamaRunning={false}
+ claudeCodeEnabled={false}
+ initial={null}
+ onClose={() => {}}
+ onSelect={() => {}}
+ />
+ );
+ }
+
+ await waitFor(() =>
+ expect(screen.getByTestId('model-picker-managed-select')).toBeInTheDocument()
+ );
+ expect(vi.mocked(listProviderModels)).toHaveBeenCalledTimes(1);
+ });
+
it('omits managed when the host opts out', () => {
render(
<ProviderModelPickerDialog
diff --git a/app/src/components/settings/panels/ai/ProviderModelPickerDialog.tsx b/app/src/components/settings/panels/ai/ProviderModelPickerDialog.tsx
index 54f31ab9fe..dee6b565c8 100644
--- a/app/src/components/settings/panels/ai/ProviderModelPickerDialog.tsx
+++ b/app/src/components/settings/panels/ai/ProviderModelPickerDialog.tsx
@@ -3,8 +3,10 @@ import { useEffect, useMemo, useState } from 'react';
import { cn } from '../../../../lib/cn';
import { useT } from '../../../../lib/i18n/I18nContext';
import { listProviderModels, type ModelInfo } from '../../../../services/api/aiSettingsApi';
+import Alert from '../../../ui/Alert';
import Button from '../../../ui/Button';
import { ModalShell } from '../../../ui/ModalShell';
+import NativeSelect from '../../../ui/NativeSelect';
import TextField from '../../../ui/TextField';
import {
CLAUDE_CODE_DEFAULT_MODEL,
@@ -18,6 +20,25 @@ import { ProviderSwatch } from './ProviderListRow';
type TFn = (key: string, fallback?: string) => string;
+/**
+ * `cloud_providers` slug of the managed backend. The picker models managed as
+ * its own `{kind:'managed'}` source (settings filters the raw `openhuman` row
+ * out of `cloudProviders`), but the core still addresses it by slug when
+ * listing models.
+ */
+const MANAGED_PROVIDER_SLUG = 'openhuman';
+
+/** `Display Name — $in/$out per 1M`, falling back to the bare id. */
+const managedOptionLabel = (m: ModelInfo): string => {
+ const name = m.display_name?.trim() || m.id;
+ const inPrice = m.input_per_1m;
+ const outPrice = m.output_per_1m;
+ if (typeof inPrice !== 'number' || typeof outPrice !== 'number') return name;
+ const fmt = (n: number) =>
+ n === 0 ? '$0' : `$${n < 1 ? n.toFixed(3).replace(/0+$/, '') : n.toFixed(2)}`;
+ return `${name} — ${fmt(inPrice)}/${fmt(outPrice)} per 1M`;
+};
+
export interface ProviderModelSelection {
source: CustomDialogSource;
model: string;
@@ -116,6 +137,7 @@ export function ProviderModelPickerDialog({
const [loading, setLoading] = useState(false);
const [catalogError, setCatalogError] = useState<string | null>(null);
const [catalogRequest, setCatalogRequest] = useState(0);
+ const isLocalSource = source?.kind === 'local';
const selectedCloudProvider =
source?.kind === 'cloud'
@@ -127,16 +149,44 @@ export function ProviderModelPickerDialog({
catalogIds: catalog.map(candidate => candidate.id),
});
+ /**
+ * Slug whose `/models` listing backs the right-hand pane, or null when the
+ * pane is not remote-backed (local / claude-code).
+ *
+ * Derived as a plain string so the fetch effect below depends on a VALUE, not
+ * on the `source` object or the `localModels` array. Callers pass those
+ * inline (`localModels={[]}` in ModelQualityPill), so their identity changes
+ * on every render — with them in the dependency list the effect re-ran each
+ * render, which for managed meant one network fetch per render and a
+ * visibly thrashing dropdown.
+ */
+ const fetchSlug = useMemo(() => {
+ if (source?.kind === 'cloud') return source.providerSlug;
+ // Managed is fetched like a cloud provider: the core resolves the hosted
+ // API + session JWT for the `openhuman` slug and asks for the OpenRouter
+ // passthrough catalog. An empty result is expected and fine — the backend
+ // returns nothing when OPENROUTER_PASSTHROUGH_ENABLED is off — and the
+ // "Automatic" default keeps managed selectable either way.
+ if (source?.kind === 'managed') return MANAGED_PROVIDER_SLUG;
+ return null;
+ }, [source]);
+
+ // Local models are supplied by the host, not fetched. Kept separate so a new
+ // array identity re-mirrors the list without re-triggering a network call.
+ useEffect(() => {
+ if (isLocalSource) setCatalog(localModels);
+ }, [isLocalSource, localModels]);
+
useEffect(() => {
- if (!source || source.kind !== 'cloud') {
- setCatalog(source?.kind === 'local' ? localModels : []);
+ if (!fetchSlug) {
+ if (!isLocalSource) setCatalog([]);
return;
}
let active = true;
setLoading(true);
setCatalog([]);
setCatalogError(null);
- void listProviderModels(source.providerSlug)
+ void listProviderModels(fetchSlug)
.then(models => {
if (!active) return;
setCatalog(models);
@@ -151,7 +201,7 @@ export function ProviderModelPickerDialog({
return () => {
active = false;
};
- }, [catalogRequest, localModels, source]);
+ }, [catalogRequest, fetchSlug, isLocalSource]);
const filteredSources = sources.filter(candidate =>
sourceLabel(candidate, cloudProviders, t)
@@ -191,7 +241,21 @@ export function ProviderModelPickerDialog({
onClick={() => {
if (!source) return;
if (isManaged(source)) {
- onSelect({ source, model: '', contextWindow: null });
+ // An empty model keeps the original contract (product routes
+ // per workload). A pinned catalog id is forwarded like any
+ // other model so the managed backend serves that exact model.
+ const pinned = model.trim();
+ const pinnedEntry = pinned
+ ? catalog.find(candidate => candidate.id === pinned)
+ : undefined;
+ onSelect({
+ source,
+ model: pinned,
+ contextWindow:
+ pinnedEntry && (pinnedEntry.context_window ?? 0) > 0
+ ? pinnedEntry.context_window
+ : null,
+ });
return;
}
const selectedModel = catalog.find(candidate => candidate.id === model.trim());
@@ -256,8 +320,10 @@ export function ProviderModelPickerDialog({
</div>
<div className="min-w-0 p-4">
{isManaged(source) ? (
- // No model field: managed picks per workload and keeps that choice
- // current, so there is nothing here for the user to fill in.
+ // Managed offers an OPTIONAL model pick. Leaving it on "Automatic"
+ // preserves the original contract (empty model id -> the product
+ // routes per workload); choosing a catalog entry pins that model,
+ // still billed through managed credits like any tier.
<div data-testid="model-picker-managed-pane" className="space-y-2">
<p className="text-sm font-medium text-content">
{t('settings.ai.managedSourceLabel')}
@@ -265,6 +331,34 @@ export function ProviderModelPickerDialog({
<p className="text-xs leading-relaxed text-content-muted">
{t('settings.ai.routing.managedDesc')}
</p>
+ {loading ? (
+ <NativeSelect disabled className="mt-1 w-full cursor-wait opacity-60">
+ <option>{t('settings.ai.loadingModels', 'Loading models…')}</option>
+ </NativeSelect>
+ ) : catalog.length > 0 ? (
+ <NativeSelect
+ aria-label={t('settings.ai.modelLabel')}
+ data-testid="model-picker-managed-select"
+ value={model}
+ onChange={event => setModel(event.target.value)}
+ className="mt-1 w-full">
+ {/* Always present, unlike ModelEntryField's empty option, so a
+ pinned model can be cleared back to automatic routing. */}
+ <option value="">
+ {t('settings.ai.picker.managedAutomatic', 'Automatic (recommended)')}
+ </option>
+ {catalog.map(candidate => (
+ <option key={candidate.id} value={candidate.id}>
+ {managedOptionLabel(candidate)}
+ </option>
+ ))}
+ </NativeSelect>
+ ) : null}
+ {catalogError ? (
+ <Alert variant="destructive" className="font-mono text-xs break-all">
+ {catalogError}
+ </Alert>
+ ) : null}
</div>
) : source?.kind === 'cloud' ? (
<ModelEntryField
diff --git a/app/src/services/api/aiSettingsApi.ts b/app/src/services/api/aiSettingsApi.ts
index 6c052802e9..e71bffcfb9 100644
--- a/app/src/services/api/aiSettingsApi.ts
+++ b/app/src/services/api/aiSettingsApi.ts
@@ -118,6 +118,11 @@ export interface ModelInfo {
id: string;
owned_by?: string | null;
context_window?: number | null;
+ /** Human-readable name; only the managed catalog listing supplies one. */
+ display_name?: string | null;
+ /** Charged price in USD per 1M tokens, when the listing publishes it. */
+ input_per_1m?: number | null;
+ output_per_1m?: number | null;
}
interface ProviderModelTestResult {
diff --git a/src/openhuman/inference/provider/ops/models.rs b/src/openhuman/inference/provider/ops/models.rs
index 51417d711c..ec69d282a5 100644
--- a/src/openhuman/inference/provider/ops/models.rs
+++ b/src/openhuman/inference/provider/ops/models.rs
@@ -14,6 +14,15 @@ pub struct ModelInfo {
pub owned_by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub context_window: Option<u64>,
+ /// Human-readable name when the listing supplies one (the managed
+ /// `?catalog=` listing does; a bare OpenAI-compatible `/models` does not).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub display_name: Option<String>,
+ /// Charged price in USD per 1M tokens, when the listing publishes it.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub input_per_1m: Option<f64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub output_per_1m: Option<f64>,
}
/// Resolve the API key used to probe a provider's `/models` endpoint.
@@ -113,6 +122,44 @@ pub async fn list_configured_models_from_config(
);
use crate::openhuman::config::schema::cloud_providers::AuthStyle;
+
+ // Managed backend (`openhuman`) needs a different URL *and* a different
+ // credential than every BYOK provider above, so neither `entry.endpoint`
+ // nor `lookup_key_for_slug` is usable here:
+ //
+ // * the seeded entry's endpoint is the *chat* base
+ // (`https://api.openhuman.ai/v1`), so `{endpoint}/models` would probe
+ // the wrong host entirely — the hosted API is resolved by
+ // `effective_backend_api_url`, which also ignores an `api_url`
+ // override pointing at a local/third-party inference host.
+ // * the session JWT lives in the `app-session` auth profile, not
+ // `provider:openhuman`, so `lookup_key_for_slug` returns "" and the
+ // request would go out unauthenticated (401).
+ //
+ // `?catalog=openrouter` is required: without it the backend returns only
+ // the curated tier list (chat-v1, reasoning-v1, ...), which is deliberately
+ // byte-identical to the legacy payload. The catalog listing is gated
+ // server-side by OPENROUTER_PASSTHROUGH_ENABLED and returns an empty set
+ // when the passthrough is off, so this degrades to "no models" rather than
+ // an error on a backend that has not enabled it.
+ let mut managed_token = String::new();
+ if entry.auth_style == AuthStyle::OpenhumanJwt {
+ managed_token =
+ crate::openhuman::security::credentials::session_support::require_live_session_token(
+ config,
+ )?;
+ let base = crate::api::config::effective_backend_api_url(&config.api_url);
+ models_url = append_query_param(
+ &crate::api::config::api_url(&base, "/openai/v1/models"),
+ "catalog",
+ "openrouter",
+ );
+ log::debug!(
+ "[providers][list_models] managed catalog url={}",
+ models_url
+ );
+ }
+
if is_openrouter_provider(&entry) {
validate_openrouter_api_key(&client, &routing.endpoint, &api_key).await?;
}
@@ -144,8 +191,16 @@ pub async fn list_configured_models_from_config(
r
}
AuthStyle::OpenhumanJwt => {
- if !api_key.is_empty() {
- request.header("Authorization", format!("Bearer {}", api_key))
+ // Prefer the live session JWT resolved above; fall back to a
+ // provider-scoped key so a self-hosted entry that stores one still
+ // authenticates.
+ let token = if !managed_token.is_empty() {
+ managed_token.as_str()
+ } else {
+ api_key.as_str()
+ };
+ if !token.is_empty() {
+ request.header("Authorization", format!("Bearer {}", token))
} else {
request
}
@@ -427,6 +482,9 @@ pub fn merge_openai_codex_model_hints(models: &mut Vec<ModelInfo>) {
id: (*id).to_string(),
owned_by: Some("openai-codex".to_string()),
context_window: None,
+ display_name: None,
+ input_per_1m: None,
+ output_per_1m: None,
});
}
}
@@ -469,6 +527,9 @@ fn model_info_from_catalog_item(item: &serde_json::Value) -> Option<ModelInfo> {
id: id.to_string(),
owned_by: None,
context_window: None,
+ display_name: None,
+ input_per_1m: None,
+ output_per_1m: None,
});
}
@@ -490,10 +551,29 @@ fn model_info_from_catalog_item(item: &serde_json::Value) -> Option<ModelInfo> {
.or_else(|| item.get("context_window"))
.or_else(|| item.get("max_context_window"))
.and_then(|v| v.as_u64());
+ let display_name = item
+ .get("display_name")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(|s| s.to_string());
+ // `pricing` is already the CHARGED price per 1M tokens on the managed
+ // catalog listing, so it can be surfaced verbatim — no margin math here.
+ let pricing = item.get("pricing");
+ let price = |key: &str| -> Option<f64> {
+ pricing
+ .and_then(|p| p.get(key))
+ .and_then(|v| v.as_f64())
+ .filter(|n| n.is_finite() && *n >= 0.0)
+ };
Some(ModelInfo {
id,
owned_by,
context_window,
+ display_name,
+ input_per_1m: price("inputPer1M"),
+ output_per_1m: price("outputPer1M"),
})
}
diff --git a/src/openhuman/inference/provider/ops_tests_part_02_tests.rs b/src/openhuman/inference/provider/ops_tests_part_02_tests.rs
index 1dd7ec7217..a1658bef43 100644
--- a/src/openhuman/inference/provider/ops_tests_part_02_tests.rs
+++ b/src/openhuman/inference/provider/ops_tests_part_02_tests.rs
@@ -198,6 +198,9 @@ fn openai_codex_model_hints_are_merged_without_duplicates() {
id: "gpt-5.4".to_string(),
owned_by: Some("openai-codex".to_string()),
context_window: Some(128000),
+ display_name: None,
+ input_per_1m: None,
+ output_per_1m: None,
}];
merge_openai_codex_model_hints(&mut models);
diff --git a/src/openhuman/platform/cost/route.rs b/src/openhuman/platform/cost/route.rs
index 121ac03fdb..91031e0728 100644
--- a/src/openhuman/platform/cost/route.rs
+++ b/src/openhuman/platform/cost/route.rs
@@ -68,13 +68,33 @@ const MANAGED_MODEL_SLUGS: &[&str] = &[
/// path is untouched by this classification.
pub fn route_for_model(model: &str) -> CostRoute {
let normalized = normalize_model_id(model);
- if MANAGED_MODEL_SLUGS.contains(&normalized.as_str()) {
+ if MANAGED_MODEL_SLUGS.contains(&normalized.as_str()) || is_managed_passthrough_id(&normalized)
+ {
CostRoute::Managed
} else {
CostRoute::Byok
}
}
+/// `openrouter/<author>/<slug>` ids served by the managed backend's OpenRouter
+/// passthrough (`OPENROUTER_PASSTHROUGH_ENABLED`).
+///
+/// These are **managed** spend even though they are not tier slugs: the request
+/// goes to our backend, is billed against managed credits, and never touches a
+/// user-held key. Without this they fell to the `Byok` default and silently
+/// stopped counting toward the local managed cap — the same failure the
+/// `hint:` / `openhuman/` decoration stripping in [`normalize_model_id`] exists
+/// to prevent, reached by a different route.
+///
+/// A BYOK OpenRouter provider addresses models by their bare upstream slug
+/// (`deepseek/deepseek-v4-flash`), never with this `openrouter/` qualifier, so
+/// the two cannot be confused.
+fn is_managed_passthrough_id(normalized: &str) -> bool {
+ normalized
+ .strip_prefix("openrouter/")
+ .is_some_and(|rest| rest.split('/').filter(|seg| !seg.is_empty()).count() == 2)
+}
+
/// Lower-case, trim, and strip the decorations a model id can pick up on its
/// way to a cost record: a `hint:` prefix from the tier-resolution helpers and
/// an `openhuman/` provider qualifier.
diff --git a/src/openhuman/platform/cost/route_tests.rs b/src/openhuman/platform/cost/route_tests.rs
index 0d0ea2609f..8b278c8f57 100644
--- a/src/openhuman/platform/cost/route_tests.rs
+++ b/src/openhuman/platform/cost/route_tests.rs
@@ -123,3 +123,38 @@ fn only_managed_counts_toward_budget() {
assert!(CostRoute::Managed.counts_toward_budget());
assert!(!CostRoute::Byok.counts_toward_budget());
}
+
+/// The managed backend's OpenRouter passthrough bills managed credits, so its
+/// `openrouter/<author>/<slug>` ids must count toward the local managed cap.
+/// They are not tier slugs, so before this they fell to the `Byok` default and
+/// managed spend silently stopped being counted.
+#[test]
+fn managed_openrouter_passthrough_ids_are_managed() {
+ for model in [
+ "openrouter/deepseek/deepseek-v4-flash",
+ "openrouter/anthropic/claude-sonnet-4.5",
+ // decorations must normalize away first, in either order
+ "hint:openrouter/deepseek/deepseek-v4-flash",
+ "openhuman/openrouter/deepseek/deepseek-v4-flash",
+ " OpenRouter/DeepSeek/DeepSeek-V4-Flash ",
+ ] {
+ assert_eq!(route_for_model(model), CostRoute::Managed, "{model}");
+ }
+}
+
+/// A BYOK OpenRouter provider addresses models by their bare upstream slug, so
+/// those must stay BYOK. Only the `openrouter/` qualifier means managed
+/// passthrough, and only with exactly `<author>/<slug>` after it.
+#[test]
+fn byok_openrouter_slugs_and_malformed_passthrough_ids_stay_byok() {
+ for model in [
+ // bare upstream slug — what a BYOK openrouter provider sends
+ "deepseek/deepseek-v4-flash",
+ // wrong segment count after the qualifier
+ "openrouter/deepseek",
+ "openrouter/",
+ "openrouter/a/b/c",
+ ] {
+ assert_eq!(route_for_model(model), CostRoute::Byok, "{model}");
+ }
+}