Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: model select + paywall changes, authoritative frontend models, model router (#4077)
Eric Hayesfe15536d1acc
diff --git a/infra/packages/shared/src/ai_tools.ts b/infra/packages/shared/src/ai_tools.tsindex b04a62a075..fa70f81c14 100644--- a/infra/packages/shared/src/ai_tools.ts+++ b/infra/packages/shared/src/ai_tools.ts@@ -1,6 +1,6 @@import * as aws from '@pulumi/aws';import * as pulumi from '@pulumi/pulumi';-import { getServiceUrl, ServiceUrl, stack } from '../../shared';+import { config, getServiceUrl, ServiceUrl, stack } from '../../shared';/*** Infrastructure wiring required by services that host the `ai_tools` crate@@ -104,6 +104,14 @@ export function getAiToolsInfra(): AiToolsInfra {.getSecretVersionOutput({ secretId: `github-client-secret-${stack}` }).apply((secret) => secret.secretString);+ const OPENAI_API_KEY = aws.secretsmanager+ .getSecretVersionOutput({ secretId: config.require('openai_api_key') })+ .apply((secret) => secret.secretString);++ const ANTHROPIC_API_KEY = aws.secretsmanager+ .getSecretVersionOutput({ secretId: config.require('anthropic_api_key') })+ .apply((secret) => secret.secretString);+const envVars: AiToolsInfra['envVars'] = [{name: 'INTERNAL_API_SECRET_KEY',@@ -178,6 +186,14 @@ export function getAiToolsInfra(): AiToolsInfra {name: 'GITHUB_CLIENT_ID',value: pulumi.interpolate`${GITHUB_CLIENT_ID}`,},+ {+ name: 'OPENAI_API_KEY',+ value: pulumi.interpolate`${OPENAI_API_KEY}`,+ },+ {+ name: 'ANTHROPIC_API_KEY',+ value: pulumi.interpolate`${ANTHROPIC_API_KEY}`,+ },];return {diff --git a/infra/stacks/agent-schedule-service/index.ts b/infra/stacks/agent-schedule-service/index.tsindex 8d15f424cf..74eda4e537 100644--- a/infra/stacks/agent-schedule-service/index.ts+++ b/infra/stacks/agent-schedule-service/index.ts@@ -47,24 +47,12 @@ const OPEN_ROUTER_API_KEY = aws.secretsmanager}).apply((secret) => secret.secretString);-const OPENAI_API_KEY = aws.secretsmanager- .getSecretVersionOutput({- secretId: config.require('openai_api_key'),- })- .apply((secret) => secret.secretString);-const XAI_API_KEY = aws.secretsmanager.getSecretVersionOutput({secretId: config.require('xai-api-key'),}).apply((secret) => secret.secretString);-const ANTHROPIC_API_KEY = aws.secretsmanager- .getSecretVersionOutput({- secretId: config.require('anthropic_api_key'),- })- .apply((secret) => secret.secretString);-const PERPLEXITY_API_KEY = aws.secretsmanager.getSecretVersionOutput({secretId: config.require('perplexity-api-key'),@@ -168,14 +156,6 @@ const service = new AgentScheduleService(`agent-schedule-service-${stack}`, {name: 'OPEN_ROUTER_API_KEY',value: pulumi.interpolate`${OPEN_ROUTER_API_KEY}`,},- {- name: 'OPENAI_API_KEY',- value: pulumi.interpolate`${OPENAI_API_KEY}`,- },- {- name: 'ANTHROPIC_API_KEY',- value: pulumi.interpolate`${ANTHROPIC_API_KEY}`,- },{name: 'XAI_API_KEY',value: pulumi.interpolate`${XAI_API_KEY}`,diff --git a/infra/stacks/document-cognition-service/index.ts b/infra/stacks/document-cognition-service/index.tsindex 8fd85edf9b..be5fb6f951 100644--- a/infra/stacks/document-cognition-service/index.ts+++ b/infra/stacks/document-cognition-service/index.ts@@ -51,25 +51,12 @@ const OPEN_ROUTER_API_KEY = aws.secretsmanager}).apply((secret) => secret.secretString);-const OPENAI_API_KEY = aws.secretsmanager- .getSecretVersionOutput({- secretId: config.get('openai_api_key') ?? '',- })- .apply((secret) => secret.secretString);-const XAI_API_KEY = aws.secretsmanager.getSecretVersionOutput({secretId: config.get('xai-api-key') ?? '',}).apply((secret) => secret.secretString);-const ANTHROPIC_API_KEY = aws.secretsmanager- .getSecretVersionOutput({- secretId: config.get('anthropic_api_key') ?? '',- })- .apply((secret) => {- return secret.secretString;- });const GCP_SERVICE_ACCOUNT = aws.secretsmanager.getSecretVersionOutput({secretId: config.get('gcp_service_account') ?? '',@@ -219,14 +206,6 @@ const documentCognitionService = new DocumentCognitionService(name: 'OPEN_ROUTER_API_KEY',value: pulumi.interpolate`${OPEN_ROUTER_API_KEY}`,},- {- name: 'OPENAI_API_KEY',- value: pulumi.interpolate`${OPENAI_API_KEY}`,- },- {- name: 'ANTHROPIC_API_KEY',- value: pulumi.interpolate`${ANTHROPIC_API_KEY}`,- },{name: 'XAI_API_KEY',value: pulumi.interpolate`${XAI_API_KEY}`,diff --git a/infra/stacks/mcp-server/Pulumi.dev.yaml b/infra/stacks/mcp-server/Pulumi.dev.yamlindex 33812ed4e4..99ca540e6f 100644--- a/infra/stacks/mcp-server/Pulumi.dev.yaml+++ b/infra/stacks/mcp-server/Pulumi.dev.yaml@@ -15,4 +15,5 @@ config:mcp-server:macro_db_secret_key: macro-db-devmcp-server:sync_service_auth_key: sync-service-key-devmcp-server:anthropic_api_key: anthropic-api-key-dev+ mcp-server:openai_api_key: openai-keydatadog:validate: "false"diff --git a/infra/stacks/mcp-server/Pulumi.prod.yaml b/infra/stacks/mcp-server/Pulumi.prod.yamlindex 6fec5a5cac..f8e159d771 100644--- a/infra/stacks/mcp-server/Pulumi.prod.yaml+++ b/infra/stacks/mcp-server/Pulumi.prod.yaml@@ -15,4 +15,5 @@ config:mcp-server:macro_db_secret_key: macro-db-prodmcp-server:sync_service_auth_key: sync-service-key-prodmcp-server:anthropic_api_key: anthropic-api-key+ mcp-server:openai_api_key: openai-keydatadog:validate: "false"diff --git a/infra/stacks/mcp-server/index.ts b/infra/stacks/mcp-server/index.tsindex 46c3fe0d96..e46c8ddbc2 100644--- a/infra/stacks/mcp-server/index.ts+++ b/infra/stacks/mcp-server/index.ts@@ -66,16 +66,6 @@ const MACRO_CACHE = aws.secretsmanager}).apply((secret) => secret.secretString);-const anthropicApiKeySecretName = config.require('anthropic_api_key');-const ANTHROPIC_API_KEY = aws.secretsmanager- .getSecretVersionOutput({- secretId: anthropicApiKeySecretName,- })- .apply((secret) => secret.secretString);-const anthropicApiKeyArn: pulumi.Output<string> = aws.secretsmanager- .getSecretVersionOutput({ secretId: anthropicApiKeySecretName })- .apply((secret) => secret.arn);-const MACRO_API_TOKENS = getMacroApiToken();// ── AI tools infra ───────────────────────────────────────────────────────────@@ -114,7 +104,6 @@ const mcpServer = new McpServer(`mcp-server-${stack}`, {fusionauthApiKeyArn,googleClientSecretArn,MACRO_API_TOKENS.macroApiTokenPublicKeyArn,- anthropicApiKeyArn,...aiTools.secretArns,],queueArns: [...aiTools.queueArns],@@ -192,10 +181,6 @@ const mcpServer = new McpServer(`mcp-server-${stack}`, {name: 'MACRO_API_TOKEN_PUBLIC_KEY',value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenPublicKey}`,},- {- name: 'ANTHROPIC_API_KEY',- value: pulumi.interpolate`${ANTHROPIC_API_KEY}`,- },// Datadog{name: 'DD_SERVICE',diff --git a/js/app/packages/app/component/SoupChatInput.tsx b/js/app/packages/app/component/SoupChatInput.tsxindex 6f6c71f7db..c70b463108 100644--- a/js/app/packages/app/component/SoupChatInput.tsx+++ b/js/app/packages/app/component/SoupChatInput.tsx@@ -1,6 +1,5 @@import { useAnalytics } from '@app/component/analytics-context';import { useSoup } from '@app/component/next-soup/soup-context';-import { useHasPaidAccess } from '@core/auth/license';import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';import {@@ -27,7 +26,6 @@ function SoupChatInputInner() {const splitPanelContext = useSplitPanelOrThrow();const soup = useSoup();const input = useChatInputContext();- const hasPaid = useHasPaidAccess();const { getAttachmentFromMention } = useGetChatAttachmentInfo();@@ -64,12 +62,6 @@ function SoupChatInputInner() {const renameMutation = createRenameDssEntityMutation();const handleSend = async (request: ChatSendInput) => {- if (!hasPaid()) {- const { showPaywall } = usePaywallState();- showPaywall(PaywallKey.CHAT_LIMIT);- return;- }-const backgroundSend = request.metaKey;// Create a new persistent chatdiff --git a/js/app/packages/app/component/home/home.tsx b/js/app/packages/app/component/home/home.tsxindex b0f56218fe..3f4dcf2787 100644--- a/js/app/packages/app/component/home/home.tsx+++ b/js/app/packages/app/component/home/home.tsx@@ -1,7 +1,6 @@import { useAnalytics } from '@app/component/analytics-context';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';import { ShowFeatureFlag } from '@app/lib/analytics/posthog';-import { useHasPaidAccess } from '@core/auth';import { DragDropWrapper } from '@core/component/AI/component/DragDrop';import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';@@ -147,7 +146,6 @@ const HomeChatInput = () => {const analytics = useAnalytics();const splitPanelContext = useSplitPanelOrThrow();const input = useChatInputContext();- const hasPaid = useHasPaidAccess();const { getAttachmentFromMention } = useGetChatAttachmentInfo();@@ -176,12 +174,6 @@ const HomeChatInput = () => {const renameMutation = createRenameDssEntityMutation();const handleSend = async (request: ChatSendInput) => {- if (!hasPaid()) {- const { showPaywall } = usePaywallState();- showPaywall(PaywallKey.CHAT_LIMIT);- return;- }-const backgroundSend = request.metaKey;// Create a new persistent chatdiff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsxindex 2aca7e5098..fad304192d 100644--- a/js/app/packages/block-chat/component/Chat.tsx+++ b/js/app/packages/block-chat/component/Chat.tsx@@ -23,6 +23,7 @@ import { useGetChatAttachmentInfo } from '@core/component/AI/signal/attachment';import { getPendingSend } from '@core/component/AI/signal/pendingSend';import { registerToolHandler } from '@core/component/AI/signal/tool';import { deriveChatName } from '@core/component/AI/util/deriveName';+import { parseModel } from '@core/component/AI/util/parse';import {getChatInputStoredState,type StoredStuff,@@ -53,10 +54,15 @@ export function Chat(props: { data: ChatData }) {const loadedState = getChatInputStoredState(props.data.chat.id);const { showPaywall } = usePaywallState();+ // Seed the selector from the chat's stored model, then the local draft, then+ // the default. The chat input reconciles to an available model if the user+ // isn't entitled to this one.+ const initialModel = parseModel(props.data.chat.model) ?? loadedState.model;+return (<ChatInputProviderinitialAttachments={loadedState.attachments}- model={loadedState.model}+ model={initialModel}><ChatProviderchatId={props.data.chat.id}diff --git a/js/app/packages/block-chat/definition.ts b/js/app/packages/block-chat/definition.tsindex d1c11e6590..db2597d5e0 100644--- a/js/app/packages/block-chat/definition.ts+++ b/js/app/packages/block-chat/definition.ts@@ -1,6 +1,6 @@import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';+import { Model } from '@core/component/AI/constant/model';import { cognitionApiServiceClient } from '@service-cognition/client';-import { AgentModel } from '@service-cognition/generated/schemas';import type { Entity } from '@service-cognition/generated/schemas/entity';import type { DocumentMetadata } from '@service-storage/generated/schemas/documentMetadata';import { ok } from 'neverthrow';@@ -38,7 +38,7 @@ export const definition = defineBlock({return ok({...chat,- allModels: Object.values(AgentModel),+ allModels: Object.values(Model),documentMetadata: {documentId: chat.chat.id,documentName: chat.chat.name,diff --git a/js/app/packages/core/component/AI/component/input/ChatInput.tsx b/js/app/packages/core/component/AI/component/input/ChatInput.tsxindex 4035c1105e..b4d0390d0e 100644--- a/js/app/packages/core/component/AI/component/input/ChatInput.tsx+++ b/js/app/packages/core/component/AI/component/input/ChatInput.tsx@@ -1,10 +1,12 @@import { useAnalytics } from '@app/component/analytics-context';import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';+import { ModelSelector } from '@core/component/AI/component/input/ModelSelector';import { useChatInputContext } from '@core/component/AI/context';import type { Model, ToolSet } from '@core/component/AI/types';import type { EditorConfigBuilder } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';import { toast } from '@core/component/Toast/Toast';+import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';import { TOKENS } from '@core/hotkey/tokens';import { isMobile } from '@core/mobile/isMobile';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';@@ -12,6 +14,9 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import { useTouchOutsideToDismissKeyboard } from '@core/mobile/useTouchOutsideToDismissKeyboard';import { handleFileFolderDrop } from '@core/util/upload';import PaperclipIcon from '@phosphor/paperclip.svg';+import { useModelsQuery } from '@queries/chat';+import { queryReadyGate } from '@queries/gate';+import { createElementSize } from '@solid-primitives/resize-observer';import { createCallback } from '@solid-primitives/rootless';import { Button, cn, Surface, SendButton as UiSendButton } from '@ui';import { createEffect, createMemo, createSignal, Show } from 'solid-js';@@ -44,9 +49,61 @@ export function ChatInput(props: ChatInputComponentProps) {const attachments = input.attachments;const model = input.model;const generating = input.isGenerating;+ const { showPaywall } = usePaywallState();++ // Which models this user may use (free → Haiku; professional → all).+ // Gate on the query so reading `.data` doesn't trip Suspense while loading;+ // an empty list until ready is fine (the effect below no-ops on `[]`).+ const modelsQuery = useModelsQuery();+ const modelOptions = createMemo(() => {+ if (!queryReadyGate(modelsQuery)) return [];+ return modelsQuery.data.models.map((m) => ({+ id: m.id as Model,+ available: m.available,+ }));+ });++ // If the selected model isn't available to this user, fall back to the+ // first available one so we never send a model that would 403.+ createEffect(() => {+ const options = modelOptions();+ if (options.length === 0) return;+ if (options.some((o) => o.id === model() && o.available)) return;+ const firstAvailable = options.find((o) => o.available);+ if (firstAvailable) input.setModel(firstAvailable.id);+ });let containerRef!: HTMLDivElement;useTouchOutsideToDismissKeyboard(() => containerRef);++ // The model selector lives inside the input, directly left of the send+ // button, and collapses to just the provider icon when the line is too tight+ // (mobile, a small split). Rather than guess a viewport breakpoint, we test+ // actual fit: an invisible, always-expanded probe of the control row is+ // measured against the available line width. The probe keeps full width+ // whatever the visible selector shows, so collapsing can't change the+ // measurement and oscillate, and it's content-driven (reacts to real+ // text/font/zoom). Both are ResizeObserver-backed, so it stays live on resize.+ const [lineEl, setLineEl] = createSignal<HTMLElement>();+ const [probeEl, setProbeEl] = createSignal<HTMLElement>();+ const lineSize = createElementSize(lineEl);+ const probeSize = createElementSize(probeEl);+ const compactSelector = () =>+ !isTallVariant() &&+ probeSize.width != null &&+ lineSize.width != null &&+ probeSize.width > lineSize.width;+ // Comfortable typing room to keep for the editor when deciding the selector+ // fits. The selector collapses while the body still has at least this much+ // room, so the body never gets squeezed into wrapping to make space for it.+ const MIN_EDITOR_WIDTH = 180;++ // Reserve space on the single-line layout so flowing text never slides under+ // the right-hand controls (whose width changes with the selector's state).+ const [rightControlsEl, setRightControlsEl] = createSignal<HTMLElement>();+ const rightControlsSize = createElementSize(rightControlsEl);+ const rightControlsInset = () => (rightControlsSize.width ?? 44) + 10;+const toolsetSignal = createSignal<ToolSet>({ type: 'all' });const { hasConsent, requestConsent, ConsentDialog } = useAiDataConsentGate();@@ -159,21 +216,30 @@ export function ChatInput(props: ChatInputComponentProps) {</Button>);+ // On mobile the send button is hidden while the input is empty. Collapse it+ // (display:none) rather than just fading it, so it doesn't reserve width and+ // offset the model selector from the right edge.+ const sendHidden = () => isMobile() && isEmptyInput();const SendButton = () => (<UiSendButtontooltip={'Ask AI'}shortcut="enter"tooltipPlacement="top"disabled={!canSendMessage()}- hidden={isMobile() && isEmptyInput()}- onClick={() =>- sendMessage(isTouchDevice() ? { modelOverride: 'smart' } : undefined)- }+ class={sendHidden() ? 'hidden' : undefined}+ onClick={() => sendMessage()}/>);const RightControls = () => (- <div class="shrink-0">+ <div ref={setRightControlsEl} class="flex shrink-0 items-center gap-1">+ <ModelSelector+ selectedModel={model()}+ models={modelOptions()}+ onSelect={(m) => input.setModel(m)}+ onLocked={() => showPaywall(PaywallKey.MODEL_LIMIT)}+ compact={compactSelector()}+ /><Show when={generating() && props.onStop} fallback={<SendButton />}><StopButton /></Show>@@ -199,86 +265,122 @@ export function ChatInput(props: ChatInputComponentProps) {const isTallVariant = createMemo(() => props.variant === 'tall');return (- <Surface active={isFocused()} class="rounded-xl" depth={2} solid>- <div- onFocusOut={(e) => {- const next = e.relatedTarget as Node | null;- if (next && containerRef.contains(next)) return;- setIsFocused(false);- }}- onFocusIn={() => setIsFocused(true)}- class="relative flex flex-col"- ref={containerRef}- id="chat-input"- >- <Show when={!isTallVariant()}>- <Attachments />- </Show>-- <Show when={showAttachMenu()}>- <ChatAttachMenu- anchorRef={attachMenuAnchorRef()!}- close={() => setShowAttachMenu(false)}- containerRef={containerRef}- open={showAttachMenu()}- onAttach={(attachment) => {- analytics.track('ai_attachment_add');- attachments.addAttachment(attachment);- }}- />- </Show>-+ <div class="relative">+ <Surface active={isFocused()} class="rounded-xl" depth={2} solid><div- class={cn('relative px-2 py-1.5', {- 'flex flex-col px-3 py-2': isTallVariant(),- })}+ onFocusOut={(e) => {+ const next = e.relatedTarget as Node | null;+ if (next && containerRef.contains(next)) return;+ setIsFocused(false);+ }}+ onFocusIn={() => setIsFocused(true)}+ class="relative flex flex-col"+ ref={containerRef}+ id="chat-input">- <div- id="chat-input-text-area"- class={cn('text-sm sm:text-sm text-ink')}- classList={{- 'pl-8': !isMultiline() && !isTallVariant(),- 'pr-12': !isMultiline() && !isTallVariant(),- 'px-0 pb-8': isMultiline() && !isTallVariant(),- }}- ref={mdRef}- >- <MarkdownShell- config={props.editor}- placeholder="Ask AI, @mention anything"- initialValue={props.initialValue}- autofocus={- !isMobile() &&- !isTouchDevice() &&- props.autoFocusOnMount !== false- }+ <Show when={!isTallVariant()}>+ <Attachments />+ </Show>++ <Show when={showAttachMenu()}>+ <ChatAttachMenu+ anchorRef={attachMenuAnchorRef()!}+ close={() => setShowAttachMenu(false)}+ containerRef={containerRef}+ open={showAttachMenu()}+ onAttach={(attachment) => {+ analytics.track('ai_attachment_add');+ attachments.addAttachment(attachment);+ }}/>- <Show when={isTallVariant()}>- <div class="h-4" />- </Show>- <Show when={isTallVariant()}>- <Attachments />- </Show>- </div>+ </Show><div- class={cn('contents', {- 'flex justify-between items-center': isTallVariant(),+ ref={setLineEl}+ class={cn('relative px-2 py-1.5', {+ 'flex flex-col px-3 py-2': isTallVariant(),})}>- <div class={cn(!isTallVariant() && 'absolute left-2 bottom-1.5')}>- <LeftButton />+ {/* Invisible reference of the fully-expanded control row laid out+ inline (paperclip + min editor room + full selector + send). Its+ measured width is the space the expanded selector needs; when+ that exceeds the line, the visible selector collapses. */}+ <Show when={!isTallVariant()}>+ <div+ ref={setProbeEl}+ aria-hidden="true"+ inert+ class="pointer-events-none invisible absolute flex w-max items-center gap-1"+ >+ <div class="size-7.5 shrink-0" />+ <div+ class="shrink-0"+ style={{ width: `${MIN_EDITOR_WIDTH}px` }}+ />+ <ModelSelector+ selectedModel={model()}+ models={modelOptions()}+ onSelect={() => {}}+ />+ <div class="size-7.5 shrink-0" />+ </div>+ </Show>+ <div+ id="chat-input-text-area"+ class={cn('text-sm sm:text-sm text-ink')}+ classList={{+ 'pl-8': !isMultiline() && !isTallVariant(),+ 'px-0 pb-8': isMultiline() && !isTallVariant(),+ // While empty, the only thing rendered is the placeholder.+ // `white-space` inherits, so this keeps it on one line (clipped)+ // instead of wrapping into the single-line height. Typing clears+ // it, restoring normal wrapping / grow-to-multiline.+ 'overflow-hidden whitespace-nowrap': isEmptyInput(),+ }}+ style={+ !isMultiline() && !isTallVariant()+ ? { 'padding-right': `${rightControlsInset()}px` }+ : undefined+ }+ ref={mdRef}+ >+ <MarkdownShell+ config={props.editor}+ placeholder="Ask AI, @mention anything"+ initialValue={props.initialValue}+ autofocus={+ !isMobile() &&+ !isTouchDevice() &&+ props.autoFocusOnMount !== false+ }+ />+ <Show when={isTallVariant()}>+ <div class="h-4" />+ </Show>+ <Show when={isTallVariant()}>+ <Attachments />+ </Show></div><div- class={cn(!isTallVariant() && 'absolute right-1.5 bottom-1.5')}+ class={cn('contents', {+ 'flex justify-between items-center': isTallVariant(),+ })}>- <RightControls />+ <div class={cn(!isTallVariant() && 'absolute left-2 bottom-1.5')}>+ <LeftButton />+ </div>++ <div+ class={cn(!isTallVariant() && 'absolute right-1.5 bottom-1.5')}+ >+ <RightControls />+ </div></div></div></div>- </div>- <ConsentDialog />- </Surface>+ <ConsentDialog />+ </Surface>+ </div>);}diff --git a/js/app/packages/core/component/AI/component/input/ModelSelector.tsx b/js/app/packages/core/component/AI/component/input/ModelSelector.tsxindex 2871d92966..d0d3691246 100644--- a/js/app/packages/core/component/AI/component/input/ModelSelector.tsx+++ b/js/app/packages/core/component/AI/component/input/ModelSelector.tsx@@ -6,47 +6,76 @@ import {} from '@core/component/AI/constant';import type { TModel } from '@core/component/AI/types';import CaretDown from '@phosphor-icons/core/regular/caret-down.svg?component-solid';-import { Dropdown } from '@ui';-import type { Accessor } from 'solid-js';-import { For } from 'solid-js';+import LockIcon from '@phosphor-icons/core/regular/lock-simple.svg?component-solid';+import { cn, Dropdown } from '@ui';+import { For, Show } from 'solid-js';import { Dynamic } from 'solid-js/web';+/** A model and whether the current user may select it. */+export type ModelOption = { id: TModel; available: boolean };+type ModelSelectorProps = {selectedModel?: TModel;- availableModels?: Accessor<TModel[]>;+ /** Per-model availability. Defaults to all models available. */+ models?: ModelOption[];onSelect: (model: TModel) => void;+ /** Called when an unavailable model is clicked (e.g. to open the paywall). */+ onLocked?: (model: TModel) => void;+ /** Collapse the trigger to just the provider icon (narrow inputs). */+ compact?: boolean;};+const ALL_AVAILABLE: ModelOption[] = (Object.values(Model) as TModel[]).map(+ (id) => ({ id, available: true })+);+export function ModelSelector(props: ModelSelectorProps) {const model = () => props.selectedModel ?? DEFAULT_MODEL;+ const options = () =>+ props.models && props.models.length > 0 ? props.models : ALL_AVAILABLE;- const setSelected = (selected: TModel) => {- props.onSelect(selected);+ const handleSelect = (option: ModelOption) => {+ if (option.available) {+ props.onSelect(option.id);+ } else {+ props.onLocked?.(option.id);+ }};return (- <Dropdown>- <Dropdown.Trigger variant="ghost">+ <Dropdown placement="top-end">+ <Dropdown.Trigger+ variant="ghost"+ size={props.compact ? 'icon-sm' : 'sm'}+ class={cn('rounded-lg text-xs', !props.compact && 'gap-1.5')}+ label={props.compact ? MODEL_PRETTYNAME[model()] : undefined}+ ><Dynamic component={MODEL_PROVIDER_ICON[model()]} />- {MODEL_PRETTYNAME[model()]}- <CaretDown />+ <Show when={!props.compact}>+ {MODEL_PRETTYNAME[model()]}+ <CaretDown />+ </Show></Dropdown.Trigger><Dropdown.Content><Dropdown.Group>- <For- each={- props.availableModels- ? props.availableModels()- : (Object.values(Model) as Model[])- }- >- {(m) => (- <Dropdown.Item onSelect={() => setSelected(m)}>+ <For each={options()}>+ {(option) => (+ // Unavailable items stay clickable (not Kobalte-disabled) so the+ // click can open the paywall; they're just visually dimmed.+ <Dropdown.Item+ class={cn('gap-2', !option.available && 'opacity-50')}+ onSelect={() => handleSelect(option)}+ ><Dynamic- component={MODEL_PROVIDER_ICON[m]}+ component={MODEL_PROVIDER_ICON[option.id]}class="size-4 shrink-0"/>- <span class="flex-1 truncate">{MODEL_PRETTYNAME[m]}</span>+ <span class="flex-1 truncate text-xs">+ {MODEL_PRETTYNAME[option.id]}+ </span>+ <Show when={!option.available}>+ <LockIcon class="size-3.5 shrink-0 text-ink-extra-muted" />+ </Show></Dropdown.Item>)}</For>diff --git a/js/app/packages/core/component/AI/component/input/buildRequest.ts b/js/app/packages/core/component/AI/component/input/buildRequest.tsindex 6a3885d02e..19e5918ecf 100644--- a/js/app/packages/core/component/AI/component/input/buildRequest.ts+++ b/js/app/packages/core/component/AI/component/input/buildRequest.ts@@ -30,16 +30,13 @@ export function useSendChatMessage() {attachments,toolset,}: ChatSendInput & { chatId?: string }): Promise<SendChatMessageResult> {- const modelInstructions = model ? `\nYou are ${model}` : '';- const additional = `${additionalInstructions()}${modelInstructions}`;-const response = await cognitionApiServiceClient.sendStreamChatMessage({content,model: model ?? DEFAULT_MODEL,chat_id: chatId,attachments: attachments.length > 0 ? attachments : undefined,toolset,- additional_instructions: additional,+ additional_instructions: additionalInstructions(),});if (isPaymentError(response)) {diff --git a/js/app/packages/core/component/AI/constant/model.ts b/js/app/packages/core/component/AI/constant/model.tsindex bbf6ce8938..b18f4b0235 100644--- a/js/app/packages/core/component/AI/constant/model.ts+++ b/js/app/packages/core/component/AI/constant/model.ts@@ -1,33 +1,46 @@import AnthropicIcon from '@core/component/AI/assets/anthropic.svg';import OpenAiIcon from '@core/component/AI/assets/openai.svg';-import type { TModel } from '@core/component/AI/types';-export { Model } from '@core/component/AI/types';+/**+ * Frontend-owned set of model ids. These are the provider api ids the backend+ * expects as plain strings — the backend `AgentModel` enum is intentionally not+ * exposed to the frontend. Reference these constants instead of hardcoding+ * strings.+ */+export const Model = {+ opus48: 'claude-opus-4-8',+ haiku45: 'claude-haiku-4-5',+ opus47: 'claude-opus-4-7',+ sonnet46: 'claude-sonnet-4-6',+ gpt55: 'gpt-5.5',+ gpt5Mini: 'gpt-5-mini',+} as const;++// `Model` is both a value (the const above) and a type (the union of api ids).+export type Model = (typeof Model)[keyof typeof Model];+/** Alias kept for existing call sites. */+export type TModel = Model;type ExhaustiveMap = {[K in TModel]: any;};export const MODEL_PRETTYNAME: ExhaustiveMap = {- smart: 'Smart',- fast: 'Fast',- opus4_7: 'Opus 4.7',- sonnet4_6: 'Sonnet 4.6',- haiku4_5: 'Haiku 4.5',- gpt5_5: 'GPT-5.5',- gpt5Mini: 'GPT-5 mini',- retired: 'Retired',+ 'claude-opus-4-8': 'Opus 4.8',+ 'claude-haiku-4-5': 'Haiku 4.5',+ 'claude-opus-4-7': 'Opus 4.7',+ 'claude-sonnet-4-6': 'Sonnet 4.6',+ 'gpt-5.5': 'GPT-5.5',+ 'gpt-5-mini': 'GPT-5 mini',} as const;export const MODEL_PROVIDER_ICON: ExhaustiveMap = {- smart: AnthropicIcon,- fast: AnthropicIcon,- opus4_7: AnthropicIcon,- sonnet4_6: AnthropicIcon,- haiku4_5: AnthropicIcon,- gpt5_5: OpenAiIcon,- gpt5Mini: OpenAiIcon,- retired: AnthropicIcon,+ 'claude-opus-4-8': AnthropicIcon,+ 'claude-haiku-4-5': AnthropicIcon,+ 'claude-opus-4-7': AnthropicIcon,+ 'claude-sonnet-4-6': AnthropicIcon,+ 'gpt-5.5': OpenAiIcon,+ 'gpt-5-mini': OpenAiIcon,};-export const DEFAULT_MODEL: TModel = 'smart';+export const DEFAULT_MODEL: TModel = Model.opus48;diff --git a/js/app/packages/core/component/AI/types/index.ts b/js/app/packages/core/component/AI/types/index.tsindex 15e7c66292..6ddebc505f 100644--- a/js/app/packages/core/component/AI/types/index.ts+++ b/js/app/packages/core/component/AI/types/index.ts@@ -1,8 +1,8 @@+export type { TModel } from '@core/component/AI/constant/model';+export { Model } from '@core/component/AI/constant/model';export type {- AgentModel as TModel,AssistantMessagePart,FileType,ToolSet,} from '@service-cognition/generated/schemas';-export { AgentModel as Model } from '@service-cognition/generated/schemas';export * from './attachment';diff --git a/js/app/packages/core/component/AI/util/parse.ts b/js/app/packages/core/component/AI/util/parse.tsindex f6a8280b9a..4aa271b105 100644--- a/js/app/packages/core/component/AI/util/parse.ts+++ b/js/app/packages/core/component/AI/util/parse.ts@@ -1,11 +1,10 @@-import { AgentModel } from '@service-cognition/generated/schemas';-import type { TModel } from '../types';+import { Model, type TModel } from '../constant/model';export const parseModel = (value: string | null | undefined): TModel | undefined => {if (!value) return undefined;- const values = Object.values(AgentModel) as string[];+ const values = Object.values(Model) as string[];if (values.includes(value)) return value as TModel;return undefined;};diff --git a/js/app/packages/core/util/create.ts b/js/app/packages/core/util/create.tsindex 3865e1979c..dade3ef8f5 100644--- a/js/app/packages/core/util/create.ts+++ b/js/app/packages/core/util/create.ts@@ -1,14 +1,8 @@import { DEFAULT_CHAT_NAME } from '@block-chat/definition';import type { CodeFileExtension } from '@block-code/util/languageSupport';import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';-import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property/constants';-import {- authKeys,- invalidateUserQuota,- type UserInfoData,-} from '@queries/auth';-import { queryClient } from '@queries/client';+import { invalidateUserQuota } from '@queries/auth';import { postNewHistoryItem } from '@queries/history/history';import { setPreviewOnCreate } from '@queries/preview/preview';import { refetchSoupEntity } from '@queries/soup/cache';@@ -281,17 +275,6 @@ export async function createCanvasFileFromJsonString(args: {export async function createChat(args?: CreateChatRequest) {const { showPaywall } = usePaywallState();- if (!isNativeMobilePlatform()) {- const userInfo = queryClient.getQueryData<UserInfoData>(- authKeys.userInfo.queryKey- );- const status = userInfo?.licenseStatus;- if (status !== 'trialing' && status !== 'active') {- showPaywall(PaywallKey.CHAT_LIMIT);- return { error: 'Upgrade required.' };- }- }-const maybeChat = await cognitionApiServiceClient.createChat(args ?? {});invalidateUserQuota();diff --git a/js/app/packages/queries/chat.ts b/js/app/packages/queries/chat.tsindex e045a50f3b..875fb4ac9f 100644--- a/js/app/packages/queries/chat.ts+++ b/js/app/packages/queries/chat.ts@@ -16,6 +16,16 @@ type ChatRenamedMessage = {name: string;};+/** The models the current user may use (free → Haiku; professional → all). */+export function useModelsQuery() {+ return useQuery(() => ({+ queryKey: ['chat', 'models'],+ queryFn: async () =>+ throwOnErr(async () => await cognitionApiServiceClient.getModels()),+ staleTime: CHAT_STALE_TIME,+ }));+}+export function useChatQuery(chatId: () => string | undefined) {return useQuery(() => {const id = chatId();diff --git a/js/app/packages/service-clients/service-cognition/client.ts b/js/app/packages/service-clients/service-cognition/client.tsindex f6e3095ed5..af1c6a957a 100644--- a/js/app/packages/service-clients/service-cognition/client.ts+++ b/js/app/packages/service-clients/service-cognition/client.ts@@ -19,6 +19,7 @@ import type { GetChatPermissionsResponse } from './generated/schemas/getChatPermimport type { GetChatResponse } from './generated/schemas/getChatResponse';import type { GetChatsForAttachmentResponse } from './generated/schemas/getChatsForAttachmentResponse';import type { HttpSendChatMessageRequest } from './generated/schemas/httpSendChatMessageRequest';+import type { ModelsResponse } from './generated/schemas/modelsResponse';import type { PatchChatRequest } from './generated/schemas/patchChatRequest';import type { SendChatMessageResponse } from './generated/schemas/sendChatMessageResponse';import type { ServerResponse } from './generated/schemas/serverResponse';@@ -199,6 +200,14 @@ export const cognitionApiServiceClient = {})).map((result) => result);},+ async getModels() {+ return (+ await dcsFetch<ModelsResponse>(`/chats/models`, {+ method: 'GET',+ })+ ).map((result) => result);+ },+async getChatsForAttachment(args: { attachment_id: string }) {const { attachment_id } = args;return (diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.tsindex e8b67cc0bd..07cec76b58 100644--- a/js/app/packages/service-clients/service-cognition/generated/client.ts+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts@@ -24,6 +24,7 @@ import type {McpAuthCallbackParams,MemoryErrorBody,MemoryResponse,+ ModelsResponse,PatchChatRequest,RejectToolCallRequest,SendChatMessageResponse,@@ -455,6 +456,53 @@ export const getChatHistoryBatchMessagesHandler = async (} as getChatHistoryBatchMessagesHandlerResponse;};+/**+ * @summary List all chat models, each flagged with whether the requesting user has+access (free users get Haiku; professional users get everything).+ */+export type listModelsResponse200 = {+ data: ModelsResponse;+ status: 200;+};++export type listModelsResponse500 = {+ data: string;+ status: 500;+};++export type listModelsResponseSuccess = listModelsResponse200 & {+ headers: Headers;+};+export type listModelsResponseError = listModelsResponse500 & {+ headers: Headers;+};++export type listModelsResponse =+ | listModelsResponseSuccess+ | listModelsResponseError;++export const getListModelsUrl = () => {+ return `/chats/models`;+};++export const listModels = async (+ options?: RequestInit+): Promise<listModelsResponse> => {+ const res = await fetch(getListModelsUrl(), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: listModelsResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as listModelsResponse;+};+/*** @summary Get a chat by ID with messages and web citations.*/diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/agentModel.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/agentModel.tsdeleted file mode 100644index df99e89d98..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/agentModel.ts+++ /dev/null@@ -1,27 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--/**- * Model to use for completions.--Unrecognized model strings (including retired Google/OpenAI variants-from older data) deserialize to `Retired` via the manual-`Deserialize` impl.- */-export type AgentModel = (typeof AgentModel)[keyof typeof AgentModel];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const AgentModel = {- smart: 'smart',- fast: 'fast',- opus4_7: 'opus4_7',- sonnet4_6: 'sonnet4_6',- haiku4_5: 'haiku4_5',- gpt5_5: 'gpt5_5',- gpt5Mini: 'gpt5Mini',- retired: 'retired',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponse.tsindex fd80c11e4f..310b98d366 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponse.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponse.ts@@ -21,6 +21,7 @@ export interface ChatResponse {id: string;/** The messages in the chat. */messages: ChatMessageWithAttachments[];+ /** The model used to generate the chat (provider api id). */model?: ChatResponseModel;/** The name of the chat. */name: string;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseModel.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseModel.tsindex 598646b4a7..83718da8f3 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseModel.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseModel.ts@@ -4,6 +4,8 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/-import type { AgentModel } from './agentModel';-export type ChatResponseModel = null | AgentModel;+/**+ * The model used to generate the chat (provider api id).+ */+export type ChatResponseModel = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequest.tsindex 5b8ebc8691..078777b58a 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequest.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequest.ts@@ -4,8 +4,6 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/--import type { AgentModel } from './agentModel';import type { HttpSendChatMessageRequestAdditionalInstructions } from './httpSendChatMessageRequestAdditionalInstructions';import type { HttpSendChatMessageRequestAttachments } from './httpSendChatMessageRequestAttachments';import type { HttpSendChatMessageRequestChatId } from './httpSendChatMessageRequestChatId';@@ -24,8 +22,8 @@ export interface HttpSendChatMessageRequest {chat_id?: HttpSendChatMessageRequestChatId;/** The content of the message */content: string;- /** The model to respond with */- model: AgentModel;+ /** The model to respond with (provider api id) */+ model: string;/** Which toolset to use. Defaults to `all` */toolset?: ToolSet;}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/index.tsindex 65e2d54195..460e0ac5d8 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts@@ -7,7 +7,6 @@export * from './accessLevel';export * from './addServerRequest';-export * from './agentModel';export * from './assistantMessagePart';export * from './assistantMessagePartOneOf';export * from './assistantMessagePartOneOfEight';@@ -116,6 +115,8 @@ export * from './mcpAuthCallbackParams';export * from './memoryErrorBody';export * from './memoryResponse';export * from './messageWithAttachments';+export * from './modelAccess';+export * from './modelsResponse';export * from './newAttachment';export * from './newChatMessage';export * from './newChatMessageAttachments';diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/model.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/model.tsindex f85b27f754..f50098ac5e 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/model.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/model.ts@@ -7,14 +7,14 @@ import { z } from 'zod';export type Model = (typeof Model)[keyof typeof Model];export const Model = {- 'claude-opus-4-7': 'claude-opus-4-7',+ 'claude-opus-4-8': 'claude-opus-4-8','claude-haiku-4-5': 'claude-haiku-4-5','gpt-5.5': 'gpt-5.5','gpt-5-mini': 'gpt-5-mini',} as const;export const AllModels: Model[] = [- 'claude-opus-4-7',+ 'claude-opus-4-8','claude-haiku-4-5','gpt-5.5','gpt-5-mini',diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/modelAccess.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/modelAccess.tsnew file mode 100644index 0000000000..4303a54daa--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/modelAccess.ts@@ -0,0 +1,23 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * A chat model paired with whether the requesting user may use it.+ */+export interface ModelAccess {+ /** Whether the requesting user has access to this model. */+ available: boolean;+ /**+ * Context window size in tokens.+ * @minimum 0+ */+ contextWindow: number;+ /** Provider api id — the string sent when this model is selected. */+ id: string;+ /** Provider serving the model (e.g. `anthropic`, `openai`). */+ provider: string;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/modelsResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/modelsResponse.tsnew file mode 100644index 0000000000..bf73596333--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/modelsResponse.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { ModelAccess } from './modelAccess';++/**+ * Response body for the models-access endpoint: every chat model, each+flagged with the requesting user's access.+ */+export interface ModelsResponse {+ /** All chat models, in display order. */+ models: ModelAccess[];+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/newChatMessage.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/newChatMessage.tsindex 6597c2d5dd..80b8c78a70 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/newChatMessage.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/newChatMessage.ts@@ -5,7 +5,6 @@* OpenAPI spec version: 1.0.0*/-import type { AgentModel } from './agentModel';import type { ChatMessageContent } from './chatMessageContent';import type { NewChatMessageAttachments } from './newChatMessageAttachments';import type { NewChatMessageId } from './newChatMessageId';@@ -19,8 +18,8 @@ export interface NewChatMessage {createdAt: string;/** Optional pre-generated ID. If None, the database generates one. */id?: NewChatMessageId;- /** The model used to generate the chat */- model: AgentModel;+ /** The model used to generate the chat (provider api id) */+ model: string;/** Whether the chat is from the user or system */role: Role;updatedAt: string;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessagePayloadAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessagePayloadAllOf.tsindex 4e67dfdc62..d2de27e8aa 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessagePayloadAllOf.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessagePayloadAllOf.ts@@ -4,8 +4,6 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/--import type { AgentModel } from './agentModel';import type { SendChatMessagePayloadAllOfAdditionalInstructions } from './sendChatMessagePayloadAllOfAdditionalInstructions';import type { SendChatMessagePayloadAllOfAttachments } from './sendChatMessagePayloadAllOfAttachments';import type { ToolSet } from './toolSet';@@ -19,8 +17,8 @@ export type SendChatMessagePayloadAllOf = {chat_id: string;/** The content of the message */content: string;- /** the chate model to respond with */- model: AgentModel;+ /** the chat model to respond with (provider api id) */+ model: string;/** Stream ID for tracking the response */stream_id: string;/** Which toolset to use. Defaults to `all` */diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOf.tsindex 5df3a9a957..cf282aa1dc 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOf.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOf.ts@@ -4,11 +4,10 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/-import type { AgentModel } from './agentModel';import type { StreamErrorOneOfStreamError } from './streamErrorOneOfStreamError';export type StreamErrorOneOf = {- model: AgentModel;+ model: string;stream_error: StreamErrorOneOfStreamError;stream_id: string;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionRequest.tsindex 7d3e7056f4..c84149c17b 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionRequest.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/structuredCompletionRequest.ts@@ -5,14 +5,13 @@* OpenAPI spec version: 1.0.0*/-import type { AgentModel } from './agentModel';import type { DynamicSchema } from './dynamicSchema';import type { StructuredCompletionRequestAdditionalInstructions } from './structuredCompletionRequestAdditionalInstructions';import type { ToolSet } from './toolSet';export interface StructuredCompletionRequest {additional_instructions?: StructuredCompletionRequestAdditionalInstructions;- model: AgentModel;+ model: string;output_schema: DynamicSchema;prompt: string;toolset?: ToolSet;diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.jsonindex a527494258..116b36712c 100644--- a/js/app/packages/service-clients/service-cognition/openapi.json+++ b/js/app/packages/service-clients/service-cognition/openapi.json@@ -365,6 +365,35 @@}}},+ "/chats/models": {+ "get": {+ "tags": ["chats"],+ "summary": "List all chat models, each flagged with whether the requesting user has\naccess (free users get Haiku; professional users get everything).",+ "operationId": "list_models",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ModelsResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/chats/{chat_id}": {"get": {"tags": ["chats"],@@ -1410,20 +1439,6 @@}}},- "AgentModel": {- "type": "string",- "description": "Model to use for completions.\n\nUnrecognized model strings (including retired Google/OpenAI variants\nfrom older data) deserialize to `Retired` via the manual\n`Deserialize` impl.",- "enum": [- "smart",- "fast",- "opus4_7",- "sonnet4_6",- "haiku4_5",- "gpt5_5",- "gpt5Mini",- "retired"- ]- },"AssistantMessagePart": {"oneOf": [{@@ -1960,15 +1975,8 @@"description": "The messages in the chat."},"model": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/AgentModel",- "description": "The model used to generate the chat."- }- ]+ "type": ["string", "null"],+ "description": "The model used to generate the chat (provider api id)."},"name": {"type": "string",@@ -2763,8 +2771,8 @@"description": "The content of the message"},"model": {- "$ref": "#/components/schemas/AgentModel",- "description": "The model to respond with"+ "type": "string",+ "description": "The model to respond with (provider api id)"},"toolset": {"$ref": "#/components/schemas/ToolSet",@@ -2821,6 +2829,45 @@}}},+ "ModelAccess": {+ "type": "object",+ "description": "A chat model paired with whether the requesting user may use it.",+ "required": ["id", "provider", "contextWindow", "available"],+ "properties": {+ "available": {+ "type": "boolean",+ "description": "Whether the requesting user has access to this model."+ },+ "contextWindow": {+ "type": "integer",+ "format": "int64",+ "description": "Context window size in tokens.",+ "minimum": 0+ },+ "id": {+ "type": "string",+ "description": "Provider api id — the string sent when this model is selected."+ },+ "provider": {+ "type": "string",+ "description": "Provider serving the model (e.g. `anthropic`, `openai`)."+ }+ }+ },+ "ModelsResponse": {+ "type": "object",+ "description": "Response body for the models-access endpoint: every chat model, each\nflagged with the requesting user's access.",+ "required": ["models"],+ "properties": {+ "models": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ModelAccess"+ },+ "description": "All chat models, in display order."+ }+ }+ },"NewAttachment": {"type": "object","required": ["attachment_type", "attachment_id"],@@ -2857,8 +2904,8 @@"description": "Optional pre-generated ID. If None, the database generates one."},"model": {- "$ref": "#/components/schemas/AgentModel",- "description": "The model used to generate the chat"+ "type": "string",+ "description": "The model used to generate the chat (provider api id)"},"role": {"$ref": "#/components/schemas/Role",@@ -2959,8 +3006,8 @@"description": "The content of the message"},"model": {- "$ref": "#/components/schemas/AgentModel",- "description": "the chate model to respond with"+ "type": "string",+ "description": "the chat model to respond with (provider api id)"},"stream_id": {"type": "string",@@ -3122,7 +3169,7 @@"required": ["stream_id", "model", "stream_error"],"properties": {"model": {- "$ref": "#/components/schemas/AgentModel"+ "type": "string"},"stream_error": {"type": "string",@@ -3187,7 +3234,7 @@"type": ["string", "null"]},"model": {- "$ref": "#/components/schemas/AgentModel"+ "type": "string"},"output_schema": {"$ref": "#/components/schemas/DynamicSchema"diff --git a/js/app/packages/service-clients/service-scheduled-action/generated/schemas/agentModel.ts b/js/app/packages/service-clients/service-scheduled-action/generated/schemas/agentModel.tsdeleted file mode 100644index c87ec94fbd..0000000000--- a/js/app/packages/service-clients/service-scheduled-action/generated/schemas/agentModel.ts+++ /dev/null@@ -1,28 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * scheduled_action- * API for managing scheduled actions- * OpenAPI spec version: 0.1.0- */--/**- * Model to use for completions.--Unrecognized model strings (including retired Google/OpenAI variants-from older data) deserialize to `Retired` via the manual-`Deserialize` impl.- */-export type AgentModel = (typeof AgentModel)[keyof typeof AgentModel];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const AgentModel = {- smart: 'smart',- fast: 'fast',- opus4_7: 'opus4_7',- sonnet4_6: 'sonnet4_6',- haiku4_5: 'haiku4_5',- gpt5_5: 'gpt5_5',- gpt5Mini: 'gpt5Mini',- retired: 'retired',-} as const;diff --git a/js/app/packages/service-clients/service-scheduled-action/generated/schemas/agentTask.ts b/js/app/packages/service-clients/service-scheduled-action/generated/schemas/agentTask.tsindex 1eaa396da1..51ccd62ad9 100644--- a/js/app/packages/service-clients/service-scheduled-action/generated/schemas/agentTask.ts+++ b/js/app/packages/service-clients/service-scheduled-action/generated/schemas/agentTask.ts@@ -5,10 +5,9 @@* API for managing scheduled actions* OpenAPI spec version: 0.1.0*/-import type { AgentModel } from './agentModel';export interface AgentTask {- model: AgentModel;+ model: string;prompt: string;user_prompt: string;}diff --git a/js/app/packages/service-clients/service-scheduled-action/generated/schemas/index.ts b/js/app/packages/service-clients/service-scheduled-action/generated/schemas/index.tsindex 68e756e0f0..cd33772993 100644--- a/js/app/packages/service-clients/service-scheduled-action/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-scheduled-action/generated/schemas/index.ts@@ -11,7 +11,6 @@ export * from './actionExecutionRecordId';export * from './actionExecutionRecordResourceId';export * from './actionExecutionRecordResult';export * from './actionKind';-export * from './agentModel';export * from './agentTask';export * from './createScheduledAction';export * from './createScheduledActionTask';diff --git a/js/app/packages/service-clients/service-scheduled-action/openapi.json b/js/app/packages/service-clients/service-scheduled-action/openapi.jsonindex c28e47d7b2..8533cd27c3 100644--- a/js/app/packages/service-clients/service-scheduled-action/openapi.json+++ b/js/app/packages/service-clients/service-scheduled-action/openapi.json@@ -415,26 +415,12 @@"type": "string","enum": ["Agent"]},- "AgentModel": {- "type": "string",- "description": "Model to use for completions.\n\nUnrecognized model strings (including retired Google/OpenAI variants\nfrom older data) deserialize to `Retired` via the manual\n`Deserialize` impl.",- "enum": [- "smart",- "fast",- "opus4_7",- "sonnet4_6",- "haiku4_5",- "gpt5_5",- "gpt5Mini",- "retired"- ]- },"AgentTask": {"type": "object","required": ["model", "prompt", "user_prompt"],"properties": {"model": {- "$ref": "#/components/schemas/AgentModel"+ "type": "string"},"prompt": {"type": "string"diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 12d28dd6e4..f54cf6ffbe 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -57,6 +57,7 @@ dependencies = ["macro_user_id","model-entity","non_empty",+ "regex","rig-core","schemars 1.2.1","serde",@@ -13991,7 +13992,6 @@ dependencies = ["rand 0.8.6","rand 0.9.4","redis",- "regex","regex-automata","regex-syntax","reqwest 0.13.4",diff --git a/rust/cloud-storage/agent/Cargo.toml b/rust/cloud-storage/agent/Cargo.tomlindex b6bae88dee..ed854b83c5 100644--- a/rust/cloud-storage/agent/Cargo.toml+++ b/rust/cloud-storage/agent/Cargo.toml@@ -13,6 +13,7 @@ async-openai = { workspace = true }async-stream = { workspace = true }async-trait = { workspace = true }futures = { workspace = true }+regex = { workspace = true }# Macro fork of rig (upstream main + with_non_strict_tools() on Responses# API models). Drop back to crates.io once the patch lands upstream.rig-core = { git = "https://github.com/macro-inc/rig", branch = "feat/responses-api-non-strict-tools" }diff --git a/rust/cloud-storage/agent/src/agent_loop.rs b/rust/cloud-storage/agent/src/agent_loop.rsindex 337c0e830b..818f6ef86d 100644--- a/rust/cloud-storage/agent/src/agent_loop.rs+++ b/rust/cloud-storage/agent/src/agent_loop.rs@@ -1,14 +1,16 @@/// The main entry point: [`AgentLoop`] and [`Session`].use crate::error::AgentError;use crate::hook::{StreamBridge, ToolRouter};-use crate::model::{AgentModel, ModelProvider};+use crate::model::AgentModel;+use crate::model::router::{AllModelsRouter, RoutedModel};+use crate::model::types::Model;use crate::stream::{ChatCompletionStream, StreamPart};use crate::tool_adapter::DynToolSetAdapter;use ai_toolset::{RequestContext, ToolSet as AiToolSet};use futures::StreamExt;use macro_user_id::user_id::MacroUserIdStr;use rig_core::agent::{Agent, MultiTurnStreamItem};-use rig_core::client::{CompletionClient, ProviderClient};+use rig_core::client::ProviderClient;use rig_core::completion::{CompletionModel, GetTokenUsage};use rig_core::message::Message;use rig_core::providers::{anthropic, openai};@@ -22,13 +24,15 @@ const DEFAULT_MAX_TOKENS: u64 = 16_000;/// Factory for creating per-request agent sessions.////// Holds one client per provider and routes each session to the provider-/// serving the selected model (see [`AgentModel::provider`]). Tools and-/// system prompt are provided per-session since they vary by request+/// serving the selected model id (see [`AllModelsRouter`]). The model is a+/// plain api-id string so the frontend can select it directly; backend+/// callers pass an [`AgentModel`] via `with_model` (it is `ToString`). Tools+/// and system prompt are provided per-session since they vary by request/// (MCP tools are per-user, system prompt depends on toolset selection).pub struct AgentLoop {- anthropic: anthropic::Client,- openai: Option<openai::Client>,- model: AgentModel,+ anthropic: Arc<anthropic::Client>,+ openai: Arc<openai::Client>,+ model: String,max_turns: usize,max_tokens: u64,}@@ -43,24 +47,26 @@ impl AgentLoop {/// Create an `AgentLoop` with provider clients from the environment and/// the default model (Opus 4.7).///- /// `ANTHROPIC_API_KEY` is required. `OPENAI_API_KEY` is optional at- /// construction; selecting an OpenAI model without it panics at- /// session creation.+ /// `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` are required.pub fn new() -> Self {- let anthropic = anthropic::Client::from_env().expect("ANTHROPIC_API_KEY must be set");- let openai = openai::Client::from_env().ok();+ let anthropic =+ Arc::new(anthropic::Client::from_env().expect("ANTHROPIC_API_KEY must be set"));+ let openai = Arc::new(openai::Client::from_env().expect("OPENAI_API_KEY must be set"));Self {anthropic,openai,- model: AgentModel::default(),+ model: AgentModel::default().to_string(),max_turns: DEFAULT_MAX_TURNS,max_tokens: DEFAULT_MAX_TOKENS,}}/// Override the model.- pub fn with_model(mut self, model: AgentModel) -> Self {- self.model = model;+ ///+ /// Accepts any stringifiable id — an [`AgentModel`] (backend) or a raw+ /// api-id string (frontend).+ pub fn with_model<M: ToString>(mut self, model: M) -> Self {+ self.model = model.to_string();self}@@ -79,16 +85,19 @@ impl AgentLoop {fn build_agent<M: CompletionModel>(&self,model: M,+ thinking: Option<serde_json::Value>,handle: ToolServerHandle,system_prompt: &str,) -> Agent<M> {- rig_core::agent::AgentBuilder::new(model)+ let mut builder = rig_core::agent::AgentBuilder::new(model).tool_server_handle(handle).default_max_turns(self.max_turns).max_tokens(self.max_tokens)- .additional_params(self.model.thinking_params())- .preamble(system_prompt)- .build()+ .preamble(system_prompt);+ if let Some(params) = thinking {+ builder = builder.additional_params(params);+ }+ builder.build()}/// Start a new streaming session.@@ -126,24 +135,34 @@ impl AgentLoop {.expect("failed to register tool");}- let agent = match self.model.provider() {- ModelProvider::Anthropic => {- let model = self.anthropic.completion_model(self.model.api_id());- ProviderAgent::Anthropic(self.build_agent(model, handle, system_prompt))+ // Tell the model which model it is. Done here (not on the frontend)+ // so the system prompt always reflects the model actually serving the+ // request.+ let system_prompt = format!("{system_prompt}\n\nYou are the {} model.", self.model);++ // The frontend selects the model by api id; route it to the provider+ // that serves it (falling back to the default on unknown / unavailable+ // ids). Each `RoutedModel` arm yields a concrete completion model that+ // feeds the provider-specific `ProviderAgent`.+ let router = AllModelsRouter::new(self.anthropic.clone(), self.openai.clone());+ let agent = match router.route_or_default(&self.model) {+ RoutedModel::Anthropic(m) => {+ let thinking = m.thinking_params();+ ProviderAgent::Anthropic(self.build_agent(+ m.completion(),+ thinking,+ handle,+ &system_prompt,+ ))}- ModelProvider::OpenAi => {- let client = self- .openai- .as_ref()- .expect("OPENAI_API_KEY must be set to use OpenAI models");- // Non-strict tools: send tool schemas verbatim instead of- // letting rig sanitize them into OpenAI's strict subset,- // which silently forces every optional parameter into- // `required`.- let model = client- .completion_model(self.model.api_id())- .with_non_strict_tools();- ProviderAgent::OpenAi(self.build_agent(model, handle, system_prompt))+ RoutedModel::OpenAi(m) => {+ let thinking = m.thinking_params();+ ProviderAgent::OpenAi(self.build_agent(+ m.completion(),+ thinking,+ handle,+ &system_prompt,+ ))}};diff --git a/rust/cloud-storage/agent/src/completion.rs b/rust/cloud-storage/agent/src/completion.rsindex 77e4adb6fe..b5f41ef0e0 100644--- a/rust/cloud-storage/agent/src/completion.rs+++ b/rust/cloud-storage/agent/src/completion.rs@@ -1,68 +1,52 @@/// One-shot completion — send a prompt and get a string response.-use crate::model::{AgentModel, ModelProvider};-use rig_core::client::{CompletionClient, ProviderClient};+use crate::model::router::{AllModelsRouter, RoutedModel};+use crate::model::types::Model;+use rig_core::client::ProviderClient;use rig_core::completion::{CompletionModel, Prompt};use rig_core::message::Message;use rig_core::providers::{anthropic, openai};+use std::sync::Arc;++/// Build a router over provider clients from the environment.+///+/// `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` are required.+fn env_router() -> anyhow::Result<AllModelsRouter> {+ let anthropic = Arc::new(anthropic::Client::from_env()?);+ let openai = Arc::new(openai::Client::from_env()?);+ Ok(AllModelsRouter::new(anthropic, openai))+}/// Send a system prompt + user message and return the model's text response.////// This is the simple, non-streaming path for one-shot tasks like-/// summarization.-#[tracing::instrument(skip(system_prompt, user_message), err)]-pub async fn complete(- model: AgentModel,+/// summarization. `model` is anything stringifiable to an api id — an+/// [`AgentModel`](crate::AgentModel) or a raw string from the frontend.+#[tracing::instrument(skip(model, system_prompt, user_message), err)]+pub async fn complete<M: ToString>(+ model: M,system_prompt: &str,user_message: &str,) -> anyhow::Result<String> {- match model.provider() {- ModelProvider::Anthropic => {- let client = anthropic::Client::from_env()?;- prompt_once(- client.completion_model(model.api_id()),- system_prompt,- user_message,- )- .await- }- ModelProvider::OpenAi => {- let client = openai::Client::from_env()?;- prompt_once(- client.completion_model(model.api_id()),- system_prompt,- user_message,- )- .await- }+ match env_router()?.route_or_default(&model.to_string()) {+ RoutedModel::Anthropic(m) => prompt_once(m.completion(), system_prompt, user_message).await,+ RoutedModel::OpenAi(m) => prompt_once(m.completion(), system_prompt, user_message).await,}}/// Send a system prompt + conversation history and return the model's text/// response.-#[tracing::instrument(skip(system_prompt, messages), err)]-pub async fn complete_with_history(- model: AgentModel,+#[tracing::instrument(skip(model, system_prompt, messages), err)]+pub async fn complete_with_history<M: ToString>(+ model: M,system_prompt: &str,messages: Vec<Message>,) -> anyhow::Result<String> {- match model.provider() {- ModelProvider::Anthropic => {- let client = anthropic::Client::from_env()?;- prompt_with_history(- client.completion_model(model.api_id()),- system_prompt,- messages,- )- .await+ match env_router()?.route_or_default(&model.to_string()) {+ RoutedModel::Anthropic(m) => {+ prompt_with_history(m.completion(), system_prompt, messages).await}- ModelProvider::OpenAi => {- let client = openai::Client::from_env()?;- prompt_with_history(- client.completion_model(model.api_id()),- system_prompt,- messages,- )- .await+ RoutedModel::OpenAi(m) => {+ prompt_with_history(m.completion(), system_prompt, messages).await}}}diff --git a/rust/cloud-storage/agent/src/error.rs b/rust/cloud-storage/agent/src/error.rsindex 0e023ba516..24903fd58f 100644--- a/rust/cloud-storage/agent/src/error.rs+++ b/rust/cloud-storage/agent/src/error.rs@@ -16,4 +16,9 @@ pub enum AgentError {/// Catch-all.#[error(transparent)]Other(#[from] anyhow::Error),+ /// Unknown completion model+ #[error("unknown completion model [{0}]")]+ UnknownModel(String),}++pub type Result<T> = std::result::Result<T, AgentError>;diff --git a/rust/cloud-storage/agent/src/lib.rs b/rust/cloud-storage/agent/src/lib.rsindex 933437cb9e..445cd96696 100644--- a/rust/cloud-storage/agent/src/lib.rs+++ b/rust/cloud-storage/agent/src/lib.rs@@ -21,7 +21,7 @@ pub use completion::{complete, complete_with_history};pub use convert::{merge_consecutive_parts, to_rig_messages};pub use error::AgentError;pub use hook::StreamBridge;-pub use model::{AgentModel, ModelProvider};+pub use model::{AgentModel, Provider};pub use stream::{ChatCompletionStream, McpInfo, StreamPart, ToolCall, ToolResponse, Usage};pub use tool_adapter::{DynToolSetAdapter, ToolsetToolAdapter, normalize_request_schema};diff --git a/rust/cloud-storage/agent/src/model/anthropic.rs b/rust/cloud-storage/agent/src/model/anthropic.rsnew file mode 100644index 0000000000..1b242057ef--- /dev/null+++ b/rust/cloud-storage/agent/src/model/anthropic.rs@@ -0,0 +1,115 @@+use super::Model;+use crate::error::AgentError;+use regex::Regex;+use rig_core::{client::CompletionClient, providers::anthropic};+use std::sync::{Arc, LazyLock};++/// Matches the Anthropic model namespace.+///+/// The frontend is authoritative over model selection, so we only need to+/// decide which *provider* an id belongs to — not validate the exact id (the+/// string is passed through to the API verbatim). Every Claude id is+/// `claude-<family>-<version>` (`claude-opus-4-8`, `claude-sonnet-4-6`,+/// `claude-haiku-4-5`, `claude-fable-5`, …), so a single prefix covers the+/// whole provider.+static ANTHROPIC_MODEL_RE: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r"^claude-").expect("Anthropic model regex is valid"));++/// Whether `model` names a known Anthropic model.+pub(crate) fn is_anthropic_model(model: &str) -> bool {+ ANTHROPIC_MODEL_RE.is_match(model)+}++/// An api id validated as belonging to the Anthropic namespace.+///+/// The only constructor is [`TryFrom<String>`], which checks the id against+/// [`is_anthropic_model`]. An `AnthropicModelId` therefore always names an+/// Anthropic model, so routing one is infallible.+#[derive(Debug, Clone)]+pub struct AnthropicModelId(String);++impl AnthropicModelId {+ /// The underlying api id, passed verbatim to the Anthropic API.+ pub(crate) fn as_str(&self) -> &str {+ &self.0+ }+}++impl TryFrom<String> for AnthropicModelId {+ type Error = AgentError;++ fn try_from(model: String) -> Result<Self, Self::Error> {+ if is_anthropic_model(&model) {+ Ok(Self(model))+ } else {+ Err(AgentError::UnknownModel(model))+ }+ }+}++pub struct AnthropicModel {+ client: Arc<anthropic::Client>,+ model: AnthropicModelId,+}++impl AnthropicModel {+ /// Build a model bound to `model` served by `client`.+ ///+ /// Validation happens when the [`AnthropicModelId`] is constructed; the id+ /// is passed through verbatim to the Anthropic API.+ pub(super) fn new(client: Arc<anthropic::Client>, model: AnthropicModelId) -> Self {+ Self { client, model }+ }+}++impl Model for AnthropicModel {+ type Completion = anthropic::completion::CompletionModel;++ fn completion(&self) -> Self::Completion {+ self.client+ .completion_model(self.model.as_str().to_string())+ }++ /// Best-effort extended-thinking config for the configured model.+ ///+ /// Returned JSON is flattened into the request body by rig, so the+ /// top-level keys here (`thinking`) become top-level request fields.+ ///+ /// The shape is chosen per model family so it never produces a config+ /// that 400s for that model:+ /// - Opus / Fable / Mythos: adaptive thinking only (`enabled` ++ /// `budget_tokens` is rejected on Opus 4.7+). `display` is valid here.+ /// - Sonnet (4.6): adaptive is supported and avoids the+ /// `budget_tokens < max_tokens` constraint.+ /// - Haiku (4.5): no adaptive support; use `enabled` + `budget_tokens`.+ /// `display` is omitted — it postdates Haiku 4.5's thinking surface and+ /// would risk a 400.+ ///+ /// Crucially we never set `temperature`: it is removed on Opus 4.7+ (400)+ /// and constrained to 1 with extended thinking elsewhere, so we leave it+ /// unset and let the API default apply.+ ///+ /// Any model we don't recognize as thinking-capable returns `None`.+ fn thinking_params(&self) -> Option<serde_json::Value> {+ let model = self.model.as_str().to_lowercase();++ // Opus / Fable / Mythos and Sonnet all take the same adaptive config+ // (Sonnet supports adaptive and so avoids the `budget_tokens < max_tokens`+ // constraint); only Haiku needs the explicit `enabled` + `budget_tokens`.+ if model.contains("opus")+ || model.contains("fable")+ || model.contains("mythos")+ || model.contains("sonnet")+ {+ Some(serde_json::json!({+ "thinking": { "type": "adaptive", "display": "summarized" }+ }))+ } else if model.contains("haiku") {+ Some(serde_json::json!({+ "thinking": { "type": "enabled", "budget_tokens": 10_000 }+ }))+ } else {+ None+ }+ }+}diff --git a/rust/cloud-storage/agent/src/model.rs b/rust/cloud-storage/agent/src/model/mod.rssimilarity index 53%rename from rust/cloud-storage/agent/src/model.rsrename to rust/cloud-storage/agent/src/model/mod.rsindex ed3941260e..b5aec78e0c 100644--- a/rust/cloud-storage/agent/src/model.rs+++ b/rust/cloud-storage/agent/src/model/mod.rs@@ -1,19 +1,26 @@-/// Supported models for the agent loop.-use rig_core::providers::{anthropic, openai};-use serde::{Deserialize, Serialize};-use strum::{Display, EnumIter, EnumString};+use rig_core::providers::anthropic::completion::{+ CLAUDE_HAIKU_4_5, CLAUDE_OPUS_4_7, CLAUDE_OPUS_4_8, CLAUDE_SONNET_4_6,+};+use rig_core::providers::openai::{GPT_5_5, GPT_5_MINI};+use serde::Serialize;use utoipa::ToSchema;+pub mod types;+pub use types::*;+mod anthropic;+mod openai;+pub mod router;+/// API provider serving a model.#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum ModelProvider {+pub enum Provider {/// Anthropic (Claude models)Anthropic,/// OpenAI (GPT models)OpenAi,}-impl ModelProvider {+impl Provider {/// Lowercase provider name as exposed in the models schema.pub fn as_str(&self) -> &'static str {match self {@@ -25,59 +32,48 @@ impl ModelProvider {/// Model to use for completions.///-/// Unrecognized model strings (including retired Google/OpenAI variants-/// from older data) deserialize to `Retired` via the manual-/// `Deserialize` impl.-#[derive(- Serialize, Debug, Clone, Copy, PartialEq, Eq, Display, EnumString, EnumIter, ToSchema, Default,-)]-#[serde(rename_all = "camelCase")]+/// This type is **serialize-only**: every variant's wire form is the+/// provider's **api id** — the exact string the API (and the model router)+/// expects. The two semantic tiers (`Smart` / `Fast`) are server-side+/// concepts that resolve to a concrete model, so they serialize to that+/// model's api id too — the router never sees a semantic name, only an id it+/// can dispatch. `Smart` and `Haiku4_5`/`Fast` may share a wire id; that's+/// fine because we never deserialize this enum.+#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq, ToSchema, Default)]pub enum AgentModel {- /// Best available model+ /// Best available model (currently Claude Opus 4.8)#[default]+ #[serde(rename = "claude-opus-4-8")]Smart,- /// Fastest available model+ /// Fastest available model (currently Claude Haiku 4.5)+ #[serde(rename = "claude-haiku-4-5")]Fast,/// Claude Opus 4.7+ #[serde(rename = "claude-opus-4-7")]Opus4_7,/// Claude Sonnet 4.6+ #[serde(rename = "claude-sonnet-4-6")]Sonnet4_6,/// Claude Haiku 4.5+ #[serde(rename = "claude-haiku-4-5")]Haiku4_5,/// OpenAI GPT-5.5+ #[serde(rename = "gpt-5.5")]Gpt5_5,/// OpenAI GPT-5 mini+ #[serde(rename = "gpt-5-mini")]Gpt5Mini,/// Retired or unrecognized model, routes to the default+ #[serde(rename = "claude-opus-4-8")]Retired,}-impl<'de> Deserialize<'de> for AgentModel {- fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {- let s = String::deserialize(deserializer)?;- #[derive(Deserialize)]- #[serde(rename_all = "camelCase")]- enum Known {- Smart,- Fast,- Opus4_7,- Sonnet4_6,- Haiku4_5,- Gpt5_5,- Gpt5Mini,- Retired,- }- match serde_json::from_value::<Known>(serde_json::Value::String(s)) {- Ok(Known::Smart) => Ok(Self::Smart),- Ok(Known::Fast) => Ok(Self::Fast),- Ok(Known::Opus4_7) => Ok(Self::Opus4_7),- Ok(Known::Sonnet4_6) => Ok(Self::Sonnet4_6),- Ok(Known::Haiku4_5) => Ok(Self::Haiku4_5),- Ok(Known::Gpt5_5) => Ok(Self::Gpt5_5),- Ok(Known::Gpt5Mini) => Ok(Self::Gpt5Mini),- Ok(Known::Retired) => Ok(Self::Retired),- Err(_) => Ok(Self::Retired),- }+/// `to_string()` yields the api id, so backend callers can pass an+/// `AgentModel` anywhere a `T: ToString` model is expected and get the exact+/// string the API/router needs.+impl std::fmt::Display for AgentModel {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(self.api_id())}}@@ -85,17 +81,18 @@ impl AgentModel {/// Returns the provider API model identifier.pub fn api_id(&self) -> &'static str {match self {- Self::Smart | Self::Opus4_7 | Self::Retired => anthropic::completion::CLAUDE_OPUS_4_7,- Self::Fast | Self::Haiku4_5 => anthropic::completion::CLAUDE_HAIKU_4_5,- Self::Sonnet4_6 => anthropic::completion::CLAUDE_SONNET_4_6,- Self::Gpt5_5 => openai::GPT_5_5,- Self::Gpt5Mini => openai::GPT_5_MINI,+ Self::Smart | Self::Retired => CLAUDE_OPUS_4_8,+ Self::Opus4_7 => CLAUDE_OPUS_4_7,+ Self::Sonnet4_6 => CLAUDE_SONNET_4_6,+ Self::Fast | Self::Haiku4_5 => CLAUDE_HAIKU_4_5,+ Self::Gpt5_5 => GPT_5_5,+ Self::Gpt5Mini => GPT_5_MINI,}}/// Returns `additional_params` JSON to enable extended thinking / reasoning.///- /// - Opus 4.7: `adaptive` (model chooses when to think)+ /// - Opus 4.8 / 4.7: `adaptive` (model chooses when to think)/// - Sonnet 4.6 / Haiku 4.5: `enabled` with `budget_tokens`/// - GPT-5.5 / GPT-5 mini: Responses API `reasoning` with effort/// (no `temperature`; reasoning models reject it)@@ -132,22 +129,17 @@ impl AgentModel {}/// API provider serving this model.- pub fn provider(&self) -> ModelProvider {+ pub fn provider(&self) -> Provider {match self {Self::Smart| Self::Fast| Self::Opus4_7| Self::Sonnet4_6| Self::Haiku4_5- | Self::Retired => ModelProvider::Anthropic,- Self::Gpt5_5 | Self::Gpt5Mini => ModelProvider::OpenAi,+ | Self::Retired => Provider::Anthropic,+ Self::Gpt5_5 | Self::Gpt5Mini => Provider::OpenAi,}}-- /// from json or Retired- pub fn from_json_or_default(json: &str) -> Self {- serde_json::from_str(json).unwrap_or(Self::Retired)- }}#[cfg(test)]diff --git a/rust/cloud-storage/agent/src/model/openai.rs b/rust/cloud-storage/agent/src/model/openai.rsnew file mode 100644index 0000000000..9e89a550b6--- /dev/null+++ b/rust/cloud-storage/agent/src/model/openai.rs@@ -0,0 +1,112 @@+use super::Model;+use crate::error::AgentError;+use regex::Regex;+use rig_core::{client::CompletionClient, providers::openai};+use std::sync::{Arc, LazyLock};++/// Matches the OpenAI model namespace.+///+/// The frontend is authoritative over model selection, so we only need to+/// decide which *provider* an id belongs to — not validate the exact id (the+/// string is passed through to the API verbatim). Every OpenAI id falls under+/// one of these prefixes:+///+/// - `gpt-…` — `gpt-5*`, `gpt-4o`, `gpt-4.1`, `gpt-3.5-turbo`, …+/// - `o[1-9]…` — `o1`, `o3-mini`, `o4-mini`, `o3-pro`, …+/// - `chatgpt-…` — `chatgpt-4o-latest`+/// - `chat-latest`+///+/// Anthropic ids (`claude-*`) never match.+static OPENAI_MODEL_RE: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(r"^(?:gpt-|o[1-9]|chatgpt-|chat-latest)").expect("OpenAI model regex is valid")+});++/// Whether `model` names a known OpenAI model.+pub(crate) fn is_openai_model(model: &str) -> bool {+ OPENAI_MODEL_RE.is_match(model)+}++/// An api id validated as belonging to the OpenAI namespace.+///+/// The only constructor is [`TryFrom<String>`], which checks the id against+/// [`is_openai_model`]. An `OpenAiModelId` therefore always names an OpenAI+/// model, so routing one is infallible.+#[derive(Debug, Clone)]+pub struct OpenAiModelId(String);++impl OpenAiModelId {+ /// The underlying api id, passed verbatim to the OpenAI API.+ pub(crate) fn as_str(&self) -> &str {+ &self.0+ }+}++impl TryFrom<String> for OpenAiModelId {+ type Error = AgentError;++ fn try_from(model: String) -> Result<Self, Self::Error> {+ if is_openai_model(&model) {+ Ok(Self(model))+ } else {+ Err(AgentError::UnknownModel(model))+ }+ }+}++pub struct OpenAiModel {+ client: Arc<openai::Client>,+ model: OpenAiModelId,+}++impl OpenAiModel {+ /// Build a model bound to `model` served by `client`.+ ///+ /// Validation happens when the [`OpenAiModelId`] is constructed; the id is+ /// passed through verbatim to the OpenAI API.+ pub(super) fn new(client: Arc<openai::Client>, model: OpenAiModelId) -> Self {+ Self { client, model }+ }+}++impl Model for OpenAiModel {+ type Completion = openai::responses_api::ResponsesCompletionModel;++ /// Tools are sent verbatim (`with_non_strict_tools`) rather than coerced+ /// into OpenAI's strict subset, which would silently force every optional+ /// tool parameter to `required`.+ fn completion(&self) -> Self::Completion {+ self.client+ .completion_model(self.model.as_str().to_string())+ .with_non_strict_tools()+ }++ /// Best-effort reasoning config for the configured model.+ ///+ /// Returned JSON is flattened into the Responses API request by rig and+ /// parsed into its `reasoning` parameter (`effort` + `summary`).+ ///+ /// Reasoning is only valid on reasoning models — the GPT-5 family — so+ /// anything else returns `None` (sending `reasoning` to a non-reasoning+ /// model 400s). Within the family, the smaller `mini` / `nano` variants+ /// get a lower effort than the full models.+ ///+ /// We never set `temperature`: reasoning models reject it, so we leave it+ /// unset and let the API default apply.+ fn thinking_params(&self) -> Option<serde_json::Value> {+ let model = self.model.as_str().to_lowercase();++ if !model.contains("gpt-5") {+ return None;+ }++ let effort = if model.contains("mini") || model.contains("nano") {+ "low"+ } else {+ "high"+ };++ Some(serde_json::json!({+ "reasoning": { "effort": effort, "summary": "auto" }+ }))+ }+}diff --git a/rust/cloud-storage/agent/src/model/router.rs b/rust/cloud-storage/agent/src/model/router.rsnew file mode 100644index 0000000000..f1a33cf1af--- /dev/null+++ b/rust/cloud-storage/agent/src/model/router.rs@@ -0,0 +1,83 @@+//! Frontend-authoritative model routing.+//!+//! Per-provider id validation lives with each model type+//! ([`AnthropicModelId`], [`OpenAiModelId`]): their `TryFrom<String>` is the+//! only constructor and checks the id against that provider's namespace. The+//! single-provider [`AnthropicRouter`] / [`OpenAiRouter`] just bind a validated+//! id to a client. This module owns the cross-provider pieces: the+//! [`RoutedModel`] dispatch enum and the [`AllModelsRouter`] that composes the+//! per-provider routers and fans any raw id out to the one serving it.++mod anthropic;+mod openai;++#[cfg(test)]+mod test;++use self::anthropic::AnthropicRouter;+use self::openai::OpenAiRouter;+use super::anthropic::{AnthropicModel, AnthropicModelId};+use super::openai::{OpenAiModel, OpenAiModelId};+use super::types::ModelRouter;+use crate::error::AgentError;+use rig_core::providers::anthropic::Client as AnthropicClient;+use rig_core::providers::openai::Client as OpenAiClient;+use std::sync::Arc;++/// A routed model, tagged by the provider that serves it.+///+/// The two providers' completion models are distinct concrete types, so they+/// can't be unified behind a single `impl Model` (`Model::completion` would+/// have to return two types). The caller matches on the variant to build the+/// provider-specific agent — mirroring the `ProviderAgent` split in+/// `agent_loop`.+pub enum RoutedModel {+ /// An Anthropic (Claude) model.+ Anthropic(AnthropicModel),+ /// An OpenAI model.+ OpenAi(OpenAiModel),+}++/// Routes any supported model id to the provider that serves it.+///+/// Composes one single-provider router per provider. Both provider clients are+/// required at construction, so routing only fails for unknown ids.+pub struct AllModelsRouter {+ anthropic: AnthropicRouter,+ openai: OpenAiRouter,+}++impl AllModelsRouter {+ /// Build a router over the given provider clients.+ pub fn new(anthropic_client: Arc<AnthropicClient>, openai_client: Arc<OpenAiClient>) -> Self {+ Self {+ anthropic: AnthropicRouter::new(anthropic_client),+ openai: OpenAiRouter::new(openai_client),+ }+ }++ /// Route `model` to a provider-tagged [`RoutedModel`].+ ///+ /// Dispatch is driven by which provider's id type accepts the string:+ /// unknown ids match neither and yield [`AgentError::UnknownModel`].+ pub fn route(&self, model: &str) -> crate::error::Result<RoutedModel> {+ if let Ok(id) = OpenAiModelId::try_from(model.to_string()) {+ Ok(RoutedModel::OpenAi(self.openai.route_model(id)))+ } else if let Ok(id) = AnthropicModelId::try_from(model.to_string()) {+ Ok(RoutedModel::Anthropic(self.anthropic.route_model(id)))+ } else {+ Err(AgentError::UnknownModel(model.to_string()))+ }+ }++ /// Route `model`, falling back to the default model on any failure+ /// (unknown id). The default is always served by the Anthropic router,+ /// which is required, so this never fails.+ pub fn route_or_default(&self, model: &str) -> RoutedModel {+ self.route(model).unwrap_or_else(|_| {+ let default = AnthropicModelId::try_from(super::AgentModel::default().to_string())+ .expect("default model is a valid Anthropic id");+ RoutedModel::Anthropic(self.anthropic.route_model(default))+ })+ }+}diff --git a/rust/cloud-storage/agent/src/model/router/anthropic.rs b/rust/cloud-storage/agent/src/model/router/anthropic.rsnew file mode 100644index 0000000000..54dff1c945--- /dev/null+++ b/rust/cloud-storage/agent/src/model/router/anthropic.rs@@ -0,0 +1,27 @@+use crate::model::anthropic::{AnthropicModel, AnthropicModelId};+use crate::model::types::ModelRouter;+use rig_core::providers::anthropic;+use std::sync::Arc;++/// Single-provider router for Anthropic models.+pub struct AnthropicRouter {+ anthropic_client: Arc<anthropic::Client>,+}++impl AnthropicRouter {+ /// Build a router over the given Anthropic client.+ pub fn new(anthropic_client: Arc<anthropic::Client>) -> Self {+ Self { anthropic_client }+ }+}++impl ModelRouter for AnthropicRouter {+ type ModelId = AnthropicModelId;+ type RoutedModel = AnthropicModel;++ /// The id is validated as Anthropic by construction, so binding it to this+ /// router's client cannot fail.+ fn route_model(&self, model: Self::ModelId) -> Self::RoutedModel {+ AnthropicModel::new(self.anthropic_client.clone(), model)+ }+}diff --git a/rust/cloud-storage/agent/src/model/router/openai.rs b/rust/cloud-storage/agent/src/model/router/openai.rsnew file mode 100644index 0000000000..f32375a5bb--- /dev/null+++ b/rust/cloud-storage/agent/src/model/router/openai.rs@@ -0,0 +1,27 @@+use crate::model::openai::{OpenAiModel, OpenAiModelId};+use crate::model::types::ModelRouter;+use rig_core::providers::openai;+use std::sync::Arc;++/// Single-provider router for OpenAI models.+pub struct OpenAiRouter {+ openai_client: Arc<openai::Client>,+}++impl OpenAiRouter {+ /// Build a router over the given OpenAI client.+ pub fn new(openai_client: Arc<openai::Client>) -> Self {+ Self { openai_client }+ }+}++impl ModelRouter for OpenAiRouter {+ type ModelId = OpenAiModelId;+ type RoutedModel = OpenAiModel;++ /// The id is validated as OpenAI by construction, so binding it to this+ /// router's client cannot fail.+ fn route_model(&self, model: Self::ModelId) -> Self::RoutedModel {+ OpenAiModel::new(self.openai_client.clone(), model)+ }+}diff --git a/rust/cloud-storage/agent/src/model/router/test.rs b/rust/cloud-storage/agent/src/model/router/test.rsnew file mode 100644index 0000000000..b52536f87c--- /dev/null+++ b/rust/cloud-storage/agent/src/model/router/test.rs@@ -0,0 +1,89 @@+use crate::model::anthropic::is_anthropic_model;+use crate::model::openai::is_openai_model;++#[test]+fn matches_gpt_family() {+ for id in [+ "gpt-5",+ "gpt-5-mini",+ "gpt-5-nano",+ "gpt-5.1",+ "gpt-5.5",+ "gpt-4o",+ "gpt-4o-mini",+ "gpt-4.1",+ "gpt-4-turbo",+ "gpt-4",+ "gpt-3.5-turbo",+ ] {+ assert!(is_openai_model(id), "{id} should match");+ }+}++#[test]+fn matches_o_series() {+ for id in [+ "o1", "o1-mini", "o1-pro", "o3", "o3-mini", "o3-pro", "o4-mini",+ ] {+ assert!(is_openai_model(id), "{id} should match");+ }+}++#[test]+fn matches_chat_aliases() {+ assert!(is_openai_model("chatgpt-4o-latest"));+ assert!(is_openai_model("chat-latest"));+}++#[test]+fn rejects_anthropic_models() {+ for id in [+ "claude-opus-4-8",+ "claude-sonnet-4-6",+ "claude-haiku-4-5",+ "claude-fable-5",+ "fable",+ "mythos",+ ] {+ assert!(!is_openai_model(id), "{id} should not match");+ }+}++#[test]+fn rejects_empty_and_unrelated() {+ assert!(!is_openai_model(""));+ assert!(!is_openai_model("gemini-2.5-pro"));+ // Anchored at the start: a string merely containing "gpt-" doesn't match.+ assert!(!is_openai_model("my-gpt-5"));+}++#[test]+fn matches_anthropic_models() {+ for id in [+ "claude-opus-4-8",+ "claude-sonnet-4-6",+ "claude-haiku-4-5",+ "claude-fable-5",+ ] {+ assert!(is_anthropic_model(id), "{id} should match");+ }+}++#[test]+fn anthropic_and_openai_namespaces_are_disjoint() {+ for id in ["gpt-5", "o3-mini", "chatgpt-4o-latest", "chat-latest"] {+ assert!(is_openai_model(id) && !is_anthropic_model(id), "{id}");+ }+ for id in ["claude-opus-4-8", "claude-haiku-4-5"] {+ assert!(is_anthropic_model(id) && !is_openai_model(id), "{id}");+ }+}++#[test]+fn anthropic_rejects_unrelated() {+ assert!(!is_anthropic_model(""));+ assert!(!is_anthropic_model("gpt-5"));+ assert!(!is_anthropic_model("gemini-2.5-pro"));+ // Anchored: bare family names without the `claude-` prefix don't match.+ assert!(!is_anthropic_model("opus"));+}diff --git a/rust/cloud-storage/agent/src/model/test.rs b/rust/cloud-storage/agent/src/model/test.rsindex eb9d71ba1d..5f8a6a83e8 100644--- a/rust/cloud-storage/agent/src/model/test.rs+++ b/rust/cloud-storage/agent/src/model/test.rs@@ -1,89 +1,52 @@use super::*;#[test]-fn retired_model_deserializes_to_retired() {- let m: AgentModel = serde_json::from_str(r#""claude-opus-4-6""#).unwrap();- assert_eq!(m, AgentModel::Retired);-}--#[test]-fn smart_deserializes() {- let m: AgentModel = serde_json::from_str(r#""smart""#).unwrap();- assert_eq!(m, AgentModel::Smart);-}--#[test]-fn fast_deserializes() {- let m: AgentModel = serde_json::from_str(r#""fast""#).unwrap();- assert_eq!(m, AgentModel::Fast);+fn default_is_smart() {+ assert_eq!(AgentModel::default(), AgentModel::Smart);}#[test]-fn smart_routes_to_opus() {- assert_eq!(AgentModel::Smart.api_id(), AgentModel::Opus4_7.api_id());+fn smart_is_opus_4_8() {+ assert_eq!(AgentModel::Smart.api_id(), "claude-opus-4-8");+ assert_eq!(+ serde_json::to_string(&AgentModel::Smart).unwrap(),+ r#""claude-opus-4-8""#+ );}#[test]-fn fast_routes_to_haiku() {+fn fast_is_haiku() {+ assert_eq!(AgentModel::Fast.api_id(), "claude-haiku-4-5");assert_eq!(AgentModel::Fast.api_id(), AgentModel::Haiku4_5.api_id());}-#[test]-fn retired_google_model_falls_back() {- let m: AgentModel = serde_json::from_str(r#""gemini-2.5-pro""#).unwrap();- assert_eq!(m, AgentModel::Retired);-}--#[test]-fn retired_openai_model_falls_back() {- let m: AgentModel = serde_json::from_str(r#""gpt-4o""#).unwrap();- assert_eq!(m, AgentModel::Retired);-}-#[test]fn retired_uses_default_api_id() {assert_eq!(AgentModel::Retired.api_id(), AgentModel::Smart.api_id());}#[test]-fn gpt5_5_deserializes() {- let m: AgentModel = serde_json::from_str(r#""gpt5_5""#).unwrap();- assert_eq!(m, AgentModel::Gpt5_5);-}--#[test]-fn gpt5_mini_deserializes() {- let m: AgentModel = serde_json::from_str(r#""gpt5Mini""#).unwrap();- assert_eq!(m, AgentModel::Gpt5Mini);-}--#[test]-fn gpt_models_route_to_openai() {- assert_eq!(AgentModel::Gpt5_5.provider(), ModelProvider::OpenAi);- assert_eq!(AgentModel::Gpt5Mini.provider(), ModelProvider::OpenAi);- assert_eq!(AgentModel::Smart.provider(), ModelProvider::Anthropic);- assert_eq!(AgentModel::Retired.provider(), ModelProvider::Anthropic);-}--#[test]-fn gpt_round_trip_serialization() {- for m in [AgentModel::Gpt5_5, AgentModel::Gpt5Mini] {- let json = serde_json::to_string(&m).unwrap();- let back: AgentModel = serde_json::from_str(&json).unwrap();- assert_eq!(back, m);+fn variants_serialize_to_their_api_id() {+ for m in [+ AgentModel::Smart,+ AgentModel::Fast,+ AgentModel::Opus4_7,+ AgentModel::Sonnet4_6,+ AgentModel::Haiku4_5,+ AgentModel::Gpt5_5,+ AgentModel::Gpt5Mini,+ AgentModel::Retired,+ ] {+ let wire = serde_json::to_string(&m).unwrap();+ assert_eq!(wire, format!(r#""{}""#, m.api_id()), "{m:?}");}}#[test]-fn round_trip_serialization() {- let m = AgentModel::Sonnet4_6;- let json = serde_json::to_string(&m).unwrap();- assert_eq!(json, r#""sonnet4_6""#);- let back: AgentModel = serde_json::from_str(&json).unwrap();- assert_eq!(back, m);-}--#[test]-fn default_is_smart() {- assert_eq!(AgentModel::default(), AgentModel::Smart);+fn providers_are_assigned_correctly() {+ assert_eq!(AgentModel::Gpt5_5.provider(), Provider::OpenAi);+ assert_eq!(AgentModel::Gpt5Mini.provider(), Provider::OpenAi);+ assert_eq!(AgentModel::Smart.provider(), Provider::Anthropic);+ assert_eq!(AgentModel::Fast.provider(), Provider::Anthropic);+ assert_eq!(AgentModel::Retired.provider(), Provider::Anthropic);}diff --git a/rust/cloud-storage/agent/src/model/types.rs b/rust/cloud-storage/agent/src/model/types.rsnew file mode 100644index 0000000000..2cdcbc4886--- /dev/null+++ b/rust/cloud-storage/agent/src/model/types.rs@@ -0,0 +1,27 @@+use rig_core::completion::CompletionModel;++pub trait Model {+ /// The provider-specific completion model this resolves to.+ type Completion: CompletionModel;+ /// Build the completion model used to drive an agent.+ fn completion(&self) -> Self::Completion;+ /// Best-effort reasoning / extended-thinking config, or `None` if the+ /// model doesn't support it.+ fn thinking_params(&self) -> Option<serde_json::Value>;+}++/// Routes a validated, provider-specific model id to a runtime model.+///+/// Routing is infallible: validation lives in the id type. Each router's+/// [`ModelId`](ModelRouter::ModelId) is a newtype whose only constructor checks+/// the id against the provider's namespace (e.g.+/// [`AnthropicModelId`](crate::model::anthropic::AnthropicModelId)), so by the+/// time `route_model` receives one it is guaranteed to belong to this provider.+pub trait ModelRouter {+ /// The validated id type this router accepts.+ type ModelId;+ /// The runtime model this router produces.+ type RoutedModel: Model;+ /// Bind an already-validated id to this router's provider client.+ fn route_model(&self, model: Self::ModelId) -> Self::RoutedModel;+}diff --git a/rust/cloud-storage/agent/src/structured_output.rs b/rust/cloud-storage/agent/src/structured_output.rsindex 2c7ae7b9d0..31b91229c1 100644--- a/rust/cloud-storage/agent/src/structured_output.rs+++ b/rust/cloud-storage/agent/src/structured_output.rs@@ -4,8 +4,6 @@ use rig_core::message::Message;use serde::{Deserialize, Serialize};use utoipa::ToSchema;-use crate::model::AgentModel;-/// Schema definition for dynamic structured completions.#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct DynamicSchema {@@ -20,9 +18,9 @@ pub struct DynamicSchema {/// Run a completion with conversation history and return a JSON value/// conforming to `schema`.-#[tracing::instrument(skip(system_prompt, messages, schema), err)]-pub async fn dynamic_structured_completion(- model: AgentModel,+#[tracing::instrument(skip(model, system_prompt, messages, schema), err)]+pub async fn dynamic_structured_completion<M: ToString>(+ model: M,system_prompt: &str,messages: Vec<Message>,schema: DynamicSchema,diff --git a/rust/cloud-storage/chat/src/domain/models/chat.rs b/rust/cloud-storage/chat/src/domain/models/chat.rsindex 8c2452334f..ac46884b88 100644--- a/rust/cloud-storage/chat/src/domain/models/chat.rs+++ b/rust/cloud-storage/chat/src/domain/models/chat.rs@@ -1,4 +1,3 @@-use agent::AgentModel;use model::chat::ChatMessageWithAttachments;use models_permissions::share_permission::access_level::AccessLevel;use serde::{Deserialize, Serialize};@@ -58,8 +57,8 @@ pub struct ChatResponse {pub name: String,/// The messages in the chat.pub messages: Vec<ChatMessageWithAttachments>,- /// The model used to generate the chat.- pub model: Option<AgentModel>,+ /// The model used to generate the chat (provider api id).+ pub model: Option<String>,/// The time the chat was created.pub created_at: Option<chrono::DateTime<chrono::Utc>>,/// The time the chat was last updated.diff --git a/rust/cloud-storage/chat/src/domain/models/mod.rs b/rust/cloud-storage/chat/src/domain/models/mod.rsindex 53bbd8c4eb..62a4d85502 100644--- a/rust/cloud-storage/chat/src/domain/models/mod.rs+++ b/rust/cloud-storage/chat/src/domain/models/mod.rs@@ -3,7 +3,9 @@mod chat;mod error;mod message;+pub mod model_access;pub use chat::{ChatResponse, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs};pub use error::{ChatErr, Result};pub use message::{PatchChatMessageArgs, ResolvedMessageContent, WebCitation};+pub use model_access::{CHAT_MODELS, FREE_MODEL, ModelAccess, ModelsResponse};diff --git a/rust/cloud-storage/chat/src/domain/models/model_access.rs b/rust/cloud-storage/chat/src/domain/models/model_access.rsnew file mode 100644index 0000000000..6a8290de73--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/models/model_access.rs@@ -0,0 +1,41 @@+//! Model availability for chat, gated by the user's plan.+//!+//! Free (non-professional) users may use only [`FREE_MODEL`]; professional+//! users may use every model in [`CHAT_MODELS`].++use agent::AgentModel;+use serde::Serialize;+use utoipa::ToSchema;++/// The chat models offered to users, best-first.+pub const CHAT_MODELS: &[AgentModel] = &[+ AgentModel::Smart,+ AgentModel::Fast,+ AgentModel::Gpt5_5,+ AgentModel::Gpt5Mini,+];++/// The only model available to free (non-professional) users.+pub const FREE_MODEL: AgentModel = AgentModel::Fast;++/// A chat model paired with whether the requesting user may use it.+#[derive(Debug, Clone, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ModelAccess {+ /// Provider api id — the string sent when this model is selected.+ pub id: String,+ /// Provider serving the model (e.g. `anthropic`, `openai`).+ pub provider: String,+ /// Context window size in tokens.+ pub context_window: u64,+ /// Whether the requesting user has access to this model.+ pub available: bool,+}++/// Response body for the models-access endpoint: every chat model, each+/// flagged with the requesting user's access.+#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct ModelsResponse {+ /// All chat models, in display order.+ pub models: Vec<ModelAccess>,+}diff --git a/rust/cloud-storage/chat/src/domain/ports/mod.rs b/rust/cloud-storage/chat/src/domain/ports/mod.rsindex 1126cac92f..32e25d3fe1 100644--- a/rust/cloud-storage/chat/src/domain/ports/mod.rs+++ b/rust/cloud-storage/chat/src/domain/ports/mod.rs@@ -1,5 +1,7 @@mod chat;mod message;+mod model_access;pub use chat::{ChatRepo, ChatService};pub use message::{MessageRepo, MessageService};+pub use model_access::ModelAccessService;diff --git a/rust/cloud-storage/chat/src/domain/ports/model_access.rs b/rust/cloud-storage/chat/src/domain/ports/model_access.rsnew file mode 100644index 0000000000..74a52c516a--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/ports/model_access.rs@@ -0,0 +1,17 @@+use crate::domain::models::ModelsResponse;++/// Decides which chat models a user may use, based on whether they are a+/// professional (paid) user.+///+/// Pure domain logic with no I/O, so it can be called directly (e.g. from DCS+/// to validate a requested model) or served over HTTP.+pub trait ModelAccessService: Send + Sync + 'static {+ /// List every chat model, each flagged with whether a `professional`+ /// (`true`) or free (`false`) user may use it.+ fn list_models(&self, professional: bool) -> ModelsResponse;++ /// Whether a `professional` (`true`) or free (`false`) user may use the+ /// model identified by `model_id` (a provider api id). Unknown ids return+ /// `false`.+ fn has_access(&self, professional: bool, model_id: &str) -> bool;+}diff --git a/rust/cloud-storage/chat/src/domain/service/mod.rs b/rust/cloud-storage/chat/src/domain/service/mod.rsindex 28c6f0f39a..e44b3f0c4c 100644--- a/rust/cloud-storage/chat/src/domain/service/mod.rs+++ b/rust/cloud-storage/chat/src/domain/service/mod.rs@@ -2,6 +2,8 @@mod chat;mod message;+mod model_access;pub use chat::ChatServiceImpl;pub use message::MessageServiceImpl;+pub use model_access::ModelAccessServiceImpl;diff --git a/rust/cloud-storage/chat/src/domain/service/model_access.rs b/rust/cloud-storage/chat/src/domain/service/model_access.rsnew file mode 100644index 0000000000..fb275f8043--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/service/model_access.rs@@ -0,0 +1,39 @@+use agent::AgentModel;++use crate::domain::models::model_access::{CHAT_MODELS, FREE_MODEL, ModelAccess, ModelsResponse};+use crate::domain::ports::ModelAccessService;++/// Default [`ModelAccessService`]: free users get only [`FREE_MODEL`],+/// professional users get every model in [`CHAT_MODELS`].+#[derive(Debug, Default, Clone, Copy)]+pub struct ModelAccessServiceImpl;++impl ModelAccessServiceImpl {+ fn available(model: AgentModel, professional: bool) -> bool {+ professional || model.api_id() == FREE_MODEL.api_id()+ }+}++impl ModelAccessService for ModelAccessServiceImpl {+ fn list_models(&self, professional: bool) -> ModelsResponse {+ let models = CHAT_MODELS+ .iter()+ .map(|&model| ModelAccess {+ id: model.api_id().to_owned(),+ provider: model.provider().as_str().to_owned(),+ context_window: model.context_window(),+ available: Self::available(model, professional),+ })+ .collect();+ ModelsResponse { models }+ }++ fn has_access(&self, professional: bool, model_id: &str) -> bool {+ CHAT_MODELS+ .iter()+ .any(|&model| model.api_id() == model_id && Self::available(model, professional))+ }+}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/chat/src/domain/service/model_access/test.rs b/rust/cloud-storage/chat/src/domain/service/model_access/test.rsnew file mode 100644index 0000000000..e36a2fa76e--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/service/model_access/test.rs@@ -0,0 +1,42 @@+use super::*;++const HAIKU: &str = "claude-haiku-4-5";+const OPUS: &str = "claude-opus-4-8";++#[test]+fn free_user_only_has_haiku() {+ let svc = ModelAccessServiceImpl;+ assert!(svc.has_access(false, HAIKU));+ assert!(!svc.has_access(false, OPUS));+ assert!(!svc.has_access(false, "gpt-5.5"));+}++#[test]+fn professional_user_has_everything() {+ let svc = ModelAccessServiceImpl;+ assert!(svc.has_access(true, HAIKU));+ assert!(svc.has_access(true, OPUS));+ assert!(svc.has_access(true, "gpt-5.5"));+ assert!(svc.has_access(true, "gpt-5-mini"));+}++#[test]+fn unknown_model_is_never_accessible() {+ let svc = ModelAccessServiceImpl;+ assert!(!svc.has_access(true, "claude-sonnet-4-6"));+ assert!(!svc.has_access(true, "not-a-model"));+}++#[test]+fn list_flags_availability_per_plan() {+ let svc = ModelAccessServiceImpl;++ let free = svc.list_models(false);+ assert_eq!(free.models.len(), CHAT_MODELS.len());+ for m in &free.models {+ assert_eq!(m.available, m.id == HAIKU, "{}", m.id);+ }++ let pro = svc.list_models(true);+ assert!(pro.models.iter().all(|m| m.available));+}diff --git a/rust/cloud-storage/chat/src/inbound/http/extractors.rs b/rust/cloud-storage/chat/src/inbound/http/extractors.rsindex fbffd69c89..67c8e35165 100644--- a/rust/cloud-storage/chat/src/inbound/http/extractors.rs+++ b/rust/cloud-storage/chat/src/inbound/http/extractors.rs@@ -1,5 +1,8 @@//! Axum extractors for chat inbound handlers.+use crate::domain::models::FREE_MODEL;+use crate::domain::ports::ModelAccessService;+use crate::domain::service::ModelAccessServiceImpl;use agent::AgentModel;use axum::extract::FromRequestParts;use axum::http::StatusCode;@@ -7,22 +10,46 @@ use axum::http::request::Parts;use axum::response::IntoResponse;use model::user::UserContext;use roles_and_permissions::domain::model::PermissionId;-use std::collections::HashSet;-/// Axum extractor that resolves the AI model a user is entitled to based on-/// their permissions.+/// Axum extractor resolving the requesting user's model entitlement from their+/// permissions.///-/// Paid users get their highest subscribed model. Free users get Haiku.-#[derive(Debug)]-pub struct ChatModelAccess(AgentModel);+/// Free users may use only [`FREE_MODEL`] (Haiku); professional (paid) users+/// may use every chat model. Backed by [`ModelAccessServiceImpl`].+#[derive(Debug, Clone, Copy)]+pub struct ChatModelAccess {+ professional: bool,+}impl ChatModelAccess {- /// Returns the resolved model.+ /// Whether the user holds the professional (paid) entitlement.+ pub fn professional(&self) -> bool {+ self.professional+ }++ /// Whether the user may use the model identified by `model_id` (an api id).+ pub fn has_access(&self, model_id: &str) -> bool {+ ModelAccessServiceImpl.has_access(self.professional, model_id)+ }++ /// The default model for this user — the best one they're entitled to.pub fn model(&self) -> AgentModel {- self.0+ if self.professional {+ AgentModel::Smart+ } else {+ FREE_MODEL+ }}}+/// Whether the user holds the professional (paid) entitlement, derived from the+/// existing roles-and-permissions access API.+fn is_professional(user: &UserContext) -> bool {+ user.permissions+ .as_ref()+ .is_some_and(|perms| perms.contains(&PermissionId::ReadProfessionalFeatures.to_string()))+}+/// Error returned when [`ChatModelAccess`] cannot be extracted.pub enum ChatModelAccessRejection {/// The `UserContext` extension was missing (middleware not applied).@@ -39,20 +66,6 @@ impl IntoResponse for ChatModelAccessRejection {}}-fn model_for_permissions(permissions: Option<&HashSet<String>>) -> AgentModel {- let Some(permissions) = permissions else {- return AgentModel::Haiku4_5;- };-- if permissions.contains(&PermissionId::WriteOpus.to_string()) {- AgentModel::Opus4_7- } else if permissions.contains(&PermissionId::WriteSonnet.to_string()) {- AgentModel::Sonnet4_6- } else {- AgentModel::Haiku4_5- }-}-impl<S: Send + Sync> FromRequestParts<S> for ChatModelAccess {type Rejection = ChatModelAccessRejection;@@ -62,9 +75,9 @@ impl<S: Send + Sync> FromRequestParts<S> for ChatModelAccess {.get::<UserContext>().ok_or(ChatModelAccessRejection::MissingUserContext)?;- Ok(ChatModelAccess(model_for_permissions(- user_context.permissions.as_ref(),- )))+ Ok(ChatModelAccess {+ professional: is_professional(user_context),+ })}}@@ -72,56 +85,52 @@ impl<S: Send + Sync> FromRequestParts<S> for ChatModelAccess {mod test {use super::*;- fn permissions(values: &[PermissionId]) -> HashSet<String> {- values.iter().map(ToString::to_string).collect()+ fn access(permissions: &[PermissionId]) -> ChatModelAccess {+ let professional = permissions.contains(&PermissionId::ReadProfessionalFeatures);+ ChatModelAccess { professional }}- #[test]- fn missing_permissions_resolve_to_haiku() {- assert_eq!(model_for_permissions(None), AgentModel::Haiku4_5);+ fn user(permissions: &[PermissionId]) -> UserContext {+ UserContext {+ permissions: Some(permissions.iter().map(ToString::to_string).collect()),+ ..Default::default()+ }}#[test]- fn empty_permissions_resolve_to_haiku() {- let permissions = HashSet::new();-- assert_eq!(- model_for_permissions(Some(&permissions)),- AgentModel::Haiku4_5- );+ fn no_permissions_is_free() {+ assert!(!is_professional(&UserContext::default()));+ assert!(!is_professional(&user(&[])));}#[test]- fn haiku_permission_resolves_to_haiku() {- let permissions = permissions(&[PermissionId::WriteHaiku]);-- assert_eq!(- model_for_permissions(Some(&permissions)),- AgentModel::Haiku4_5- );+ fn professional_permission_is_professional() {+ assert!(is_professional(&user(&[+ PermissionId::ReadProfessionalFeatures+ ])));}#[test]- fn sonnet_permission_resolves_to_sonnet() {- let permissions = permissions(&[PermissionId::WriteHaiku, PermissionId::WriteSonnet]);+ fn free_user_defaults_to_haiku_and_only_has_haiku() {+ let free = access(&[]);+ assert_eq!(free.model(), FREE_MODEL);+ assert!(free.has_access(FREE_MODEL.api_id()));+ assert!(!free.has_access(AgentModel::Smart.api_id()));+ }- assert_eq!(- model_for_permissions(Some(&permissions)),- AgentModel::Sonnet4_6- );+ #[test]+ fn professional_user_defaults_to_smart_and_has_everything() {+ let pro = access(&[PermissionId::ReadProfessionalFeatures]);+ assert_eq!(pro.model(), AgentModel::Smart);+ assert!(pro.has_access(AgentModel::Smart.api_id()));+ assert!(pro.has_access(FREE_MODEL.api_id()));}+ // Permission strings unrelated to the professional flag don't grant access.#[test]- fn opus_permission_resolves_to_opus() {- let permissions = permissions(&[- PermissionId::WriteHaiku,- PermissionId::WriteSonnet,- PermissionId::WriteOpus,- ]);-- assert_eq!(- model_for_permissions(Some(&permissions)),- AgentModel::Opus4_7- );+ fn unrelated_permissions_stay_free() {+ let acc = access(&[PermissionId::WriteHaiku, PermissionId::WriteOpus]);+ assert!(!acc.professional());+ assert!(!acc.has_access(AgentModel::Smart.api_id()));}}diff --git a/rust/cloud-storage/chat/src/inbound/http/mod.rs b/rust/cloud-storage/chat/src/inbound/http/mod.rsindex 17f47c715a..30f4c2da7a 100644--- a/rust/cloud-storage/chat/src/inbound/http/mod.rs+++ b/rust/cloud-storage/chat/src/inbound/http/mod.rs@@ -1,4 +1,5 @@//! HTTP-specific inbound adapters: routers, handlers, and extractors.pub mod extractors;+pub mod models;pub mod router;diff --git a/rust/cloud-storage/chat/src/inbound/http/models.rs b/rust/cloud-storage/chat/src/inbound/http/models.rsnew file mode 100644index 0000000000..1b6fe1111c--- /dev/null+++ b/rust/cloud-storage/chat/src/inbound/http/models.rs@@ -0,0 +1,36 @@+//! HTTP endpoint exposing the per-user model access list.++use std::sync::Arc;++use axum::{Json, Router, extract::State, routing::get};++use crate::domain::models::ModelsResponse;+use crate::domain::ports::ModelAccessService;+use crate::inbound::http::extractors::ChatModelAccess;++/// Build the `GET /models` router backed by `service`.+pub fn models_router<M: ModelAccessService, T: Send + Sync + 'static>(service: M) -> Router<T> {+ Router::new()+ .route("/models", get(list_models_handler::<M>))+ .with_state(Arc::new(service))+}++#[utoipa::path(+ get,+ path = "/chats/models",+ tag = "chats",+ operation_id = "list_models",+ responses(+ (status = 200, body = ModelsResponse),+ (status = 500, body = String),+ )+)]+/// List all chat models, each flagged with whether the requesting user has+/// access (free users get Haiku; professional users get everything).+#[tracing::instrument(skip(service, access))]+pub async fn list_models_handler<M: ModelAccessService>(+ State(service): State<Arc<M>>,+ access: ChatModelAccess,+) -> Json<ModelsResponse> {+ Json(service.list_models(access.professional()))+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/mod.rs b/rust/cloud-storage/chat/src/outbound/postgres/mod.rsindex e44ee21f93..8e7fa6d4d9 100644--- a/rust/cloud-storage/chat/src/outbound/postgres/mod.rs+++ b/rust/cloud-storage/chat/src/outbound/postgres/mod.rs@@ -9,7 +9,6 @@ use crate::domain::models::{Result, WebCitation,};use crate::domain::ports::{ChatRepo, MessageRepo};-use agent::AgentModel;use agent::types::ChatMessageContent;use attachment::FormattedParts;use macro_user_id::cowlike::CowLike;@@ -20,9 +19,6 @@ use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::access_level::AccessLevel;use sqlx::PgPool;-/// The default model used when no model is set on a chat.-const FALLBACK_MODEL: AgentModel = AgentModel::Haiku4_5;-/// Convert an [`anyhow::Error`] to a [`ChatErr`], detecting `sqlx::RowNotFound`.fn to_chat_err(e: anyhow::Error) -> ChatErr {if e.downcast_ref::<sqlx::Error>()@@ -128,7 +124,7 @@ impl ChatRepo for PgChatRepo {id: chat.id,user_id: chat.user_id,name: chat.name,- model: Some(FALLBACK_MODEL),+ model: chat.model,messages,project_id: chat.project_id,created_at: chat.created_at,diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rsindex 33c8dd9764..e98b4e6478 100644--- a/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs@@ -6,7 +6,8 @@ use axum::{Router,routing::{get, post},};-use chat::domain::service::ChatServiceImpl;+use chat::domain::service::{ChatServiceImpl, ModelAccessServiceImpl};+use chat::inbound::http::models::models_router;use chat::inbound::http::router::{ChatRouterState, chat_create_router, chat_id_router};use chat::outbound::postgres::PgChatRepo;use entity_access::domain::service::EntityAccessServiceImpl;@@ -62,6 +63,19 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {.layer(ensure_chat_exists.clone()),),)+ // Per-user model access list — needs user + permissions populated.+ .merge(+ models_router(ModelAccessServiceImpl).layer(+ ServiceBuilder::new()+ .layer(axum::middleware::from_fn(+ macro_middleware::auth::ensure_user_exists::handler,+ ))+ .layer(axum::middleware::from_fn_with_state(+ state.clone(),+ macro_middleware::user_permissions::attach_user_permissions::handler,+ )),+ ),+ )// History routes — remain in DCS.route("/history/{chat_id}",diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rsindex eca85e96df..e85654b396 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs@@ -11,7 +11,6 @@ use crate::service::ai_stream_registry::CancellationSubscription;use crate::service::chat_renamer::spawn_initial_chat_rename;use crate::service::get_chat::get_chat;use crate::service::notification::notify;-use agent::AgentModel;use agent::types::{AssistantMessagePart, ChatMessage, ChatMessageContent};use agent::{AgentLoop, StreamAccumulator};use async_stream::stream;@@ -73,8 +72,8 @@ pub struct HttpSendChatMessageRequest {pub content: String,/// Id of the chat the message belongs to (optional - if not provided, a new chat is created)pub chat_id: Option<String>,- /// The model to respond with- pub model: AgentModel,+ /// The model to respond with (provider api id)+ pub model: String,/// Additional system instructions appended to the base system prompt#[serde(skip_serializing_if = "Option::is_none")]pub additional_instructions: Option<String>,@@ -180,12 +179,21 @@ async fn send_chat_message_inner(// Determine chat_id - use provided or we'll create a new chatlet requested_chat_id = request.chat_id.clone().unwrap_or_default();- let model = model_access.model();+ // The frontend selects the model; enforce the user's entitlement here.+ // Free users get Haiku; professional users get everything.+ if !model_access.has_access(&request.model) {+ return Err(ChatMessageError {+ error: format!("No access to model {}", request.model),+ stream_id: Some(stream_id.clone()),+ status: Some(StatusCode::FORBIDDEN),+ });+ }+ let model = request.model.clone();// Try to get the chat first - if it doesn't exist or no chat_id provided, create itlet (chat, actual_chat_id, created_new_chat) = if requested_chat_id.is_empty() {// No chat_id provided - create a new chat- let (chat, chat_id) = create_new_chat(&ctx, &user_id, model, &stream_id).await?;+ let (chat, chat_id) = create_new_chat(&ctx, &user_id, &model, &stream_id).await?;(chat, chat_id, true)} else {match get_chat(&ctx, &requested_chat_id, user_id.0.as_ref()).await {@@ -225,7 +233,7 @@ async fn send_chat_message_inner(requested_chat_id = %requested_chat_id,"Chat not found, creating new chat");- let (chat, chat_id) = create_new_chat(&ctx, &user_id, model, &stream_id).await?;+ let (chat, chat_id) = create_new_chat(&ctx, &user_id, &model, &stream_id).await?;(chat, chat_id, true)}}@@ -237,7 +245,7 @@ async fn send_chat_message_inner(stream_id: stream_id.clone(),content: request.content.clone(),chat_id: actual_chat_id.clone(),- model,+ model: model.clone(),additional_instructions: request.additional_instructions.clone(),attachments: request.attachments.clone(),toolset: request.toolset.clone(),@@ -247,7 +255,7 @@ async fn send_chat_message_inner(};// Store the incoming user message and resolve its attachments- let resolved = store_incoming_message(ctx.clone(), user_id.0.as_ref(), &chat, model, &payload)+ let resolved = store_incoming_message(ctx.clone(), user_id.0.as_ref(), &chat, &model, &payload).await.map_err(|err| {tracing::error!(error=?err, "failed to store incoming message");@@ -301,7 +309,7 @@ async fn send_chat_message_inner(})?;// Log time to send request- log::log_timing(log::LatencyMetric::TimeToSendRequest, model, now.elapsed());+ log::log_timing(log::LatencyMetric::TimeToSendRequest, &model, now.elapsed());// Create stream ID for publishinglet durable_stream_id = StreamId {@@ -359,7 +367,7 @@ async fn send_chat_message_inner(async fn create_new_chat(ctx: &Arc<ApiContext>,user_id: &Arc<MacroUserIdStr<'static>>,- model: AgentModel,+ model: &str,stream_id: &str,) -> Result<(crate::model::chats::ChatResponse, String), ChatMessageError> {let share_permission = SharePermissionV2::new_chat_share_permission();@@ -462,7 +470,7 @@ fn stream_and_save_message(chat_id: String,message_id: String,stream_id: String,- model: AgentModel,+ model: String,now: std::time::Instant,user_message_content: String,user_message_id: String,@@ -504,7 +512,7 @@ fn stream_and_save_message(let toolset: Arc<dyn ai_toolset::ToolSet<_> + Send + Sync> = Arc::new(mcp_client::domain::service::CombinedToolSet::new(static_tools, &mcp_records).await,);- let agent_loop = AgentLoop::new();+ let agent_loop = AgentLoop::new().with_model(&model);let rig_messages = agent::to_rig_messages(&request);let mut session = agent_loop.session(toolset, Arc::new(tool_context), &system_prompt, user_id.clone())@@ -560,7 +568,7 @@ fn stream_and_save_message(if !is_first_token {is_first_token = true;- log::log_timing(log::LatencyMetric::TimeToFirstToken, model, now.elapsed());+ log::log_timing(log::LatencyMetric::TimeToFirstToken, &model, now.elapsed());}match response {@@ -632,7 +640,7 @@ fn stream_and_save_message(user_id.0.as_ref(),&chat_id,new_messages,- model,+ &model,Some(message_id.clone()),).awaitdiff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/mod.rsindex 422ce7b5df..520adc9ea3 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/mod.rs@@ -7,7 +7,6 @@ use crate::{model::stream::SendChatMessagePayload,};-use agent::AgentModel;use agent::types::Role;use agent::types::{ChatMessage, ChatMessageContent};use anyhow::{Context, Result};@@ -23,7 +22,7 @@ pub async fn store_incoming_message(ctx: Arc<ApiContext>,user_id: &str,chat: &ChatResponse,- model: AgentModel,+ model: &str,incoming_message: &SendChatMessagePayload,) -> Result<ResolvedMessageContent> {let created_at = chrono::Utc::now();@@ -52,7 +51,7 @@ pub async fn store_incoming_message(}),created_at,updated_at: created_at,- model,+ model: model.to_string(),};let user_id: macro_user_id::user_id::MacroUserIdStr<'static> =@@ -83,7 +82,7 @@ pub async fn store_conversation_messages(user_id: &str,chat_id: &str,messages: Vec<ChatMessage>,- model: AgentModel,+ model: &str,first_message_id: Option<String>,) -> Result<Vec<String>> {if messages.is_empty() {@@ -108,7 +107,7 @@ pub async fn store_conversation_messages(content: message.content,role: message.role,attachments: None,- model,+ model: model.to_string(),created_at,updated_at: created_at,};diff --git a/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs b/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rsindex 57e629a307..1a43d3459a 100644--- a/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs@@ -2,7 +2,7 @@ use crate::api::context::ApiContext;use crate::model::stream::ToolSet;use agent::structured_output::DynamicSchema;use agent::types::{ChatMessage, ChatMessageContent, Role};-use agent::{AgentLoop, AgentModel, StreamAccumulator};+use agent::{AgentLoop, StreamAccumulator};use axum::Json;use axum::extract::{Extension, State};use axum::http::StatusCode;@@ -20,7 +20,7 @@ use utoipa::ToSchema;#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct StructuredCompletionRequest {pub prompt: String,- pub model: AgentModel,+ pub model: String,pub output_schema: DynamicSchema,#[serde(skip_serializing_if = "Option::is_none")]pub additional_instructions: Option<String>,diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rsindex b29b057726..019cd73162 100644--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs@@ -17,7 +17,6 @@ use crate::model::{response::attachments::GetChatsForAttachmentResponse,stream::{ChatStream, SendChatMessagePayload, StreamError, ToolSet},};-use agent::AgentModel;use mcp_client::inbound::axum_router::{self as mcp_api, AddServerRequest, ServerResponse, StartAuthRequest, StartAuthResponse,UpdateServerRequest,@@ -26,7 +25,10 @@ use memory::inbound::axum_router::{self as memory_api, MemoryErrorBody, MemoryReuse crate::api::preview::get_batch_preview::{GetBatchPreviewRequest, GetBatchPreviewResponse};-use chat::domain::models::{ChatResponse, GetChatResponse, WebCitation};+use chat::domain::models::{+ ChatResponse, GetChatResponse, ModelAccess, ModelsResponse, WebCitation,+};+use chat::inbound::http::models as chat_models;use chat::inbound::http::router::{self as chat_router, CallToolRequest, CallToolResponse, CreateChatRequest,GetChatPermissionsResponse, PatchChatRequest, RejectToolCallRequest, UpdateToolCallRequest,@@ -71,6 +73,7 @@ use utoipa::OpenApi;chat_router::update_tool_response_handler,chat_router::call_tool_handler,chat_router::reject_tool_call_handler,+ chat_models::list_models_handler,get_chats_for_attachment::get_chats_for_attachment_handler,citations::get_citation_handler,get_batch_preview::handler,@@ -90,7 +93,8 @@ use utoipa::OpenApi;components(schemas(DocumentCognitionServiceApiVersion,- AgentModel,+ ModelAccess,+ ModelsResponse,// GenericStringIDResponse,GenericErrorResponse,diff --git a/rust/cloud-storage/document_cognition_service/src/api/utils/log.rs b/rust/cloud-storage/document_cognition_service/src/api/utils/log.rsindex a039a204c1..1584c453e9 100644--- a/rust/cloud-storage/document_cognition_service/src/api/utils/log.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/utils/log.rs@@ -1,4 +1,3 @@-use agent::AgentModel;use std::time::Duration;use strum::{Display, EnumString};@@ -9,7 +8,7 @@ pub enum LatencyMetric {TimeToFirstToken,}-pub fn log_timing(metric: LatencyMetric, model: AgentModel, duration: Duration) {+pub fn log_timing(metric: LatencyMetric, model: &str, duration: Duration) {tracing::info!(metric = %metric,model_name = %model,diff --git a/rust/cloud-storage/document_cognition_service/src/core/model.rs b/rust/cloud-storage/document_cognition_service/src/core/model.rsindex 6c5eda7af6..e01271fbbf 100644--- a/rust/cloud-storage/document_cognition_service/src/core/model.rs+++ b/rust/cloud-storage/document_cognition_service/src/core/model.rs@@ -1,9 +1,6 @@use agent::AgentModel;-pub static CHAT_MODELS: &[AgentModel] = &[- AgentModel::Smart,- AgentModel::Fast,- AgentModel::Gpt5_5,- AgentModel::Gpt5Mini,-];+/// Chat models offered to users — single source of truth lives in the chat crate.+pub use chat::domain::models::CHAT_MODELS;+pub static FALLBACK_MODEL: AgentModel = AgentModel::Haiku4_5;diff --git a/rust/cloud-storage/document_cognition_service/src/model/chats.rs b/rust/cloud-storage/document_cognition_service/src/model/chats.rsindex 81e50e0b89..0545a0bbff 100644--- a/rust/cloud-storage/document_cognition_service/src/model/chats.rs+++ b/rust/cloud-storage/document_cognition_service/src/model/chats.rs@@ -1,5 +1,4 @@#![allow(deprecated)]-use agent::AgentModel;use model::chat::ChatMessageWithAttachments;use model_entity::Entity;use serde::{Deserialize, Serialize};@@ -19,8 +18,8 @@ pub struct ChatResponse {pub name: String,/// The messages in the chatpub messages: Vec<ChatMessageWithAttachments>,- /// The model used to generate the chat- pub model: Option<AgentModel>,+ /// The model used to generate the chat (provider api id)+ pub model: Option<String>,/// The time the chat was createdpub created_at: Option<chrono::DateTime<chrono::Utc>>,/// The time the chat was last updated@@ -31,9 +30,9 @@ pub struct ChatResponse {/// Current number of tokens in the chat// killpub token_count: Option<i64>,- /// Available models for the chat+ /// Available models for the chat (provider api ids)// kill- pub available_models: Vec<AgentModel>,+ pub available_models: Vec<String>,/// message_id - web citation list// killpub web_citations: Vec<(String, Vec<GetUnfurlResponse>)>,diff --git a/rust/cloud-storage/document_cognition_service/src/model/stream.rs b/rust/cloud-storage/document_cognition_service/src/model/stream.rsindex 8028eb819d..51b3db4cc0 100644--- a/rust/cloud-storage/document_cognition_service/src/model/stream.rs+++ b/rust/cloud-storage/document_cognition_service/src/model/stream.rs@@ -1,4 +1,3 @@-use agent::AgentModel;use agent::types::AssistantMessagePart;use model_entity::Entity;use serde::{Deserialize, Serialize};@@ -25,8 +24,8 @@ pub struct SendChatMessagePayload {pub content: String,/// Id of the chat the message belongs topub chat_id: String,- /// the chate model to respond with- pub model: AgentModel,+ /// the chat model to respond with (provider api id)+ pub model: String,/// Additional system instructions appended to the base system prompt#[serde(skip_serializing_if = "Option::is_none")]pub additional_instructions: Option<String>,@@ -73,10 +72,7 @@ pub enum ChatStream {#[serde(rename_all = "snake_case", tag = "stream_error")]pub enum StreamError {#[error("provider error")]- ProviderError {- stream_id: String,- model: AgentModel,- },+ ProviderError { stream_id: String, model: String },#[error("model context overflow")]ModelContextOverflow { stream_id: String },diff --git a/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs b/rust/cloud-storage/document_cognition_service/src/service/get_chat.rsindex 51759ad97c..2e2bbe17d8 100644--- a/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs+++ b/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs@@ -20,7 +20,7 @@ pub async fn get_chat(.await.context("Failed to get messages")?;- let model = Some(FALLBACK_MODEL);+ let model = Some(FALLBACK_MODEL.to_string());let web_citations = get_web_citations(&ctx.db, chat_id).await@@ -54,7 +54,7 @@ pub async fn get_chat(updated_at: chat.updated_at,attachments: vec![],token_count: chat.token_count,- available_models: CHAT_MODELS.to_vec(),+ available_models: CHAT_MODELS.iter().map(|m| m.to_string()).collect(),web_citations,is_persistent: chat.is_persistent,})diff --git a/rust/cloud-storage/macro_db_client/src/dcs/create_chat.rs b/rust/cloud-storage/macro_db_client/src/dcs/create_chat.rsindex 01ee18a2fd..e2a7aa626d 100644--- a/rust/cloud-storage/macro_db_client/src/dcs/create_chat.rs+++ b/rust/cloud-storage/macro_db_client/src/dcs/create_chat.rs@@ -1,6 +1,5 @@use super::append_attachment_to_chat::append_attachment_to_chat;use crate::history::{upsert_item_last_accessed, upsert_user_history};-use agent::AgentModel;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::{IDWithTimeStamps, chat::NewChatAttachment};use model_entity::EntityType;@@ -15,7 +14,7 @@ pub async fn create_chat_v2(db: &Pool<Postgres>,user_id: MacroUserIdStr<'static>,name: &str,- model: AgentModel,+ model: &str,project_id: Option<&str>,share_permission: &SharePermissionV2,attachments: Vec<NewChatAttachment>,@@ -34,7 +33,7 @@ pub async fn create_chat_v2("#,user_id.as_ref(),&name,- model.to_string(),+ model,project_id,is_persistent)diff --git a/rust/cloud-storage/model/src/chat/message.rs b/rust/cloud-storage/model/src/chat/message.rsindex 099b287d30..774452646b 100644--- a/rust/cloud-storage/model/src/chat/message.rs+++ b/rust/cloud-storage/model/src/chat/message.rs@@ -1,5 +1,4 @@use super::NewAttachment;-use agent::AgentModel;use agent::types::{ChatMessageContent, Role};use chrono::{DateTime, Utc};use model_entity::Entity;@@ -44,8 +43,8 @@ pub struct NewChatMessage {pub role: Role,/// The ids of the attachments used to generate the messagepub attachments: Option<Vec<NewAttachment>>,- /// The model used to generate the chat- pub model: AgentModel,+ /// The model used to generate the chat (provider api id)+ pub model: String,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,}diff --git a/rust/cloud-storage/scheduled_action/src/domain/models.rs b/rust/cloud-storage/scheduled_action/src/domain/models.rsindex 6ff915cf24..22851d829e 100644--- a/rust/cloud-storage/scheduled_action/src/domain/models.rs+++ b/rust/cloud-storage/scheduled_action/src/domain/models.rs@@ -1,4 +1,3 @@-use agent::AgentModel;use anyhow::Result;use chrono::{DateTime, Duration, Utc};use chrono_tz::Tz;@@ -57,7 +56,7 @@ pub enum ActionKind {#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]pub struct AgentTask {- pub model: AgentModel,+ pub model: String,pub prompt: String,pub user_prompt: String,}diff --git a/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rsindex 5e0a9730ef..9ec7f5880b 100644--- a/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs+++ b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs@@ -104,7 +104,7 @@ async fn store_user_message(db: &PgPool, chat_id: &str, agent_task: &AgentTask)attachments: None,created_at: now,updated_at: now,- model: agent_task.model,+ model: agent_task.model.clone(),};create_chat_message(db.clone(), chat_id, message).await}@@ -129,7 +129,7 @@ async fn run_tool_loop(};let toolset: Arc<dyn AiToolSet<_> + Send + Sync> = tools.toolset;- let agent_loop = AgentLoop::new().with_model(agent_task.model);+ let agent_loop = AgentLoop::new().with_model(&agent_task.model);let mut session = agent_loop.session(toolset,@@ -190,7 +190,7 @@ async fn store_conversation(attachments: None,created_at: now,updated_at: now,- model: agent_task.model,+ model: agent_task.model.clone(),};create_chat_message(db.clone(), chat_id, message).awaitdiff --git a/rust/cloud-storage/workspace-hack/Cargo.toml b/rust/cloud-storage/workspace-hack/Cargo.tomlindex 844e646823..604aa597b7 100644--- a/rust/cloud-storage/workspace-hack/Cargo.toml+++ b/rust/cloud-storage/workspace-hack/Cargo.toml@@ -86,7 +86,6 @@ prost = { version = "0.12", features = ["prost-derive"] }rand-274715c4dabd11b0 = { package = "rand", version = "0.9" }rand-c38e5c1d305a1b54 = { package = "rand", version = "0.8", features = ["small_rng"] }redis = { version = "1", features = ["cluster-async", "tokio-rustls-comp"] }-regex = { version = "1" }regex-automata = { version = "0.4", default-features = false, features = ["dfa-build", "dfa-onepass", "hybrid", "meta", "nfa-backtrack", "perf-inline", "perf-literal", "std", "unicode"] }regex-syntax = { version = "0.8" }reqwest = { version = "0.13", features = ["form", "gzip", "hickory-dns", "json", "multipart", "query", "stream"] }@@ -206,7 +205,6 @@ quote = { version = "1" }rand-274715c4dabd11b0 = { package = "rand", version = "0.9" }rand-c38e5c1d305a1b54 = { package = "rand", version = "0.8", features = ["small_rng"] }redis = { version = "1", features = ["cluster-async", "tokio-rustls-comp"] }-regex = { version = "1" }regex-automata = { version = "0.4", default-features = false, features = ["dfa-build", "dfa-onepass", "hybrid", "meta", "nfa-backtrack", "perf-inline", "perf-literal", "std", "unicode"] }regex-syntax = { version = "0.8" }reqwest = { version = "0.13", features = ["form", "gzip", "hickory-dns", "json", "multipart", "query", "stream"] }