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
fix(ai): unchud model routing (#4273)
Eric Hayes9476d1de64e6
diff --git a/docker-compose.yml b/docker-compose.ymlindex 249a02ca30..2802e447a3 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -232,6 +232,8 @@ services:command: ["/app/out/notification_service"]ports:- "8089:8080"+ environment:+ LAST_ONLINE_REDIS_URI: ${LAST_ONLINE_REDIS_URI:-${REDIS_URI:-redis://redis:6379}}depends_on:- redis- document_cognition_servicediff --git a/flake.lock b/flake.lockindex d4f9839c3a..d3230bdfb6 100644--- a/flake.lock+++ b/flake.lock@@ -2,11 +2,11 @@"nodes": {"crane": {"locked": {- "lastModified": 1777335812,- "narHash": "sha256-bEg5xoAxAwsyfnGhkEX7RJViTIBIYPd8ISg4O1c0HFc=",+ "lastModified": 1781825982,+ "narHash": "sha256-SlXKwIRIhrOSAcTjCB3ftPLzJWZStQIPS7J1FlZPnKk=","owner": "ipetkov","repo": "crane",- "rev": "5e0fb2f64edff2822249f21293b8304dedaaf676",+ "rev": "469fd08d0bcf6926321fa973c6777fbc87785dd7","type": "github"},"original": {@@ -23,11 +23,11 @@"rust-analyzer-src": "rust-analyzer-src"},"locked": {- "lastModified": 1777488689,- "narHash": "sha256-UYE+SRTDdhXz/y9wmtibVyNapdQF7KCKa1w0Aw3bT7U=",+ "lastModified": 1782131086,+ "narHash": "sha256-M73jIp606F878X6bq/dQ11IRmAwd+/ssdK+7qvr50vo=","owner": "nix-community","repo": "fenix",- "rev": "ed56ade264bdc3294f457b472cb0482fc36f105c",+ "rev": "309fb007facc8caa25c99413502b38fddb3ffdc2","type": "github"},"original": {@@ -56,11 +56,11 @@},"nixpkgs": {"locked": {- "lastModified": 1777268161,- "narHash": "sha256-bxrdOn8SCOv8tN4JbTF/TXq7kjo9ag4M+C8yzzIRYbE=",+ "lastModified": 1781577229,+ "narHash": "sha256-lrp67w8AulE9Ks53n27I45ADSzbOCn4H+CNW1Ck8B+8=","owner": "NixOS","repo": "nixpkgs",- "rev": "1c3fe55ad329cbcb28471bb30f05c9827f724c76",+ "rev": "567a49d1913ce81ac6e9582e3553dd90a955875f","type": "github"},"original": {@@ -99,11 +99,11 @@"rust-analyzer-src": {"flake": false,"locked": {- "lastModified": 1777399820,- "narHash": "sha256-S9efKWyWdEXBxItqalexMVgcWlcVH52GCu4pw3amb0w=",+ "lastModified": 1782030001,+ "narHash": "sha256-1JBvwtGyIsEBIemJBi6syH7iQ+pct7i+HNa1WSZfozs=","owner": "rust-lang","repo": "rust-analyzer",- "rev": "561d1dd862573b5763064f5402511eecce69fc7a",+ "rev": "69ccffdb5b3570c6c14c5780bf2e8836f2209d90","type": "github"},"original": {diff --git a/js/app/packages/core/component/AI/component/debug/HttpStream.tsx b/js/app/packages/core/component/AI/component/debug/HttpStream.tsxindex d6af55240e..524c9a1e6d 100644--- a/js/app/packages/core/component/AI/component/debug/HttpStream.tsx+++ b/js/app/packages/core/component/AI/component/debug/HttpStream.tsx@@ -97,7 +97,7 @@ export default function HttpStreamDebug() {body: JSON.stringify({chat_id: chatId(),content: messageContent(),- model: 'claude-haiku-4-5',+ model: 'anthropic/claude-haiku-4-5',token: '',}),}diff --git a/js/app/packages/core/component/AI/component/input/ChatInput.tsx b/js/app/packages/core/component/AI/component/input/ChatInput.tsxindex e48b6ea36d..79545317ca 100644--- a/js/app/packages/core/component/AI/component/input/ChatInput.tsx+++ b/js/app/packages/core/component/AI/component/input/ChatInput.tsx@@ -2,7 +2,7 @@ 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 { Model, type 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';@@ -14,8 +14,6 @@ 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';@@ -51,26 +49,19 @@ export function ChatInput(props: ChatInputComponentProps) {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,- }));- });+ // Every model is offered in the picker; the backend enforces plan+ // entitlements on send (a free user picking a pro model is rejected there).+ const modelOptions = createMemo(() =>+ Object.values(Model).map((id) => ({ id, available: true }))+ );- // 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.+ // If the selected model isn't a known id (e.g. a stale persisted value),+ // fall back to the first one so we never send something unroutable.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);+ if (options.some((o) => o.id === model())) return;+ const [first] = options;+ if (first) input.setModel(first.id);});let containerRef!: HTMLDivElement;diff --git a/js/app/packages/core/component/AI/constant/model.ts b/js/app/packages/core/component/AI/constant/model.tsindex b18f4b0235..12f02707e5 100644--- a/js/app/packages/core/component/AI/constant/model.ts+++ b/js/app/packages/core/component/AI/constant/model.ts@@ -2,18 +2,18 @@ import AnthropicIcon from '@core/component/AI/assets/anthropic.svg';import OpenAiIcon from '@core/component/AI/assets/openai.svg';/**- * 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+ * Frontend-owned set of model ids. These are the `provider/model` ids the+ * backend router expects as plain strings (the provider segment is how routing+ * picks the provider) — 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',+ opus48: 'anthropic/claude-opus-4-8',+ haiku45: 'anthropic/claude-haiku-4-5',+ sonnet46: 'anthropic/claude-sonnet-4-6',+ gpt55: 'openai/gpt-5.5',+ gpt5Mini: 'openai/gpt-5-mini',} as const;// `Model` is both a value (the const above) and a type (the union of api ids).@@ -26,21 +26,19 @@ type ExhaustiveMap = {};export const MODEL_PRETTYNAME: ExhaustiveMap = {- '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',+ 'anthropic/claude-opus-4-8': 'Opus 4.8',+ 'anthropic/claude-haiku-4-5': 'Haiku 4.5',+ 'anthropic/claude-sonnet-4-6': 'Sonnet 4.6',+ 'openai/gpt-5.5': 'GPT-5.5',+ 'openai/gpt-5-mini': 'GPT-5 mini',} as const;export const MODEL_PROVIDER_ICON: ExhaustiveMap = {- '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,+ 'anthropic/claude-opus-4-8': AnthropicIcon,+ 'anthropic/claude-haiku-4-5': AnthropicIcon,+ 'anthropic/claude-sonnet-4-6': AnthropicIcon,+ 'openai/gpt-5.5': OpenAiIcon,+ 'openai/gpt-5-mini': OpenAiIcon,};export const DEFAULT_MODEL: TModel = Model.opus48;diff --git a/js/app/packages/queries/chat.ts b/js/app/packages/queries/chat.tsindex 875fb4ac9f..e045a50f3b 100644--- a/js/app/packages/queries/chat.ts+++ b/js/app/packages/queries/chat.ts@@ -16,16 +16,6 @@ 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 af1c6a957a..f6e3095ed5 100644--- a/js/app/packages/service-clients/service-cognition/client.ts+++ b/js/app/packages/service-clients/service-cognition/client.ts@@ -19,7 +19,6 @@ 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';@@ -200,14 +199,6 @@ 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 50f29da148..b0d1189570 100644--- a/js/app/packages/service-clients/service-cognition/generated/client.ts+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts@@ -25,7 +25,6 @@ import type {McpAuthCallbackParams,MemoryErrorBody,MemoryResponse,- ModelsResponse,PatchChatRequest,ProjectionStateResponse,RejectToolCallRequest,@@ -646,53 +645,6 @@ 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/chatResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponse.tsindex 310b98d366..d383fc0d32 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,7 +21,7 @@ export interface ChatResponse {id: string;/** The messages in the chat. */messages: ChatMessageWithAttachments[];- /** The model used to generate the chat (provider api id). */+ /** The model used to generate the chat (`provider/model` 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 83718da8f3..6a467375db 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@@ -6,6 +6,6 @@*//**- * The model used to generate the chat (provider api id).+ * The model used to generate the chat (`provider/model` 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 078777b58a..4419e98fc6 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@@ -22,7 +22,7 @@ export interface HttpSendChatMessageRequest {chat_id?: HttpSendChatMessageRequestChatId;/** The content of the message */content: string;- /** The model to respond with (provider api id) */+ /** The model to respond with (`provider/model` 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 91b8c79224..38dd6490a3 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@@ -122,8 +122,6 @@ 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.tsdeleted file mode 100644index f50098ac5e..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/model.ts+++ /dev/null@@ -1,27 +0,0 @@-/* Generated by scripts/generate-models-enum.ts- * *DO NOT EDIT MANUALLY*- *- * Model names enum generated from document-cognition/models endpoint- */-import { z } from 'zod';-export type Model = (typeof Model)[keyof typeof Model];--export const Model = {- '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-8',- 'claude-haiku-4-5',- 'gpt-5.5',- 'gpt-5-mini',-] as const;-const values: [Model, ...Model[]] = [- Object.values(Model)[0],- ...Object.values(Model).slice(1),-];--export const ModelEnum = z.enum(values);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.tsdeleted file mode 100644index 4303a54daa..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/modelAccess.ts+++ /dev/null@@ -1,23 +0,0 @@-/**- * 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.tsdeleted file mode 100644index bf73596333..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/modelsResponse.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * 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/sendChatMessagePayloadAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessagePayloadAllOf.tsindex d2de27e8aa..510072f510 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@@ -17,7 +17,7 @@ export type SendChatMessagePayloadAllOf = {chat_id: string;/** The content of the message */content: string;- /** the chat model to respond with (provider api id) */+ /** the chat model to respond with (`provider/model` id) */model: string;/** Stream ID for tracking the response */stream_id: string;diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.jsonindex dbd764adb7..0d95a33a12 100644--- a/js/app/packages/service-clients/service-cognition/openapi.json+++ b/js/app/packages/service-clients/service-cognition/openapi.json@@ -525,35 +525,6 @@}}},- "/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"],@@ -2150,7 +2121,7 @@},"model": {"type": ["string", "null"],- "description": "The model used to generate the chat (provider api id)."+ "description": "The model used to generate the chat (`provider/model` id)."},"name": {"type": "string",@@ -3010,7 +2981,7 @@},"model": {"type": "string",- "description": "The model to respond with (provider api id)"+ "description": "The model to respond with (`provider/model` id)"},"toolset": {"$ref": "#/components/schemas/ToolSet",@@ -3070,45 +3041,6 @@}}},- "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"],@@ -3309,7 +3241,7 @@},"model": {"type": "string",- "description": "the chat model to respond with (provider api id)"+ "description": "the chat model to respond with (`provider/model` id)"},"stream_id": {"type": "string",diff --git a/js/app/scripts/generate-api-schema.ts b/js/app/scripts/generate-api-schema.tsindex 1eca22d37f..7e29639c34 100644--- a/js/app/scripts/generate-api-schema.ts+++ b/js/app/scripts/generate-api-schema.ts@@ -46,12 +46,6 @@ async function buildOpenApiBinaries(const binArgs = crateNames.flatMap((crate) => ["--bin", `${crate}_openapi`]);- // Also build the DCS models + tools binaries if document_cognition_service is included- if (crateNames.includes("document_cognition_service")) {- binArgs.push("--bin", "document_cognition_service_models");- binArgs.push("--bin", "gen_tool_schemas");- }-console.log(`Building ${crateNames.length} OpenAPI binaries...`);console.log(`cargo build args: ${binArgs.join(" ")}`);await $`cd ${rustCloudStorageDir} && SQLX_OFFLINE=true cargo build ${binArgs}`;@@ -173,29 +167,13 @@ const processService = async (await $`cd ${serviceClientsDir} && bun run orval --config orval.config.ts --project ${service.orvalKey}`;console.log(`[${service.name}] Orval finished (${elapsed(stepStart)})`);- // Special handling for document-cognition+ // Special handling for document-cognition: generate AI tool schema types.if (service.name === "document-cognition") {- stepStart = performance.now();- const rustCloudStorageDir = getRustCloudStorageDir();- const modelsJson = await runBinary(- "document_cognition_service_models",- rustCloudStorageDir,- );- console.log(- `[${service.name}] Models binary finished (${elapsed(stepStart)})`,- );- const modelsJsonPath = path.join(import.meta.dirname, ".models.json");- await write(modelsJsonPath, modelsJson);-stepStart = performance.now();const appDir = path.resolve(import.meta.dirname, "..");- try {- await $`cd ${appDir} && MODELS_JSON=${modelsJsonPath} bun scripts/generate-dcs-types.ts`.quiet();- } finally {- await $`rm -f ${modelsJsonPath}`.quiet();- }+ await $`cd ${appDir} && bun scripts/generate-dcs-tools.ts`.quiet();console.log(- `[${service.name}] DCS types generation finished (${elapsed(stepStart)})`,+ `[${service.name}] DCS tool types generation finished (${elapsed(stepStart)})`,);}@@ -223,7 +201,9 @@ async function main() {// Phase 1: Build all binaries (skipped when OPENAPI_BINS_DIR is set)const buildStart = performance.now();if (process.env.OPENAPI_BINS_DIR) {- console.log(`Phase 1 (cargo build) skipped — using OPENAPI_BINS_DIR=${process.env.OPENAPI_BINS_DIR}`);+ console.log(+ `Phase 1 (cargo build) skipped — using OPENAPI_BINS_DIR=${process.env.OPENAPI_BINS_DIR}`,+ );} else {await buildOpenApiBinaries(crateNames);console.log(`Phase 1 (cargo build) total: ${elapsed(buildStart)}`);diff --git a/js/app/scripts/generate-dcs-models.ts b/js/app/scripts/generate-dcs-models.tsdeleted file mode 100644index f09ff00639..0000000000--- a/js/app/scripts/generate-dcs-models.ts+++ /dev/null@@ -1,93 +0,0 @@-#!/usr/bin/env bun-import * as path from 'node:path';-import { join } from 'path';-import { documentCognitionBase, serviceUrl } from "./services"-import { z } from "zod";--const outputDir = path.resolve(import.meta.dirname, documentCognitionBase.output);-const outputFile = join(outputDir, "generated", "schemas", "model.ts")--const ModelSchema = z.object({- name: z.string(),- provider: z.string(),- metadata: z.object({- contextWindow: z.number(),- })-});--const ModelResponseSchema = z.object({- models: z.array(ModelSchema)-})--type ModelResponse = z.infer<typeof ModelResponseSchema>;--async function fetchModels(): Promise<ModelResponse> {- // If MODELS_JSON env var is set, read from that file instead of fetching from a server- const modelsFile = process.env.MODELS_JSON;- if (modelsFile) {- console.log(`Reading models from local file: ${modelsFile}`);- const file = Bun.file(modelsFile);- const json = await file.json();- return ModelResponseSchema.parse(json);- }-- const baseUrl = serviceUrl(documentCognitionBase)-- const response = await fetch(`${baseUrl}/models`);- if (!response.ok){- throw new Error("bad response from DCS")- }- const models = await response.json();-- return ModelResponseSchema.parse(models);-}--function modelType(models: ModelResponse): string {- return `export type Model = typeof Model[keyof typeof Model];--export const Model = {-${models.models- .map(model => (- ` "${model.name}": "${model.name}",`- ))- .join("\n")-}-} as const;`-}---function warning(): string {- return`/* Generated by scripts/generate-models-enum.ts- * *DO NOT EDIT MANUALLY*- *- * Model names enum generated from document-cognition/models endpoint-*/`-}--function allModels(models: ModelResponse): string {- return `-export const AllModels: Model[] = [-${models.models.map(model => (` "${model.name}"`)).join(',\n')}-] as const;-const values: [Model, ...Model[]] = [-Object.values(Model)[0],-...Object.values(Model).slice(1),-];--export const ModelEnum = z.enum(values);---`--}---const models = await fetchModels();-const contents = [- warning(),- "import {z} from 'zod';",- modelType(models),- allModels(models)-].join("\n");--await Bun.write(outputFile, contents)diff --git a/js/app/scripts/generate-dcs-types.ts b/js/app/scripts/generate-dcs-types.tsdeleted file mode 100644index aeedb09668..0000000000--- a/js/app/scripts/generate-dcs-types.ts+++ /dev/null@@ -1,7 +0,0 @@-import { $ } from "bun"--console.log("Generating DCS tools");-await $`bun run scripts/generate-dcs-tools.ts`;-console.log("\n\nGenerating DCS models");-await $`bun run scripts/generate-dcs-models.ts`;-console.log("Generated models");diff --git a/rust/cloud-storage/agent/src/agent_loop.rs b/rust/cloud-storage/agent/src/agent_loop.rsindex e70b0addb7..7c0e686c4f 100644--- a/rust/cloud-storage/agent/src/agent_loop.rs+++ b/rust/cloud-storage/agent/src/agent_loop.rs@@ -1,21 +1,14 @@/// The main entry point: [`AgentLoop`] and [`Session`].use crate::error::AgentError;-use crate::hook::{RegisterFn, StreamBridge, ToolRouter};-use crate::model::AgentModel;-use crate::model::router::{AllModelsRouter, RoutedModel};-use crate::model::types::Model;-use crate::provider_env;-use crate::stream::{ChatCompletionStream, StreamPart};+use crate::hook::{RegisterFn, ToolRouter};+use crate::model::PredefinedModel;+use crate::model::router::{ModelRouter, ProviderAgent};+use crate::stream::ChatCompletionStream;use crate::tool_adapter::DynToolSetAdapter;use ai_toolset::{RequestContext, SearchableTool, ToolLoader, ToolSet as AiToolSet};use ai_usage::{UsageContext, UsageRecorder};-use futures::StreamExt;-use rig_core::agent::{Agent, MultiTurnStreamItem};-use rig_core::completion::{CompletionModel, GetTokenUsage};use rig_core::message::Message;-use rig_core::providers::{anthropic, openai};-use rig_core::streaming::{StreamedAssistantContent, StreamingPrompt};-use rig_core::tool::server::{ToolServer, ToolServerHandle};+use rig_core::tool::server::ToolServer;use std::future::Future;use std::pin::Pin;use std::sync::{Arc, Mutex, RwLock};@@ -25,15 +18,13 @@ 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 id (see [`AllModelsRouter`]). The model is a+/// Routes each session to the provider serving the selected model id (see+/// [`ModelRouter`]). 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+/// callers may pass a [`PredefinedModel`] 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: Arc<anthropic::Client>,- openai: Arc<openai::Client>,model: String,max_turns: usize,max_tokens: u64,@@ -49,15 +40,8 @@ impl AgentLoop {////// `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` are required.pub fn new(recorder: Arc<dyn UsageRecorder>) -> Self {- let anthropic = Arc::new(- provider_env::anthropic_client_from_env().expect("ANTHROPIC_API_KEY must be set"),- );- let openai =- Arc::new(provider_env::openai_client_from_env().expect("OPENAI_API_KEY must be set"));Self {- anthropic,- openai,- model: AgentModel::default().to_string(),+ model: PredefinedModel::default().to_string(),max_turns: DEFAULT_MAX_TURNS,max_tokens: DEFAULT_MAX_TOKENS,recorder,@@ -85,24 +69,6 @@ impl AgentLoop {self}- fn build_agent<M: CompletionModel>(- &self,- model: M,- thinking: Option<serde_json::Value>,- handle: ToolServerHandle,- system_prompt: &str,- ) -> Agent<M> {- let mut builder = rig_core::agent::AgentBuilder::new(model)- .tool_server_handle(handle)- .default_max_turns(self.max_turns)- .max_tokens(self.max_tokens)- .preamble(system_prompt);- if let Some(params) = thinking {- builder = builder.additional_params(params);- }- builder.build()- }-/// Start a new streaming session.////// `toolset` is the combined tool set (static + MCP) for this request.@@ -222,29 +188,16 @@ impl AgentLoop {// 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,- ))- }- RoutedModel::OpenAi(m) => {- let thinking = m.thinking_params();- ProviderAgent::OpenAi(self.build_agent(- m.completion(),- thinking,- handle,- &system_prompt,- ))- }- };+ // ids). The router owns provider-specific agent construction.+ let agent = ModelRouter::shared()+ .expect("failed to initialize model router")+ .agent(+ &self.model,+ handle,+ &system_prompt,+ self.max_turns,+ self.max_tokens,+ );Session {agent,@@ -260,12 +213,6 @@ impl AgentLoop {}}-/// A rig agent bound to the provider that serves the session's model.-enum ProviderAgent {- Anthropic(Agent<anthropic::completion::CompletionModel>),- OpenAi(Agent<openai::responses_api::ResponsesCompletionModel>),-}-/// A single streaming conversation session.pub struct Session {agent: ProviderAgent,@@ -299,38 +246,20 @@ impl Session {)));};- let stream = match &self.agent {- ProviderAgent::Anthropic(agent) => {- run_stream(- agent,- prompt.clone(),- history.to_vec(),- self.max_turns,- self.routing.clone(),- self.loaded_buffer.clone(),- self.register_loaded.clone(),- self.recorder.clone(),- self.usage_ctx.clone(),- self.model.clone(),- )- .await- }- ProviderAgent::OpenAi(agent) => {- run_stream(- agent,- prompt.clone(),- history.to_vec(),- self.max_turns,- self.routing.clone(),- self.loaded_buffer.clone(),- self.register_loaded.clone(),- self.recorder.clone(),- self.usage_ctx.clone(),- self.model.clone(),- )- .await- }- };+ let stream = self+ .agent+ .run_stream(+ prompt.clone(),+ history.to_vec(),+ self.max_turns,+ self.routing.clone(),+ self.loaded_buffer.clone(),+ self.register_loaded.clone(),+ self.recorder.clone(),+ self.usage_ctx.clone(),+ self.model.clone(),+ )+ .await;Ok(stream)}@@ -340,81 +269,3 @@ impl Session {&self.history}}--/// Run the agentic loop on `agent` and adapt rig's stream into the-/// provider-agnostic [`StreamPart`] stream consumed by DCS.-#[allow(clippy::too_many_arguments)]-async fn run_stream<M>(- agent: &Agent<M>,- prompt: Message,- history: Vec<Message>,- max_turns: usize,- routing: ToolRouter,- loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,- register_loaded: RegisterFn,- recorder: Arc<dyn UsageRecorder>,- usage_ctx: UsageContext,- model: String,-) -> ChatCompletionStream<'static>-where- M: CompletionModel + 'static,- M::StreamingResponse: GetTokenUsage + Send + Sync,-{- let (bridge, mut rx) = StreamBridge::channel(routing, loaded_buffer, register_loaded);-- let mut rig_stream = agent- .stream_prompt(prompt)- .with_history(history)- .multi_turn(max_turns)- .with_hook(bridge)- .await;-- let stream = async_stream::stream! {- let mut thinking_buf = String::new();-- while let Some(item) = rig_stream.next().await {- while let Ok(part) = rx.try_recv() {- yield part;- }- match item {- Ok(MultiTurnStreamItem::StreamAssistantItem(- StreamedAssistantContent::ReasoningDelta { reasoning, .. },- )) => {- thinking_buf.push_str(&reasoning);- }- other => {- if !thinking_buf.is_empty() {- yield Ok(StreamPart::Thinking(std::mem::take(&mut thinking_buf)));- }- match other {- Ok(MultiTurnStreamItem::FinalResponse(final_resp)) => {- let usage = final_resp.usage();- // Best-effort cost logging; never fails the stream.- recorder.record(usage_ctx.clone().into_event(- model.clone(),- usage.input_tokens,- usage.output_tokens,- ));- yield Ok(StreamPart::Usage(crate::stream::Usage {- input_tokens: usage.input_tokens,- output_tokens: usage.output_tokens,- }));- }- Err(e) => {- yield Err(AgentError::Streaming(e));- }- _ => {}- }- }- }- }- if !thinking_buf.is_empty() {- yield Ok(StreamPart::Thinking(std::mem::take(&mut thinking_buf)));- }- while let Ok(part) = rx.try_recv() {- yield part;- }- };-- Box::pin(stream)-}diff --git a/rust/cloud-storage/agent/src/completion.rs b/rust/cloud-storage/agent/src/completion.rsindex d05567a14e..7d493390f3 100644--- a/rust/cloud-storage/agent/src/completion.rs+++ b/rust/cloud-storage/agent/src/completion.rs@@ -1,21 +1,14 @@-/// One-shot completion — send a prompt and get a string response.-use crate::model::router::{AllModelsRouter, RoutedModel};-use crate::model::types::Model;-use crate::provider_env;+//! One-shot completion — send a prompt and get a string response.+//!+//! This is the non-streaming API layer: routing only resolves a model, and the+//! actual prompting lives here.+use crate::model::router::{ModelRouter, RoutedModel};use ai_usage::{UsageContext, UsageRecorder};-use rig_core::agent::PromptResponse;+use rig_core::agent::{AgentBuilder, PromptResponse};use rig_core::completion::{CompletionModel, Prompt};use rig_core::message::Message;-use std::sync::Arc;-/// Build a router over provider clients from `APP_SECRETS_JSON` or the environment.-///-/// `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` are required.-fn env_router() -> anyhow::Result<AllModelsRouter> {- let anthropic = Arc::new(provider_env::anthropic_client_from_env()?);- let openai = Arc::new(provider_env::openai_client_from_env()?);- Ok(AllModelsRouter::new(anthropic, openai))-}+const ONE_SHOT_MAX_TOKENS: u64 = 16_000;/// Send a system prompt + user message and return the model's text response.///@@ -34,11 +27,16 @@ pub async fn complete<M: ToString>(ctx: UsageContext,) -> anyhow::Result<String> {let model = model.to_string();- let response = match env_router()?.route_or_default(&model) {+ let response = match ModelRouter::shared()?.route_or_default(&model) {RoutedModel::Anthropic(m) => {prompt_once(m.completion(), system_prompt, user_message).await?}- RoutedModel::OpenAi(m) => prompt_once(m.completion(), system_prompt, user_message).await?,+ RoutedModel::OpenAiChatCompletions(m) => {+ prompt_once(m.completion(), system_prompt, user_message).await?+ }+ RoutedModel::OpenAiResponses(m) => {+ prompt_once(m.completion(), system_prompt, user_message).await?+ }};record(recorder, ctx, model, &response);Ok(response.output)@@ -57,11 +55,14 @@ pub async fn complete_with_history<M: ToString>(ctx: UsageContext,) -> anyhow::Result<String> {let model = model.to_string();- let response = match env_router()?.route_or_default(&model) {+ let response = match ModelRouter::shared()?.route_or_default(&model) {RoutedModel::Anthropic(m) => {prompt_with_history(m.completion(), system_prompt, messages).await?}- RoutedModel::OpenAi(m) => {+ RoutedModel::OpenAiChatCompletions(m) => {+ prompt_with_history(m.completion(), system_prompt, messages).await?+ }+ RoutedModel::OpenAiResponses(m) => {prompt_with_history(m.completion(), system_prompt, messages).await?}};@@ -83,27 +84,30 @@ fn record());}+/// Build a toolless agent and prompt it with a single user message.async fn prompt_once<M: CompletionModel + 'static>(completion_model: M,system_prompt: &str,user_message: &str,) -> anyhow::Result<PromptResponse> {- let agent = rig_core::agent::AgentBuilder::new(completion_model)+ let agent = AgentBuilder::new(completion_model).preamble(system_prompt)- .max_tokens(16_000)+ .max_tokens(ONE_SHOT_MAX_TOKENS).build();Ok(agent.prompt(user_message).extended_details().await?)}+/// Build a toolless agent and prompt it with the last message of `messages`,+/// using the rest as history.async fn prompt_with_history<M: CompletionModel + 'static>(completion_model: M,system_prompt: &str,messages: Vec<Message>,) -> anyhow::Result<PromptResponse> {- let agent = rig_core::agent::AgentBuilder::new(completion_model)+ let agent = AgentBuilder::new(completion_model).preamble(system_prompt)- .max_tokens(16_000)+ .max_tokens(ONE_SHOT_MAX_TOKENS).build();let Some((prompt, history)) = messages.split_last() else {diff --git a/rust/cloud-storage/agent/src/convert.rs b/rust/cloud-storage/agent/src/convert.rsindex 05811f9568..d07c90975f 100644--- a/rust/cloud-storage/agent/src/convert.rs+++ b/rust/cloud-storage/agent/src/convert.rs@@ -153,14 +153,14 @@ fn convert_assistant(msg: &ChatMessage) -> Vec<Message> {replay_item_id(id),ToolFunction::new(name.clone(), json.clone()),)- .with_call_id(id.clone()),+ .with_call_id(replay_call_id(id)),));}AssistantMessagePart::ToolCallResponseJson { id, json, .. } => {let text = serde_json::to_string(json).unwrap_or_default();tool_results.push(UserContent::tool_result_with_call_id(replay_item_id(id),- id.clone(),+ replay_call_id(id),OneOrMany::one(ToolResultContent::text(text)),));}@@ -169,7 +169,7 @@ fn convert_assistant(msg: &ChatMessage) -> Vec<Message> {} => {tool_results.push(UserContent::tool_result_with_call_id(replay_item_id(id),- id.clone(),+ replay_call_id(id),OneOrMany::one(ToolResultContent::text(description.clone())),));}@@ -181,16 +181,27 @@ fn convert_assistant(msg: &ChatMessage) -> Vec<Message> {out}-/// Item id replayed to the provider for a persisted tool call or result.+/// `call_id` replayed to the provider for a persisted tool call or result.////// The persisted id is the provider call id when one exists (OpenAI's-/// `call_…`) or an internal nanoid otherwise. OpenAI's Responses API rejects-/// replayed `function_call` item ids that don't begin with `fc`, and pairs-/// calls to results through `call_id` — which is why the persisted id is also-/// set as `call_id` above. Anthropic ignores `call_id` and only requires a-/// result's id to match its call's id, which this uniform prefix preserves.+/// `call_…`) or an internal nanoid otherwise. OpenAI's Responses API pairs a+/// call to its result through `call_id` and rejects ids ending in a separator,+/// and a nanoid can end in `_` or `-` — so trim the trailing separator(s). A+/// call and its result both run through this with the same `id`, so trimming+/// keeps them paired. Anthropic ignores `call_id`.+fn replay_call_id(id: &str) -> String {+ id.trim_end_matches(['_', '-']).to_owned()+}++/// `function_call` item id replayed to the provider for a persisted tool call+/// or result.+///+/// OpenAI's Responses API rejects replayed item ids that don't begin with `fc`+/// (and, like `call_id`, ones ending in a separator — hence [`replay_call_id`]).+/// Anthropic ignores `call_id` and only requires a result's item id to match+/// its call's, which this uniform prefix-over-trimmed-id preserves.fn replay_item_id(id: &str) -> String {- format!("fc_{id}")+ format!("fc_{}", replay_call_id(id))}/// Merges consecutive `Text` and `Thinking` parts into single entries.diff --git a/rust/cloud-storage/agent/src/convert/test.rs b/rust/cloud-storage/agent/src/convert/test.rsindex a7649ddee4..4baed99a47 100644--- a/rust/cloud-storage/agent/src/convert/test.rs+++ b/rust/cloud-storage/agent/src/convert/test.rs@@ -254,6 +254,60 @@ fn tool_call_round_trip_carries_call_id_and_fc_item_id() {assert_eq!(result.call_id.as_deref(), Some("call_1"));}+#[test]+fn trailing_separator_ids_are_trimmed_before_replay() {+ // A persisted nanoid can end in `_` or `-`; the OpenAI Responses API+ // rejects replayed `function_call` item ids / `call_id`s ending in a+ // separator. Both the item id and call_id must be trimmed, and a call and+ // its result must stay paired afterwards.+ for raw in ["74JQSgjB6MEaTtCNVdDG_", "abcDEF123-"] {+ let msg = assistant_parts(vec![+ AssistantMessagePart::ToolCall {+ name: "search".to_owned(),+ json: json!({}),+ id: raw.to_owned(),+ },+ AssistantMessagePart::ToolCallResponseJson {+ name: "search".to_owned(),+ json: json!({}),+ id: raw.to_owned(),+ },+ ]);+ let messages = to_rig_messages(&[msg]);++ let trimmed = raw.trim_end_matches(['_', '-']);+ let expected_item = format!("fc_{trimmed}");++ let Message::Assistant { content, .. } = &messages[0] else {+ panic!("expected assistant");+ };+ let AssistantContent::ToolCall(call) = content.first() else {+ panic!("expected tool call");+ };+ assert_eq!(call.id, expected_item, "item id must be trimmed for {raw}");+ assert_eq!(+ call.call_id.as_deref(),+ Some(trimmed),+ "call_id must be trimmed for {raw}"+ );+ assert!(+ !call.id.ends_with(['_', '-'])+ && !call.call_id.as_deref().unwrap().ends_with(['_', '-']),+ "no replayed id may end in a separator ({raw})"+ );++ let Message::User { content } = &messages[1] else {+ panic!("expected tool result");+ };+ let UserContent::ToolResult(result) = content.first() else {+ panic!("expected tool result");+ };+ // Result must pair to its call on both ids.+ assert_eq!(result.id, expected_item);+ assert_eq!(result.call_id.as_deref(), Some(trimmed));+ }+}+#[test]fn mcp_tool_call_converts_like_regular_tool_call() {let msg = assistant_parts(vec![AssistantMessagePart::McpToolCall {diff --git a/rust/cloud-storage/agent/src/error.rs b/rust/cloud-storage/agent/src/error.rsindex 24903fd58f..df90011df3 100644--- a/rust/cloud-storage/agent/src/error.rs+++ b/rust/cloud-storage/agent/src/error.rs@@ -19,6 +19,16 @@ pub enum AgentError {/// Unknown completion model#[error("unknown completion model [{0}]")]UnknownModel(String),+ /// Model id missing a `provider/` segment.+ #[error("malformed model")]+ MalformedModel(String),+ /// Expected env var+ #[error(transparent)]+ EnvVar(#[from] macro_env_var::VarNameErr),+ /// Provider client error+ #[error(transparent)]+ ProviderClientError(#[from] rig_core::client::ProviderClientError),+ /// Rig http client error+ #[error(transparent)]+ RigHttpClient(#[from] rig_core::http_client::Error),}--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 8e67b69e75..72500f2430 100644--- a/rust/cloud-storage/agent/src/lib.rs+++ b/rust/cloud-storage/agent/src/lib.rs@@ -9,7 +9,6 @@ mod convert;mod error;mod hook;mod model;-mod provider_env;mod stream;/// Structured output via prompted JSON generation.pub mod structured_output;@@ -22,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, Provider};+pub use model::PredefinedModel;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.rsindex 1b242057ef..4de920a80d 100644--- a/rust/cloud-storage/agent/src/model/anthropic.rs+++ b/rust/cloud-storage/agent/src/model/anthropic.rs@@ -1,101 +1,41 @@-use super::Model;-use crate::error::AgentError;-use regex::Regex;+use crate::model::types::Model;use rig_core::{client::CompletionClient, providers::anthropic};-use std::sync::{Arc, LazyLock};+use std::sync::Arc;-/// Matches the Anthropic model namespace.+/// A Claude model bound to the native Anthropic client that serves it.///-/// 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 {+/// Carries the parsed [`Model`] id and a shared client. Which provider an id+/// belongs to is decided by routing (the `anthropic/…` segment), so there is no+/// id classification here.+pub struct AnthropicModel<'a> {+ model: Model<'a>,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<'a> AnthropicModel<'a> {+ /// Bind `model` to the client that serves it.+ pub fn new(model: Model<'a>, client: Arc<anthropic::Client>) -> Self {+ Self { model, client }}-}--impl Model for AnthropicModel {- type Completion = anthropic::completion::CompletionModel;- fn completion(&self) -> Self::Completion {- self.client- .completion_model(self.model.as_str().to_string())+ /// The rig completion model for this id. The id is passed verbatim to the+ /// Anthropic API.+ pub fn completion(&self) -> anthropic::completion::CompletionModel {+ self.client.completion_model(self.model.name().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.+ /// Best-effort extended-thinking config for the configured model, flattened+ /// into the request body by rig, or `None` if the model doesn't support it.///- /// 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.+ /// - Opus / Fable / Mythos / Sonnet: `adaptive` (the model chooses when to+ /// think; avoids the `budget_tokens < max_tokens` constraint).+ /// - Haiku: no adaptive support, so `enabled` + `budget_tokens`.///- /// 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();+ /// `temperature` is never set: it is rejected on Opus 4.7+ and constrained+ /// to 1 with extended thinking elsewhere, so we let the API default apply.+ pub fn thinking_params(&self) -> Option<serde_json::Value> {+ let model = self.model.name().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")diff --git a/rust/cloud-storage/agent/src/model/mod.rs b/rust/cloud-storage/agent/src/model/mod.rsindex b5aec78e0c..b1f3e7f45d 100644--- a/rust/cloud-storage/agent/src/model/mod.rs+++ b/rust/cloud-storage/agent/src/model/mod.rs@@ -1,146 +1,12 @@-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::*;+//! Models are strings+//! AgentModel exists to help the backend use AI+//! Model routing takes a string and returns the appropriate client+mod predefined_model;+mod types;+pub use predefined_model::*;mod anthropic;mod openai;pub mod router;-/// API provider serving a model.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum Provider {- /// Anthropic (Claude models)- Anthropic,- /// OpenAI (GPT models)- OpenAi,-}--impl Provider {- /// Lowercase provider name as exposed in the models schema.- pub fn as_str(&self) -> &'static str {- match self {- Self::Anthropic => "anthropic",- Self::OpenAi => "openai",- }- }-}--/// Model to use for completions.-///-/// 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 (currently Claude Opus 4.8)- #[default]- #[serde(rename = "claude-opus-4-8")]- Smart,- /// 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,-}--/// `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())- }-}--impl AgentModel {- /// Returns the provider API model identifier.- pub fn api_id(&self) -> &'static str {- match self {- 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.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)- pub fn thinking_params(&self) -> serde_json::Value {- match self {- Self::Smart | Self::Opus4_7 | Self::Retired => serde_json::json!({- "thinking": { "type": "adaptive", "display": "summarized" },- "temperature": 1- }),- Self::Sonnet4_6 | Self::Fast | Self::Haiku4_5 => serde_json::json!({- "thinking": {- "type": "enabled",- "budget_tokens": 10_000,- "display": "summarized"- },- "temperature": 1- }),- Self::Gpt5_5 => serde_json::json!({- "reasoning": { "effort": "medium", "summary": "auto" }- }),- Self::Gpt5Mini => serde_json::json!({- "reasoning": { "effort": "low", "summary": "auto" }- }),- }- }-- /// Context window size in tokens.- pub fn context_window(&self) -> u64 {- match self {- Self::Smart | Self::Opus4_7 | Self::Sonnet4_6 | Self::Retired => 1_000_000,- Self::Fast | Self::Haiku4_5 => 200_000,- Self::Gpt5_5 | Self::Gpt5Mini => 400_000,- }- }-- /// API provider serving this model.- pub fn provider(&self) -> Provider {- match self {- Self::Smart- | Self::Fast- | Self::Opus4_7- | Self::Sonnet4_6- | Self::Haiku4_5- | Self::Retired => Provider::Anthropic,- Self::Gpt5_5 | Self::Gpt5Mini => Provider::OpenAi,- }- }-}-#[cfg(test)]mod test;diff --git a/rust/cloud-storage/agent/src/model/openai.rs b/rust/cloud-storage/agent/src/model/openai.rsindex 9e89a550b6..214b6f533e 100644--- a/rust/cloud-storage/agent/src/model/openai.rs+++ b/rust/cloud-storage/agent/src/model/openai.rs@@ -1,101 +1,101 @@-use super::Model;-use crate::error::AgentError;-use regex::Regex;+use std::sync::Arc;++use crate::model::types::Model;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:+/// A model served over the OpenAI-compatible **Chat Completions** API.///-/// - `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)+/// OpenAI-compatible providers differ only by the+/// [`CompletionsClient`](openai::CompletionsClient)'s base URL and key, never+/// by Rust type, so routing can hold any number of them without new variants.+/// Which provider serves an id is decided by routing (the `provider/…`+/// segment), so there is no id classification here.+pub struct OpenAiChatCompletionsModel<'a> {+ model: Model<'a>,+ client: Arc<openai::CompletionsClient>,}-/// 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<'a> OpenAiChatCompletionsModel<'a> {+ /// Bind `model` to the client that serves it.+ pub fn new(model: Model<'a>, client: Arc<openai::CompletionsClient>) -> Self {+ Self { model, client }+ }-impl OpenAiModelId {- /// The underlying api id, passed verbatim to the OpenAI API.- pub(crate) fn as_str(&self) -> &str {- &self.0+ /// The rig completion model for this id.+ ///+ /// Unlike the Responses API, the Chat Completions API does not coerce tools+ /// into a strict subset, so tools are already sent verbatim.+ pub fn completion(&self) -> openai::completion::CompletionModel {+ self.client.completion_model(self.model.name().to_string())}-}-impl TryFrom<String> for OpenAiModelId {- type Error = AgentError;+ /// Best-effort reasoning config, flattened into the request by rig, or+ /// `None` if the model doesn't support it.+ ///+ /// The Chat Completions API takes a flat `reasoning_effort` field, accepted+ /// only by reasoning models (the GPT-5 family and the `o`-series); anything+ /// else returns `None`, since sending it elsewhere 400s. `mini` / `nano`+ /// variants get a lower effort. `temperature` is never set (reasoning models+ /// reject it).+ pub fn thinking_params(&self) -> Option<serde_json::Value> {+ let model = self.model.name().to_lowercase();- fn try_from(model: String) -> Result<Self, Self::Error> {- if is_openai_model(&model) {- Ok(Self(model))- } else {- Err(AgentError::UnknownModel(model))+ let is_reasoning = model.contains("gpt-5")+ || model.starts_with("o1")+ || model.starts_with("o3")+ || model.starts_with("o4");+ if !is_reasoning {+ return None;}++ let effort = if model.contains("mini") || model.contains("nano") {+ "low"+ } else {+ "high"+ };++ Some(serde_json::json!({ "reasoning_effort": effort }))}}-pub struct OpenAiModel {+/// A model served over OpenAI's **Responses** API.+///+/// This is intentionally separate from OpenAI-compatible Chat Completions:+/// OpenAI GPT reasoning models expect Responses-shaped request fields, while+/// many compatible OSS endpoints only promise `/v1/chat/completions`.+pub struct OpenAiResponsesModel<'a> {+ model: Model<'a>,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<'a> OpenAiResponsesModel<'a> {+ /// Bind `model` to the Responses API client that serves it.+ pub fn new(model: Model<'a>, client: Arc<openai::Client>) -> Self {+ Self { model, client }}-}--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 {+ /// The rig Responses API completion model for this id.+ ///+ /// Rig maps the generic `max_tokens` agent setting to the Responses API's+ /// `max_output_tokens`, avoiding the Chat Completions `max_tokens` 400s on+ /// GPT reasoning models. Tools are sent verbatim (`with_non_strict_tools`)+ /// rather than coerced into OpenAI's strict subset.+ pub fn completion(&self) -> openai::responses_api::ResponsesCompletionModel {self.client- .completion_model(self.model.as_str().to_string())+ .completion_model(self.model.name().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();+ /// Best-effort reasoning config for OpenAI Responses models, or `None` if+ /// the model doesn't support it.+ pub fn thinking_params(&self) -> Option<serde_json::Value> {+ let model = self.model.name().to_lowercase();- if !model.contains("gpt-5") {+ let is_reasoning = model.contains("gpt-5")+ || model.starts_with("o1")+ || model.starts_with("o3")+ || model.starts_with("o4");+ if !is_reasoning {return None;}@@ -106,7 +106,10 @@ impl Model for OpenAiModel {};Some(serde_json::json!({- "reasoning": { "effort": effort, "summary": "auto" }+ "reasoning": {+ "effort": effort,+ "summary": "auto"+ }}))}}diff --git a/rust/cloud-storage/agent/src/model/predefined_model.rs b/rust/cloud-storage/agent/src/model/predefined_model.rsnew file mode 100644index 0000000000..3a47cc95c2--- /dev/null+++ b/rust/cloud-storage/agent/src/model/predefined_model.rs@@ -0,0 +1,123 @@+use crate::model::types::Model;+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;++static ANTHROPIC: &str = "anthropic";+static OPENAI: &str = "openai";++/// 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 PredefinedModel {+ /// Best available model (currently Claude Opus 4.8)+ #[default]+ #[serde(rename = "claude-opus-4-8")]+ Smart,+ /// 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 From<PredefinedModel> for super::types::Model<'static> {+ fn from(model: PredefinedModel) -> Self {+ let (provider, name) = match model {+ PredefinedModel::Smart | PredefinedModel::Retired => (ANTHROPIC, CLAUDE_OPUS_4_8),+ PredefinedModel::Opus4_7 => (ANTHROPIC, CLAUDE_OPUS_4_7),+ PredefinedModel::Sonnet4_6 => (ANTHROPIC, CLAUDE_SONNET_4_6),+ PredefinedModel::Fast | PredefinedModel::Haiku4_5 => (ANTHROPIC, CLAUDE_HAIKU_4_5),+ PredefinedModel::Gpt5_5 => (OPENAI, GPT_5_5),+ PredefinedModel::Gpt5Mini => (OPENAI, GPT_5_MINI),+ };+ super::types::Model {+ provider: std::borrow::Cow::Borrowed(provider),+ name: std::borrow::Cow::Borrowed(name),+ }+ }+}++impl PredefinedModel {+ /// Returns the provider API model identifier.+ pub fn api_id(&self) -> &'static str {+ match self {+ 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.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)+ pub fn thinking_params(&self) -> serde_json::Value {+ match self {+ Self::Smart | Self::Opus4_7 | Self::Retired => serde_json::json!({+ "thinking": { "type": "adaptive", "display": "summarized" },+ "temperature": 1+ }),+ Self::Sonnet4_6 | Self::Fast | Self::Haiku4_5 => serde_json::json!({+ "thinking": {+ "type": "enabled",+ "budget_tokens": 10_000,+ "display": "summarized"+ },+ "temperature": 1+ }),+ Self::Gpt5_5 => serde_json::json!({+ "reasoning": { "effort": "medium", "summary": "auto" }+ }),+ Self::Gpt5Mini => serde_json::json!({+ "reasoning": { "effort": "low", "summary": "auto" }+ }),+ }+ }++ /// Context window size in tokens.+ pub fn context_window(&self) -> u64 {+ match self {+ Self::Smart | Self::Opus4_7 | Self::Sonnet4_6 | Self::Retired => 1_000_000,+ Self::Fast | Self::Haiku4_5 => 200_000,+ Self::Gpt5_5 | Self::Gpt5Mini => 400_000,+ }+ }+}++impl std::fmt::Display for PredefinedModel {+ /// Displays the provider-qualified id (`provider/name`) the router routes on.+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let model: Model = (*self).into();+ write!(f, "{}", model)+ }+}diff --git a/rust/cloud-storage/agent/src/model/router.rs b/rust/cloud-storage/agent/src/model/router.rsindex f1a33cf1af..092645ceae 100644--- a/rust/cloud-storage/agent/src/model/router.rs+++ b/rust/cloud-storage/agent/src/model/router.rs@@ -1,83 +1,476 @@-//! Frontend-authoritative model routing.+//! 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.+//! Routing turns a `provider/model` api id into a runnable agent and owns the+//! provider fan-out so the rest of the crate stays provider-agnostic:+//!+//! - [`RoutedModel`] — the routed id bound to its provider client. One arm per+//! wire protocol: Anthropic-native, OpenAI Responses, and OpenAI-compatible+//! Chat Completions. Compatible providers live in a data registry keyed by+//! name, so adding one is [`with_openai_provider`](ModelRouter::with_openai_provider).+//! - [`ProviderAgent`] — a built rig agent, with the same arms. Its+//! [`run_stream`](ProviderAgent::run_stream) matches internally, so callers+//! (e.g. `agent_loop`) hold one type and never fan out.+//!+//! Ids are addressed as `provider/model` (e.g. `anthropic/claude-opus-4-8`,+//! `groq/llama-3.3-70b`); routing picks the provider from the segment, never by+//! sniffing the id. Unroutable ids fall back to the default model.-mod anthropic;-mod openai;+use std::borrow::Cow;+use std::collections::HashMap;+use std::sync::{Arc, Mutex, OnceLock};-#[cfg(test)]-mod test;+use ai_toolset::SearchableTool;+use ai_usage::{UsageContext, UsageRecorder};+use futures::StreamExt;+use macro_env_var::env_var;+use rig_core::agent::{Agent, AgentBuilder, MultiTurnStreamItem};+use rig_core::completion::{CompletionModel, GetTokenUsage};+use rig_core::message::Message;+use rig_core::providers::{anthropic, openai};+use rig_core::streaming::{StreamedAssistantContent, StreamingPrompt};+use rig_core::tool::server::ToolServerHandle;-use self::anthropic::AnthropicRouter;-use self::openai::OpenAiRouter;-use super::anthropic::{AnthropicModel, AnthropicModelId};-use super::openai::{OpenAiModel, OpenAiModelId};-use super::types::ModelRouter;+use super::PredefinedModel;+use super::anthropic::AnthropicModel;+use super::openai::{OpenAiChatCompletionsModel, OpenAiResponsesModel};+use super::types::Model;use crate::error::AgentError;-use rig_core::providers::anthropic::Client as AnthropicClient;-use rig_core::providers::openai::Client as OpenAiClient;-use std::sync::Arc;+use crate::hook::{RegisterFn, StreamBridge, ToolRouter};+use crate::stream::{ChatCompletionStream, StreamPart};++env_var! {+ struct ApiKeys {+ AnthropicApiKey,+ OpenaiApiKey+ }+}++/// Provider segment for native Anthropic.+const ANTHROPIC_PROVIDER: &str = "anthropic";+/// Provider segment the built-in OpenAI client is registered under.+const OPENAI_PROVIDER: &str = "openai";++/// A routed model id bound to the provider client that serves it.+pub(crate) enum RoutedModel<'a> {+ /// A model on Anthropic's native API.+ Anthropic(AnthropicModel<'a>),+ /// A model on the OpenAI-compatible Chat Completions API.+ OpenAiChatCompletions(OpenAiChatCompletionsModel<'a>),+ /// A model on OpenAI's Responses API.+ OpenAiResponses(OpenAiResponsesModel<'a>),+}++impl<'a> RoutedModel<'a> {+ /// Build the rig agent for this model, applying provider-specific thinking+ /// config. Pure construction — no model call is made here.+ pub(crate) fn into_agent(+ self,+ handle: ToolServerHandle,+ system_prompt: &str,+ max_turns: usize,+ max_tokens: u64,+ ) -> ProviderAgent {+ match self {+ RoutedModel::Anthropic(m) => {+ let thinking = m.thinking_params();+ ProviderAgent::Anthropic(build_agent(+ m.completion(),+ thinking,+ handle,+ system_prompt,+ max_turns,+ max_tokens,+ ))+ }+ RoutedModel::OpenAiChatCompletions(m) => {+ let thinking = m.thinking_params();+ ProviderAgent::OpenAiChatCompletions(build_agent(+ m.completion(),+ thinking,+ handle,+ system_prompt,+ max_turns,+ max_tokens,+ ))+ }+ RoutedModel::OpenAiResponses(m) => {+ let thinking = m.thinking_params();+ ProviderAgent::OpenAiResponses(build_agent(+ m.completion(),+ thinking,+ handle,+ system_prompt,+ max_turns,+ max_tokens,+ ))+ }+ }+ }+}-/// A routed model, tagged by the provider that serves it.+/// A built rig agent bound to the provider serving the session's model.+///+/// The two arms are different concrete `Agent<M>` types; [`run_stream`] hides+/// that behind one concrete [`ChatCompletionStream`], so callers never match.///-/// 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),+/// [`run_stream`]: ProviderAgent::run_stream+pub(crate) enum ProviderAgent {+ /// An agent over Anthropic's native completion model.+ Anthropic(Agent<anthropic::completion::CompletionModel>),+ /// An agent over the OpenAI Chat Completions model.+ OpenAiChatCompletions(Agent<openai::completion::CompletionModel>),+ /// An agent over the OpenAI Responses model.+ OpenAiResponses(Agent<openai::responses_api::ResponsesCompletionModel>),}-/// Routes any supported model id to the provider that serves it.+impl ProviderAgent {+ /// Run the agentic loop and adapt rig's stream into the provider-agnostic+ /// [`StreamPart`] stream consumed by DCS. The provider fan-out is internal.+ #[allow(clippy::too_many_arguments)]+ pub(crate) async fn run_stream(+ &self,+ prompt: Message,+ history: Vec<Message>,+ max_turns: usize,+ routing: ToolRouter,+ loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,+ register_loaded: RegisterFn,+ recorder: Arc<dyn UsageRecorder>,+ usage_ctx: UsageContext,+ model: String,+ ) -> ChatCompletionStream<'static> {+ match self {+ ProviderAgent::Anthropic(agent) => {+ drive_stream(+ agent,+ prompt,+ history,+ max_turns,+ routing,+ loaded_buffer,+ register_loaded,+ recorder,+ usage_ctx,+ model,+ )+ .await+ }+ ProviderAgent::OpenAiChatCompletions(agent) => {+ drive_stream(+ agent,+ prompt,+ history,+ max_turns,+ routing,+ loaded_buffer,+ register_loaded,+ recorder,+ usage_ctx,+ model,+ )+ .await+ }+ ProviderAgent::OpenAiResponses(agent) => {+ drive_stream(+ agent,+ prompt,+ history,+ max_turns,+ routing,+ loaded_buffer,+ register_loaded,+ recorder,+ usage_ctx,+ model,+ )+ .await+ }+ }+ }+}++/// Routes model api-id strings to the provider client that serves them.///-/// 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,+/// Holds native Anthropic and OpenAI Responses clients plus a registry of+/// OpenAI-compatible Chat Completions clients keyed by provider name. The+/// built-in [`OPENAI_PROVIDER`] always uses Responses; register compatible+/// providers with [`with_openai_provider`](Self::with_openai_provider).+#[derive(Clone)]+pub struct ModelRouter {+ anthropic: Arc<anthropic::Client>,+ openai: Arc<openai::Client>,+ openai_compatible: HashMap<String, Arc<openai::CompletionsClient>>,}-impl AllModelsRouter {- /// Build a router over the given provider clients.- pub fn new(anthropic_client: Arc<AnthropicClient>, openai_client: Arc<OpenAiClient>) -> Self {+impl ModelRouter {+ /// Build a router over native Anthropic and OpenAI Responses clients, with+ /// no OpenAI-compatible Chat Completions providers registered yet.+ pub fn new(anthropic: anthropic::Client, openai: openai::Client) -> Self {Self {- anthropic: AnthropicRouter::new(anthropic_client),- openai: OpenAiRouter::new(openai_client),+ anthropic: Arc::new(anthropic),+ openai: Arc::new(openai),+ openai_compatible: HashMap::new(),}}- /// Route `model` to a provider-tagged [`RoutedModel`].+ /// Build a router with the two built-in providers from the environment.+ ///+ /// Requires `ANTHROPIC_API_KEY` and `OPENAI_API_KEY`. Chain+ /// [`with_openai_provider`](Self::with_openai_provider) to add more.+ pub fn try_from_env() -> Result<Self, AgentError> {+ let env = ApiKeys::new()?;+ let anthropic = anthropic::Client::builder()+ .api_key(env.anthropic_api_key.to_string())+ .build()?;+ // Default base URL is api.openai.com; OpenAI's GPT models use+ // Responses API so reasoning models get max_output_tokens.+ let openai = openai::Client::builder()+ .api_key(env.openai_api_key.to_string())+ .build()?;+ Ok(Self::new(anthropic, openai))+ }++ /// The process-wide full router, built from the environment on first use.///- /// 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()))+ /// This is the only router the crate uses — every entry point routes through+ /// the same fully-populated instance, so a model id resolves identically+ /// everywhere. Register additional OpenAI-compatible providers here as they+ /// are added.+ pub(crate) fn shared() -> Result<&'static ModelRouter, AgentError> {+ static ROUTER: OnceLock<ModelRouter> = OnceLock::new();+ if let Some(router) = ROUTER.get() {+ return Ok(router);}+ let router = Self::try_from_env()?;+ Ok(ROUTER.get_or_init(|| router))+ }++ /// Register an already-built OpenAI-compatible Chat Completions client under+ /// `provider`.+ pub fn with_openai_client(+ mut self,+ provider: impl Into<String>,+ client: openai::CompletionsClient,+ ) -> Self {+ self.openai_compatible+ .insert(provider.into(), Arc::new(client));+ self}- /// 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))- })+ /// Register an OpenAI-compatible Chat Completions provider from a base URL+ /// and key.+ ///+ /// This is the whole cost of adding a provider — models served by it are+ /// then reachable as `provider/<model-id>`. The extension point for the+ /// open provider set; unused until the first extra provider is wired.+ #[allow(dead_code)]+ pub fn with_openai_provider(+ self,+ provider: impl Into<String>,+ base_url: &str,+ api_key: &str,+ ) -> Result<Self, AgentError> {+ let client = openai::CompletionsClient::builder()+ .api_key(api_key)+ .base_url(base_url)+ .build()?;+ Ok(self.with_openai_client(provider, client))+ }++ /// Route + build the agent in one step, falling back to the default model on+ /// an unroutable id.+ pub(crate) fn agent(+ &self,+ model: &str,+ handle: ToolServerHandle,+ system_prompt: &str,+ max_turns: usize,+ max_tokens: u64,+ ) -> ProviderAgent {+ self.route_or_default(model)+ .into_agent(handle, system_prompt, max_turns, max_tokens)+ }++ /// Route a `provider/model` id to the provider that serves it.+ ///+ /// Returns [`AgentError::UnknownModel`] if no provider claims it (and+ /// [`AgentError::MalformedModel`] if the id has no `provider/` segment).+ pub(crate) fn route<'a>(&self, model: &'a str) -> Result<RoutedModel<'a>, AgentError> {+ let parsed = Model::try_from(model)?;++ if parsed.provider() == ANTHROPIC_PROVIDER {+ return Ok(RoutedModel::Anthropic(AnthropicModel::new(+ parsed,+ self.anthropic.clone(),+ )));+ }+ if parsed.provider() == OPENAI_PROVIDER {+ return Ok(RoutedModel::OpenAiResponses(OpenAiResponsesModel::new(+ parsed,+ self.openai.clone(),+ )));+ }+ if let Some(client) = self.openai_compatible.get(parsed.provider()) {+ let client = Arc::clone(client);+ return Ok(RoutedModel::OpenAiChatCompletions(+ OpenAiChatCompletionsModel::new(parsed, client),+ ));+ }+ Err(AgentError::UnknownModel(model.to_string()))+ }++ /// Route `model`, falling back to the default model on an unroutable id.+ pub(crate) fn route_or_default<'a>(&self, model: &'a str) -> RoutedModel<'a> {+ self.route(model).unwrap_or_else(|_| self.default_model())+ }++ /// The default model: native Anthropic serving [`AgentModel::default`].+ fn default_model(&self) -> RoutedModel<'static> {+ let model = Model {+ provider: Cow::Borrowed(ANTHROPIC_PROVIDER),+ name: Cow::Borrowed(PredefinedModel::default().api_id()),+ };+ RoutedModel::Anthropic(AnthropicModel::new(model, self.anthropic.clone()))+ }+}++/// Build a rig agent from a completion model and per-session config.+fn build_agent<M: CompletionModel>(+ model: M,+ thinking: Option<serde_json::Value>,+ handle: ToolServerHandle,+ system_prompt: &str,+ max_turns: usize,+ max_tokens: u64,+) -> Agent<M> {+ let mut builder = AgentBuilder::new(model)+ .tool_server_handle(handle)+ .default_max_turns(max_turns)+ .max_tokens(max_tokens)+ .preamble(system_prompt);+ if let Some(params) = thinking {+ builder = builder.additional_params(params);+ }+ builder.build()+}++/// Run the agentic loop on `agent` and adapt rig's stream into the+/// provider-agnostic [`StreamPart`] stream consumed by DCS.+#[allow(clippy::too_many_arguments)]+async fn drive_stream<M>(+ agent: &Agent<M>,+ prompt: Message,+ history: Vec<Message>,+ max_turns: usize,+ routing: ToolRouter,+ loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,+ register_loaded: RegisterFn,+ recorder: Arc<dyn UsageRecorder>,+ usage_ctx: UsageContext,+ model: String,+) -> ChatCompletionStream<'static>+where+ M: CompletionModel + 'static,+ M::StreamingResponse: GetTokenUsage + Send + Sync,+{+ let (bridge, mut rx) = StreamBridge::channel(routing, loaded_buffer, register_loaded);++ let mut rig_stream = agent+ .stream_prompt(prompt)+ .with_history(history)+ .multi_turn(max_turns)+ .with_hook(bridge)+ .await;++ let stream = async_stream::stream! {+ let mut thinking_buf = String::new();++ while let Some(item) = rig_stream.next().await {+ while let Ok(part) = rx.try_recv() {+ yield part;+ }+ match item {+ Ok(MultiTurnStreamItem::StreamAssistantItem(+ StreamedAssistantContent::ReasoningDelta { reasoning, .. },+ )) => {+ thinking_buf.push_str(&reasoning);+ }+ other => {+ if !thinking_buf.is_empty() {+ yield Ok(StreamPart::Thinking(std::mem::take(&mut thinking_buf)));+ }+ match other {+ Ok(MultiTurnStreamItem::FinalResponse(final_resp)) => {+ let usage = final_resp.usage();+ // Best-effort cost logging; never fails the stream.+ recorder.record(usage_ctx.clone().into_event(+ model.clone(),+ usage.input_tokens,+ usage.output_tokens,+ ));+ yield Ok(StreamPart::Usage(crate::stream::Usage {+ input_tokens: usage.input_tokens,+ output_tokens: usage.output_tokens,+ }));+ }+ Err(e) => {+ yield Err(AgentError::Streaming(e));+ }+ _ => {}+ }+ }+ }+ }+ if !thinking_buf.is_empty() {+ yield Ok(StreamPart::Thinking(std::mem::take(&mut thinking_buf)));+ }+ while let Ok(part) = rx.try_recv() {+ yield part;+ }+ };++ Box::pin(stream)+}++#[cfg(test)]+mod test {+ use super::*;++ fn test_router() -> ModelRouter {+ let anthropic = anthropic::Client::builder()+ .api_key("test-anthropic-key")+ .build()+ .unwrap();+ let openai = openai::Client::builder()+ .api_key("test-openai-key")+ .build()+ .unwrap();+ let compatible = openai::CompletionsClient::builder()+ .api_key("test-compatible-key")+ .base_url("http://localhost:11434/v1")+ .build()+ .unwrap();++ ModelRouter::new(anthropic, openai).with_openai_client("local", compatible)+ }++ #[test]+ fn openai_provider_routes_to_responses() {+ let router = test_router();++ assert!(matches!(+ router.route("openai/gpt-5.5").unwrap(),+ RoutedModel::OpenAiResponses(_)+ ));+ }++ #[test]+ fn registered_openai_compatible_provider_routes_to_chat_completions() {+ let router = test_router();++ assert!(matches!(+ router.route("local/llama-3.3-70b").unwrap(),+ RoutedModel::OpenAiChatCompletions(_)+ ));}}diff --git a/rust/cloud-storage/agent/src/model/router/anthropic.rs b/rust/cloud-storage/agent/src/model/router/anthropic.rsdeleted file mode 100644index 54dff1c945..0000000000--- a/rust/cloud-storage/agent/src/model/router/anthropic.rs+++ /dev/null@@ -1,27 +0,0 @@-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.rsdeleted file mode 100644index f32375a5bb..0000000000--- a/rust/cloud-storage/agent/src/model/router/openai.rs+++ /dev/null@@ -1,27 +0,0 @@-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.rsdeleted file mode 100644index b52536f87c..0000000000--- a/rust/cloud-storage/agent/src/model/router/test.rs+++ /dev/null@@ -1,89 +0,0 @@-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 5f8a6a83e8..561d8bc1c4 100644--- a/rust/cloud-storage/agent/src/model/test.rs+++ b/rust/cloud-storage/agent/src/model/test.rs@@ -2,51 +2,48 @@ use super::*;#[test]fn default_is_smart() {- assert_eq!(AgentModel::default(), AgentModel::Smart);+ assert_eq!(PredefinedModel::default(), PredefinedModel::Smart);}#[test]fn smart_is_opus_4_8() {- assert_eq!(AgentModel::Smart.api_id(), "claude-opus-4-8");+ assert_eq!(PredefinedModel::Smart.api_id(), "claude-opus-4-8");assert_eq!(- serde_json::to_string(&AgentModel::Smart).unwrap(),+ serde_json::to_string(&PredefinedModel::Smart).unwrap(),r#""claude-opus-4-8""#);}#[test]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());+ assert_eq!(PredefinedModel::Fast.api_id(), "claude-haiku-4-5");+ assert_eq!(+ PredefinedModel::Fast.api_id(),+ PredefinedModel::Haiku4_5.api_id()+ );}#[test]fn retired_uses_default_api_id() {- assert_eq!(AgentModel::Retired.api_id(), AgentModel::Smart.api_id());+ assert_eq!(+ PredefinedModel::Retired.api_id(),+ PredefinedModel::Smart.api_id()+ );}#[test]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,+ PredefinedModel::Smart,+ PredefinedModel::Fast,+ PredefinedModel::Opus4_7,+ PredefinedModel::Sonnet4_6,+ PredefinedModel::Haiku4_5,+ PredefinedModel::Gpt5_5,+ PredefinedModel::Gpt5Mini,+ PredefinedModel::Retired,] {let wire = serde_json::to_string(&m).unwrap();assert_eq!(wire, format!(r#""{}""#, m.api_id()), "{m:?}");}}--#[test]-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.rsindex 2cdcbc4886..f3d0360ea4 100644--- a/rust/cloud-storage/agent/src/model/types.rs+++ b/rust/cloud-storage/agent/src/model/types.rs@@ -1,27 +1,52 @@-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>;+use std::borrow::Cow;++use crate::AgentError;+#[derive(Debug)]+pub struct Model<'a> {+ pub provider: Cow<'a, str>,+ pub name: Cow<'a, str>,+}++impl<'a> Model<'a> {+ pub fn provider(&self) -> &str {+ &self.provider+ }++ pub fn name(&self) -> &str {+ &self.name+ }+}++impl<'a> TryFrom<&'a str> for Model<'a> {+ type Error = crate::error::AgentError;++ fn try_from(value: &'a str) -> Result<Self, Self::Error> {+ value+ .trim()+ .split_once("/")+ .ok_or_else(|| AgentError::MalformedModel(value.to_string()))+ .map(|(provider, name)| Self {+ provider: Cow::Borrowed(provider),+ name: Cow::Borrowed(name),+ })+ }}-/// 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;+impl<'a> std::fmt::Display for Model<'a> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}/{}", self.provider, self.name)+ }+}++#[cfg(test)]+mod test {+ #[test]+ fn test_from_string() {+ let good = super::Model::try_from("anthropic/claude-big-burger").expect("good model");+ assert_eq!(good.name(), "claude-big-burger");+ assert_eq!(good.provider(), "anthropic");++ let bad = "claude-big-burger";+ assert!(super::Model::try_from(bad).is_err());+ }}diff --git a/rust/cloud-storage/agent/src/provider_env.rs b/rust/cloud-storage/agent/src/provider_env.rsdeleted file mode 100644index 722cc8691d..0000000000--- a/rust/cloud-storage/agent/src/provider_env.rs+++ /dev/null@@ -1,39 +0,0 @@-use rig_core::client::{ProviderClientError, ProviderClientResult};-use rig_core::providers::{anthropic, openai};--// TODO: remove this shim once our rig fork's client env helpers call macro_env_var directly.-/// Mirror rig-core's required env var helper, but with macro_env_var's APP_SECRETS_JSON support.-pub(crate) fn required_env_var(name: &'static str) -> ProviderClientResult<String> {- macro_env_var::read_env_var(name)- .map_err(|source| ProviderClientError::EnvironmentVariable { name, source })-}--/// Mirror rig-core's optional env var helper, but with macro_env_var's APP_SECRETS_JSON support.-pub(crate) fn optional_env_var(name: &'static str) -> ProviderClientResult<Option<String>> {- macro_env_var::optional_read_env_var(name)- .map_err(|source| ProviderClientError::EnvironmentVariable { name, source })-}--/// Create an Anthropic client from APP_SECRETS_JSON-aware environment values.-pub(crate) fn anthropic_client_from_env() -> ProviderClientResult<anthropic::Client> {- let api_key = required_env_var("ANTHROPIC_API_KEY")?;-- anthropic::Client::builder()- .api_key(api_key)- .build()- .map_err(Into::into)-}--/// Create an OpenAI client from APP_SECRETS_JSON-aware environment values.-pub(crate) fn openai_client_from_env() -> ProviderClientResult<openai::Client> {- let base_url = optional_env_var("OPENAI_BASE_URL")?;- let api_key = required_env_var("OPENAI_API_KEY")?;-- let mut builder = openai::Client::builder().api_key(api_key);-- if let Some(base_url) = base_url {- builder = builder.base_url(base_url);- }-- builder.build().map_err(Into::into)-}diff --git a/rust/cloud-storage/ai_tools/src/subagent.rs b/rust/cloud-storage/ai_tools/src/subagent.rsindex 75e9fb73f8..855aae36fd 100644--- a/rust/cloud-storage/ai_tools/src/subagent.rs+++ b/rust/cloud-storage/ai_tools/src/subagent.rs@@ -1,4 +1,4 @@-use agent::AgentModel;+use agent::PredefinedModel;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;use schemars::JsonSchema;@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};use crate::ToolServiceContext;-static SUBAGENT_MODEL: AgentModel = AgentModel::Smart;+static SUBAGENT_MODEL: PredefinedModel = PredefinedModel::Smart;static SUBAGENT_PROMPT: &str = include_str!("prompts/subagent.md");diff --git a/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rs b/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rsindex d8c1fdd5cb..36777a753f 100644--- a/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rs+++ b/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rs@@ -6,7 +6,7 @@use std::collections::HashSet;use std::fmt::Write as _;-use agent::AgentModel;+use agent::PredefinedModel;use uuid::Uuid;use macro_user_id::user_id::MacroUserIdStr;@@ -17,7 +17,7 @@ use crate::domain::models::{use crate::domain::ports::CallSummarizer;/// Default model used when summarizing a call transcript.-const SUMMARIZATION_MODEL: AgentModel = AgentModel::Sonnet4_6;+const SUMMARIZATION_MODEL: PredefinedModel = PredefinedModel::Sonnet4_6;/// System prompt framing the LLM's task: produce a concise, factual call summary.const SUMMARIZATION_SYSTEM_PROMPT: &str = "\diff --git a/rust/cloud-storage/chat/src/domain/models/chat.rs b/rust/cloud-storage/chat/src/domain/models/chat.rsindex ac46884b88..a132ffe62f 100644--- a/rust/cloud-storage/chat/src/domain/models/chat.rs+++ b/rust/cloud-storage/chat/src/domain/models/chat.rs@@ -57,7 +57,7 @@ pub struct ChatResponse {pub name: String,/// The messages in the chat.pub messages: Vec<ChatMessageWithAttachments>,- /// The model used to generate the chat (provider api id).+ /// The model used to generate the chat (`provider/model` id).pub model: Option<String>,/// The time the chat was created.pub created_at: Option<chrono::DateTime<chrono::Utc>>,diff --git a/rust/cloud-storage/chat/src/domain/models/mod.rs b/rust/cloud-storage/chat/src/domain/models/mod.rsindex 62a4d85502..a8e75fec23 100644--- a/rust/cloud-storage/chat/src/domain/models/mod.rs+++ b/rust/cloud-storage/chat/src/domain/models/mod.rs@@ -8,4 +8,4 @@ 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};+pub use model_access::{CHAT_MODELS, FREE_MODEL};diff --git a/rust/cloud-storage/chat/src/domain/models/model_access.rs b/rust/cloud-storage/chat/src/domain/models/model_access.rsindex 6a8290de73..69afe95949 100644--- a/rust/cloud-storage/chat/src/domain/models/model_access.rs+++ b/rust/cloud-storage/chat/src/domain/models/model_access.rs@@ -3,39 +3,15 @@//! 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,+pub const CHAT_MODELS: &[&str] = &[+ "anthropic/claude-opus-4-8",+ "anthropic/claude-haiku-4-5",+ "anthropic/claude-opus-4-7",+ "anthropic/claude-sonnet-4-6",+ "openai/gpt-5.5",+ "openai/gpt-5-mini",];/// 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>,-}+pub const FREE_MODEL: &str = "anthropic/claude-haiku-4-5";diff --git a/rust/cloud-storage/chat/src/domain/ports/model_access.rs b/rust/cloud-storage/chat/src/domain/ports/model_access.rsindex 74a52c516a..d6f3a989a2 100644--- a/rust/cloud-storage/chat/src/domain/ports/model_access.rs+++ b/rust/cloud-storage/chat/src/domain/ports/model_access.rs@@ -1,17 +1,11 @@-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.+/// to validate a requested model).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+ /// provider-qualified model identified by `model_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/model_access.rs b/rust/cloud-storage/chat/src/domain/service/model_access.rsindex fb275f8043..97a3b1612a 100644--- a/rust/cloud-storage/chat/src/domain/service/model_access.rs+++ b/rust/cloud-storage/chat/src/domain/service/model_access.rs@@ -1,6 +1,4 @@-use agent::AgentModel;--use crate::domain::models::model_access::{CHAT_MODELS, FREE_MODEL, ModelAccess, ModelsResponse};+use crate::domain::models::model_access::FREE_MODEL;use crate::domain::ports::ModelAccessService;/// Default [`ModelAccessService`]: free users get only [`FREE_MODEL`],@@ -8,30 +6,9 @@ use crate::domain::ports::ModelAccessService;#[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))+ professional || model_id == FREE_MODEL}}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.rsindex e36a2fa76e..10be7f52bb 100644--- a/rust/cloud-storage/chat/src/domain/service/model_access/test.rs+++ b/rust/cloud-storage/chat/src/domain/service/model_access/test.rs@@ -1,14 +1,19 @@use super::*;-const HAIKU: &str = "claude-haiku-4-5";-const OPUS: &str = "claude-opus-4-8";+const HAIKU: &str = "anthropic/claude-haiku-4-5";+const OPUS: &str = "anthropic/claude-opus-4-8";+const OPUS_4_7: &str = "anthropic/claude-opus-4-7";+const SONNET_4_6: &str = "anthropic/claude-sonnet-4-6";+const GPT_5_5: &str = "openai/gpt-5.5";+const GPT_5_MINI: &str = "openai/gpt-5-mini";#[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"));+ assert!(!svc.has_access(false, SONNET_4_6));+ assert!(!svc.has_access(false, GPT_5_5));}#[test]@@ -16,27 +21,8 @@ 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));+ assert!(svc.has_access(true, OPUS_4_7));+ assert!(svc.has_access(true, SONNET_4_6));+ assert!(svc.has_access(true, GPT_5_5));+ assert!(svc.has_access(true, GPT_5_MINI));}diff --git a/rust/cloud-storage/chat/src/inbound/http/extractors.rs b/rust/cloud-storage/chat/src/inbound/http/extractors.rsindex 67c8e35165..0fa39ff867 100644--- a/rust/cloud-storage/chat/src/inbound/http/extractors.rs+++ b/rust/cloud-storage/chat/src/inbound/http/extractors.rs@@ -3,7 +3,6 @@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;use axum::http::request::Parts;@@ -27,15 +26,16 @@ impl ChatModelAccess {self.professional}- /// Whether the user may use the model identified by `model_id` (an api id).+ /// Whether the user may use the provider-qualified model identified by+ /// `model_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 {+ pub fn model(&self) -> &'static str {if self.professional {- AgentModel::Smart+ "anthropic/claude-opus-4-8"} else {FREE_MODEL}@@ -114,16 +114,17 @@ mod test {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!(free.has_access(FREE_MODEL));+ assert!(!free.has_access("anthropic/claude-opus-4-8"));}#[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()));+ assert_eq!(pro.model(), "anthropic/claude-opus-4-8");+ assert!(pro.has_access("anthropic/claude-opus-4-8"));+ assert!(pro.has_access(FREE_MODEL));+ assert!(pro.has_access("openai/gpt-5.5"));}// Permission strings unrelated to the professional flag don't grant access.@@ -131,6 +132,6 @@ mod test {fn unrelated_permissions_stay_free() {let acc = access(&[PermissionId::WriteHaiku, PermissionId::WriteOpus]);assert!(!acc.professional());- assert!(!acc.has_access(AgentModel::Smart.api_id()));+ assert!(!acc.has_access("anthropic/claude-opus-4-8"));}}diff --git a/rust/cloud-storage/chat/src/inbound/http/mod.rs b/rust/cloud-storage/chat/src/inbound/http/mod.rsindex 30f4c2da7a..17f47c715a 100644--- a/rust/cloud-storage/chat/src/inbound/http/mod.rs+++ b/rust/cloud-storage/chat/src/inbound/http/mod.rs@@ -1,5 +1,4 @@//! 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.rsdeleted file mode 100644index 1b6fe1111c..0000000000--- a/rust/cloud-storage/chat/src/inbound/http/models.rs+++ /dev/null@@ -1,36 +0,0 @@-//! 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/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex 24206132ea..455c129eaa 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -13,10 +13,6 @@ path = "src/main.rs"name = "document_cognition_service_openapi"path = "src/openapi.rs"-[[bin]]-name = "document_cognition_service_models"-path = "src/models_bin.rs"-[features]local = []local_auth = ["macro_middleware/local_auth"]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 6fd1dfc4c3..8d3268f2b0 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,8 +6,7 @@ use axum::{Router,routing::{get, post},};-use chat::domain::service::{ChatServiceImpl, ModelAccessServiceImpl};-use chat::inbound::http::models::models_router;+use chat::domain::service::ChatServiceImpl;use chat::inbound::http::router::{ChatRouterState, chat_create_router, chat_id_router};use chat::outbound::postgres::PgChatRepo;use entity_access::domain::service::EntityAccessServiceImpl;@@ -61,19 +60,6 @@ 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 0aad732f3b..99e2c28cf0 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@@ -72,7 +72,7 @@ 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 (provider api id)+ /// The model to respond with (`provider/model` id)pub model: String,/// Additional system instructions appended to the base system prompt#[serde(skip_serializing_if = "Option::is_none")]diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/test.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/test.rsindex e20d7d1f51..36219ef578 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/test.rs@@ -1,5 +1,16 @@use super::*;+#[test]+fn send_chat_message_request_accepts_arbitrary_model_string() {+ let request: HttpSendChatMessageRequest = serde_json::from_value(serde_json::json!({+ "content": "hello",+ "model": "custom-provider/custom-model",+ }))+ .unwrap();++ assert_eq!(request.model, "custom-provider/custom-model");+}+fn text(s: &str) -> AssistantMessagePart {AssistantMessagePart::Text { text: s.into() }}diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rsindex f592476b1c..97e5a9cd5c 100644--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs@@ -30,10 +30,7 @@ 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, ModelAccess, ModelsResponse, WebCitation,-};-use chat::inbound::http::models as chat_models;+use chat::domain::models::{ChatResponse, GetChatResponse, WebCitation};use chat::inbound::http::router::{self as chat_router, CallToolRequest, CallToolResponse, CreateChatRequest,GetChatPermissionsResponse, PatchChatRequest, RejectToolCallRequest, UpdateToolCallRequest,@@ -78,7 +75,6 @@ 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,@@ -101,8 +97,6 @@ use utoipa::OpenApi;components(schemas(DocumentCognitionServiceApiVersion,- ModelAccess,- ModelsResponse,// GenericStringIDResponse,GenericErrorResponse,diff --git a/rust/cloud-storage/document_cognition_service/src/core/mod.rs b/rust/cloud-storage/document_cognition_service/src/core/mod.rsindex f823c4bf40..0b6d2c4eab 100644--- a/rust/cloud-storage/document_cognition_service/src/core/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/core/mod.rs@@ -1,2 +1 @@pub mod constants;-pub mod model;diff --git a/rust/cloud-storage/document_cognition_service/src/core/model.rs b/rust/cloud-storage/document_cognition_service/src/core/model.rsdeleted file mode 100644index e01271fbbf..0000000000--- a/rust/cloud-storage/document_cognition_service/src/core/model.rs+++ /dev/null@@ -1,6 +0,0 @@-use agent::AgentModel;--/// 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 0545a0bbff..9f00ef67b9 100644--- a/rust/cloud-storage/document_cognition_service/src/model/chats.rs+++ b/rust/cloud-storage/document_cognition_service/src/model/chats.rs@@ -18,7 +18,7 @@ pub struct ChatResponse {pub name: String,/// The messages in the chatpub messages: Vec<ChatMessageWithAttachments>,- /// The model used to generate the chat (provider api id)+ /// The model used to generate the chat (`provider/model` id)pub model: Option<String>,/// The time the chat was createdpub created_at: Option<chrono::DateTime<chrono::Utc>>,@@ -30,9 +30,6 @@ pub struct ChatResponse {/// Current number of tokens in the chat// killpub token_count: Option<i64>,- /// Available models for the chat (provider api ids)- // kill- 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 51b3db4cc0..9295956117 100644--- a/rust/cloud-storage/document_cognition_service/src/model/stream.rs+++ b/rust/cloud-storage/document_cognition_service/src/model/stream.rs@@ -24,7 +24,7 @@ pub struct SendChatMessagePayload {pub content: String,/// Id of the chat the message belongs topub chat_id: String,- /// the chat model to respond with (provider api id)+ /// the chat model to respond with (`provider/model` id)pub model: String,/// Additional system instructions appended to the base system prompt#[serde(skip_serializing_if = "Option::is_none")]diff --git a/rust/cloud-storage/document_cognition_service/src/models_bin.rs b/rust/cloud-storage/document_cognition_service/src/models_bin.rsdeleted file mode 100644index 1803595314..0000000000--- a/rust/cloud-storage/document_cognition_service/src/models_bin.rs+++ /dev/null@@ -1,54 +0,0 @@-#![recursion_limit = "256"]-#![allow(unused)]--mod api;-mod config;-mod core;-mod model;-mod service;--pub use config::Config;--use crate::core::model::CHAT_MODELS;-use agent::AgentModel;-use serde::Serialize;--#[derive(Serialize)]-#[serde(rename_all = "camelCase")]-struct ModelSchema {- pub name: String,- pub provider: &'static str,- pub metadata: ModelMetadata,-}--#[derive(Serialize)]-#[serde(rename_all = "camelCase")]-struct ModelMetadata {- pub context_window: u64,-}--#[derive(Serialize)]-struct ModelsResponse {- pub models: Vec<ModelSchema>,-}--impl From<AgentModel> for ModelSchema {- fn from(m: AgentModel) -> Self {- Self {- name: m.api_id().to_owned(),- provider: m.provider().as_str(),- metadata: ModelMetadata {- context_window: m.context_window(),- },- }- }-}--fn main() {- let models = CHAT_MODELS- .iter()- .map(|m| ModelSchema::from(*m))- .collect::<Vec<_>>();- let data = ModelsResponse { models };- println!("{}", serde_json::to_string_pretty(&data).unwrap());-}diff --git a/rust/cloud-storage/document_cognition_service/src/service/chat_renamer.rs b/rust/cloud-storage/document_cognition_service/src/service/chat_renamer.rsindex e1b13447f8..21f8d5d4ec 100644--- a/rust/cloud-storage/document_cognition_service/src/service/chat_renamer.rs+++ b/rust/cloud-storage/document_cognition_service/src/service/chat_renamer.rs@@ -1,5 +1,5 @@use crate::api::context::ApiContext;-use agent::AgentModel;+use agent::PredefinedModel;use chat::domain::models::PatchChatArgs;use chat::domain::ports::ChatRepo;use chat::outbound::postgres::PgChatRepo;@@ -110,7 +110,7 @@ async fn generate_chat_name(let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::ChatRename, user_id).with_entity(macro_uuid::string_to_uuid(chat_id).ok());let response = agent::complete(- AgentModel::Fast,+ PredefinedModel::Fast,CHAT_RENAME_SYSTEM_PROMPT,&rename_request,recorder,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 b9bd239e67..ed9f990d45 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@@ -1,6 +1,5 @@// biohazarduse crate::api::context::ApiContext;-use crate::core::model::{CHAT_MODELS, FALLBACK_MODEL};use crate::model::chats::ChatResponse;use anyhow::Context;use macro_db_client::dcs::get_chat::{get_chat_db, get_messages, get_web_citations};@@ -20,8 +19,6 @@ pub async fn get_chat(.await.context("Failed to get messages")?;- let model = Some(FALLBACK_MODEL.to_string());-let web_citations = get_web_citations(&ctx.db, chat_id).await.unwrap_or_default()@@ -47,14 +44,13 @@ pub async fn get_chat(id: chat.id,user_id: chat.user_id,name: chat.name,- model,+ model: chat.model,messages,project_id: chat.project_id,created_at: chat.created_at,updated_at: chat.updated_at,attachments: vec![],token_count: chat.token_count,- available_models: CHAT_MODELS.iter().map(|m| m.to_string()).collect(),web_citations,is_persistent: chat.is_persistent,})diff --git a/rust/cloud-storage/memory/src/domain/service.rs b/rust/cloud-storage/memory/src/domain/service.rsindex 1423ab2295..e025b666ec 100644--- a/rust/cloud-storage/memory/src/domain/service.rs+++ b/rust/cloud-storage/memory/src/domain/service.rs@@ -1,6 +1,6 @@use super::ports::*;use agent::types::{ChatMessage, ChatMessageContent, Role};-use agent::{AgentLoop, AgentModel, StreamPart};+use agent::{AgentLoop, PredefinedModel, StreamPart};use ai_tools::{ToolServiceContext, ToolSetWithPrompt};use chrono::Utc;use futures::stream::StreamExt;@@ -8,8 +8,8 @@ use macro_env::Environment;use serde::Deserialize;use std::sync::Arc;-static GENERATION_MODEL: AgentModel = AgentModel::Smart;-static JUDGE_MODEL: AgentModel = AgentModel::Sonnet4_6;+static GENERATION_MODEL: PredefinedModel = PredefinedModel::Smart;+static JUDGE_MODEL: PredefinedModel = PredefinedModel::Sonnet4_6;static GENERATE_MEMORY_PROMPT: &str = "\Use tool calls to research who I am, what I care about, what I'm working on, \diff --git a/rust/cloud-storage/task_dedup/src/outbound/judge.rs b/rust/cloud-storage/task_dedup/src/outbound/judge.rsindex 08968262a0..7fe5d6b98f 100644--- a/rust/cloud-storage/task_dedup/src/outbound/judge.rs+++ b/rust/cloud-storage/task_dedup/src/outbound/judge.rs@@ -1,7 +1,7 @@//! Duplicate judge adapters.use agent::structured_output::{DynamicSchema, dynamic_structured_completion};-use agent::{AgentModel, Message};+use agent::{Message, PredefinedModel};use async_trait::async_trait;use serde::{Deserialize, Serialize};use serde_json::json;@@ -41,7 +41,7 @@ In the reason, briefly compare the concrete categories that matter most for the/// When the model call fails it defaults to *not* a duplicate, so an outage/// can't fabricate matches.pub struct AgentDuplicateJudge {- model: AgentModel,+ model: PredefinedModel,recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>,}@@ -55,14 +55,14 @@ impl AgentDuplicateJudge {/// Creates a new judge using the fast agent model.pub fn new(recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>) -> Self {Self {- model: AgentModel::Fast,+ model: PredefinedModel::Fast,recorder,}}/// Creates a new judge with an explicit agent model.pub fn with_model(- model: AgentModel,+ model: PredefinedModel,recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>,) -> Self {Self { model, recorder }