From 2a09995c5a736b1bb514627a3ce46f138c139ee8 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 03:07:00 -0800 Subject: [PATCH 1/2] fix(models): stop resolving sim-auto to ollama outside the model router sim-auto is a pseudo-model that only the agent, router and evaluator handlers resolve, through the model router, at execution time. Every other provider lookup fell through to getProviderFromModel's unknown-model default and treated it as an Ollama model: - translate and guardrails offered Auto but never resolve it, so a run sent model sim-auto to provider ollama (or a provider allowlist refused it as ollama); editing validation accepted it there and the catalog advertised it - assertModelAllowed refused sim-auto as provider ollama under allowedModelProviders, while the client gate allowed it - the usage breakdown gave sim-auto rows the Ollama mark and merged BYOK sim-auto usage into the Ollama row - the editor's API-key reset, tool-usage control and attachment cap looked up ollama for it (hiding the tool-usage control for Auto), and the first two threw uncaught on a blacklisted model - getPiModelOptions and the router/evaluator serialization looked it up on every call, logging a provider warning each time Now: - getProviderFromModel throws an explicit error for sim-auto instead of answering ollama; the guardrails Vertex-credential check skips sim-auto so it cannot reach that throw - DEFAULT_BLOCK_MODEL (providers/default-model.ts, dependency-free) is the one source for the agent/router/evaluator default and the executor's DEFAULT_MODELs, which are what sim-auto falls back to - getSerializedModelProviderId becomes resolveModelProviderId: an unset, reference or sim-auto model answers as DEFAULT_BLOCK_MODEL, and it still never throws. The agent block (dropping its own special case) and the three editor call sites use it, so they no longer throw - getModelOptions no longer includes Auto; getModelOptionsWithAuto (router, evaluator) and getAgentModelOptions do. Editing validation reads one declarative MODEL_OPTION_SOURCES map instead of comparing option functions: only getModelOptions and getModelOptionsWithAuto fields are checked against the catalog, sim-auto is accepted only where the source offers Auto on hosted Sim, and a reference or {{ENV_VAR}} value is passed through (router and evaluator used to reject them). The agent's model field stays unvalidated, as before - assertModelAllowed skips the provider allowlist for sim-auto (the router gates each pool candidate) but still applies deniedModels - the usage breakdown attributes sim-auto to its own key, labelled Auto, in the model and BYOK dimensions; every other model is attributed as before --- .../components/file-upload/file-upload.tsx | 8 +- .../components/tool-input/tool-input.test.ts | 13 +++ .../components/tool-input/tool-input.tsx | 8 +- .../sub-block/components/tool-input/utils.ts | 12 +++ .../sub-block/hooks/use-sub-block-value.ts | 6 +- apps/sim/blocks/blocks/agent.test.ts | 12 +++ apps/sim/blocks/blocks/agent.ts | 14 +--- apps/sim/blocks/blocks/evaluator.ts | 11 +-- apps/sim/blocks/blocks/router.ts | 17 ++-- apps/sim/blocks/utils.test.ts | 79 ++++++++++++++--- apps/sim/blocks/utils.ts | 77 +++++++++++------ .../utils/permission-check.test.ts | 20 +++++ .../access-control/utils/permission-check.ts | 7 +- .../components/usage-consumers.tsx | 3 + apps/sim/executor/constants.ts | 7 +- .../get-organization-usage-breakdown.test.ts | 60 +++++++++++++ .../get-organization-usage-breakdown.ts | 27 ++++-- .../guardrails/validate-hallucination.test.ts | 14 ++++ .../internal/guardrails/operations.test.ts | 23 +++++ .../sim/lib/internal/guardrails/operations.ts | 9 +- .../read-workflow-lint-agent-tools.test.ts | 2 +- .../read-workflow-lint-refs.test.ts | 2 +- .../editing/validation-models.test.ts | 84 +++++++++++++++++++ .../lib/workflows/editing/validation.test.ts | 1 + apps/sim/lib/workflows/editing/validation.ts | 19 +++-- apps/sim/providers/default-model.ts | 6 ++ apps/sim/providers/utils.test.ts | 7 ++ apps/sim/providers/utils.ts | 14 ++++ apps/sim/tools/llm/chat.test.ts | 10 +++ 29 files changed, 478 insertions(+), 94 deletions(-) create mode 100644 apps/sim/lib/billing/application/organization-usage/get-organization-usage-breakdown.test.ts create mode 100644 apps/sim/lib/workflows/editing/validation-models.test.ts create mode 100644 apps/sim/providers/default-model.ts diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-upload/file-upload.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-upload/file-upload.tsx index c8457d034f0..55972551818 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-upload/file-upload.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-upload/file-upload.tsx @@ -28,6 +28,7 @@ import { useActiveCanonicalSubBlockValue } from '@/app/workspace/[workspaceId]/w import { useResourceFolders } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-resource-folders' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' import { useActiveSearchTarget } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/providers/active-search-target-provider' +import { resolveModelProviderId } from '@/blocks/utils' import { invalidateWorkspaceFileReads } from '@/hooks/queries/utils/workspace-file-cache' import { workspaceFileListParams, @@ -42,7 +43,6 @@ import { } from '@/hooks/queries/workspace-files' import { useSearchFilterValue } from '@/hooks/use-search-filter-value' import { getProviderAttachmentMaxBytes } from '@/providers/attachments' -import { getProviderFromModel } from '@/providers/utils' import { useWorkflowRegistry } from '@/stores/workflows/registry/store' import { useWorkflowStore } from '@/stores/workflows/workflow/store' @@ -322,11 +322,7 @@ export function FileUpload({ const maxSizeInBytes = useMemo(() => { const fallback = maxSize * 1024 * 1024 if (typeof modelValue !== 'string' || !modelValue) return fallback - try { - return Math.max(fallback, getProviderAttachmentMaxBytes(getProviderFromModel(modelValue))) - } catch { - return fallback - } + return Math.max(fallback, getProviderAttachmentMaxBytes(resolveModelProviderId(modelValue))) }, [modelValue, maxSize]) const maxSizeLabel = `${Math.round(maxSizeInBytes / (1024 * 1024))}MB` diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.test.ts b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.test.ts index 79b6e14a8e8..3391c26b06e 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.test.ts +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.test.ts @@ -3,6 +3,7 @@ import type { StoredTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/co import { isAgentToolBlock, isCustomToolAlreadySelected, + supportsToolUsageControlForModel, } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils' describe('isAgentToolBlock', () => { @@ -47,3 +48,15 @@ describe('already-selected checks', () => { ).toBe(false) }) }) + +describe('supportsToolUsageControlForModel', () => { + it('offers the control for Auto, which falls back to a provider that supports it', () => { + expect(supportsToolUsageControlForModel('agent', 'sim-auto')).toBe(true) + }) + + it('offers it for a supporting provider and never without a model', () => { + expect(supportsToolUsageControlForModel('agent', 'claude-sonnet-5-5')).toBe(true) + expect(supportsToolUsageControlForModel('agent', '')).toBe(false) + expect(supportsToolUsageControlForModel('mothership', '')).toBe(true) + }) +}) diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx index f19e9af9771..7f007010acc 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx @@ -72,6 +72,7 @@ import { isCustomToolAlreadySelected, isMcpToolAlreadySelected, isWorkflowAlreadySelected, + supportsToolUsageControlForModel, } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils' import { getActiveWorkflowSearchHighlight } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/workflow-search-highlight' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' @@ -105,8 +106,7 @@ import { useCollaborativeWorkflow } from '@/hooks/use-collaborative-workflow' import { useOperationAccess } from '@/hooks/use-operation-access' import { usePermissionConfig } from '@/hooks/use-permission-config' import { useSettingsNavigation } from '@/hooks/use-settings-navigation' -import { supportsForcedToolUse, supportsToolUsageControl } from '@/providers/models' -import { getProviderFromModel } from '@/providers/utils' +import { supportsForcedToolUse } from '@/providers/models' import type { ActiveSearchTarget } from '@/stores/panel/editor/store' import { useSubBlockStore } from '@/stores/workflows/subblock/store' import { useWorkflowStore } from '@/stores/workflows/workflow/store' @@ -603,9 +603,7 @@ export const ToolInput = memo(function ToolInput({ const modelValue = useSubBlockStore((state) => state.getValue(blockId, 'model')) const model = typeof modelValue === 'string' ? modelValue : '' - const provider = model ? getProviderFromModel(model) : '' - const supportsToolControl = - blockType === 'mothership' || (provider ? supportsToolUsageControl(provider) : false) + const supportsToolControl = supportsToolUsageControlForModel(blockType, model) const supportsForce = blockType === 'mothership' || supportsForcedToolUse(model) const { diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts index 49a0bb1428b..710674aeea2 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts @@ -1,6 +1,8 @@ import { stripVersionSuffix } from '@sim/utils/string' import type { StoredTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/types' import type { BlockConfig } from '@/blocks/types' +import { resolveModelProviderId } from '@/blocks/utils' +import { supportsToolUsageControl } from '@/providers/models' /** * Core blocks the agent tool picker offers even though they are not @@ -71,3 +73,13 @@ export function isWorkflowAlreadySelected( (tool) => tool.type === 'workflow_input' && tool.params?.workflowId === workflowId ) } + +/** + * Whether the tool picker offers the per-tool usage control (auto, force, none) for the + * block's model. Sim Chat always does; any other block asks its model's provider. + */ +export function supportsToolUsageControlForModel(blockType: string, model: string): boolean { + if (blockType === 'mothership') return true + if (!model) return false + return supportsToolUsageControl(resolveModelProviderId(model)) +} diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value.ts b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value.ts index 6381ff29cba..51751367e03 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value.ts +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value.ts @@ -4,8 +4,8 @@ import { isEqual } from 'es-toolkit' import { useShallow } from 'zustand/react/shallow' import { useStoreWithEqualityFn } from 'zustand/traditional' import { isMcpRuntimeReference } from '@/lib/mcp/operation-policy' +import { resolveModelProviderId } from '@/blocks/utils' import { useCollaborativeWorkflow } from '@/hooks/use-collaborative-workflow' -import { getProviderFromModel } from '@/providers/utils' import { useWorkflowDiffStore } from '@/stores/workflow-diff/store' import { useWorkflowRegistry } from '@/stores/workflows/registry/store' import { useSubBlockStore } from '@/stores/workflows/subblock/store' @@ -193,8 +193,8 @@ export function useSubBlockValue( const currentApiKeyValue = useSubBlockStore.getState().getValue(blockId, 'apiKey') if (currentApiKeyValue && currentApiKeyValue !== '') { const oldModelValue = storeValue as string - const oldProvider = oldModelValue ? getProviderFromModel(oldModelValue) : null - const newProvider = getProviderFromModel(newValue) + const oldProvider = oldModelValue ? resolveModelProviderId(oldModelValue) : null + const newProvider = resolveModelProviderId(newValue) if (oldProvider !== newProvider) { collaborativeSetSubblockValue(blockId, 'apiKey', '') } diff --git a/apps/sim/blocks/blocks/agent.test.ts b/apps/sim/blocks/blocks/agent.test.ts index c701852780e..05936948cfb 100644 --- a/apps/sim/blocks/blocks/agent.test.ts +++ b/apps/sim/blocks/blocks/agent.test.ts @@ -112,4 +112,16 @@ describe('AgentBlock', () => { }) }) }) + + describe('tools.config.tool function', () => { + const toolFunction = AgentBlock.tools.config?.tool + + it('records the provider sim-auto falls back to, since it has none of its own', () => { + expect(toolFunction?.({ model: 'sim-auto' })).toBe('anthropic') + }) + + it('falls back to the same provider when no model is set', () => { + expect(toolFunction?.({})).toBe('anthropic') + }) + }) }) diff --git a/apps/sim/blocks/blocks/agent.ts b/apps/sim/blocks/blocks/agent.ts index 816a7232fe4..8316335b58a 100644 --- a/apps/sim/blocks/blocks/agent.ts +++ b/apps/sim/blocks/blocks/agent.ts @@ -8,10 +8,11 @@ import { getAgentModelOptions, getModelCapabilityCondition, getProviderCredentialSubBlocks, - getSerializedModelProviderId, normalizeFileInput, RESPONSE_FORMAT_WAND_CONFIG, + resolveModelProviderId, } from '@/blocks/utils' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' import { getBaseModelProviders, getEvaluationModels, @@ -24,15 +25,11 @@ import { getReasoningEffortValuesForModel, getThinkingLevelsForModel, getVerbosityValuesForModel, - isAutoModel, supportsTemperature, } from '@/providers/models' const logger = createLogger('AgentBlock') -/** Model the agent block falls back to when `model` is unset or the auto pseudo-model. */ -const AGENT_FALLBACK_MODEL = 'claude-sonnet-5-5' - const MODELS_WITH_REASONING_EFFORT = getModelsWithReasoningEffort() const MODELS_WITH_VERBOSITY = getModelsWithVerbosity() const MODELS_WITH_THINKING = getModelsWithThinking() @@ -130,7 +127,7 @@ Return ONLY the JSON array.`, type: 'combobox', placeholder: 'Type or select a model...', required: true, - defaultValue: 'claude-sonnet-5-5', + defaultValue: DEFAULT_BLOCK_MODEL, options: getAgentModelOptions, commandSearchable: true, }, @@ -428,10 +425,7 @@ Return ONLY the JSON array.`, ], config: { tool: (params: Record) => { - const model = params.model || AGENT_FALLBACK_MODEL - // sim-auto has no provider of its own until the pool resolves it at execution time. - const lookupModel = isAutoModel(model) ? AGENT_FALLBACK_MODEL : model - return getSerializedModelProviderId(lookupModel, AGENT_FALLBACK_MODEL) + return resolveModelProviderId(params.model) }, params: (params: Record) => { const normalizedFiles = normalizeFileInput(params.files) diff --git a/apps/sim/blocks/blocks/evaluator.ts b/apps/sim/blocks/blocks/evaluator.ts index 11708998be6..95890acf151 100644 --- a/apps/sim/blocks/blocks/evaluator.ts +++ b/apps/sim/blocks/blocks/evaluator.ts @@ -4,11 +4,12 @@ import { getModelFallbackSubBlock, MODEL_FALLBACK_INPUTS } from '@/blocks/model- import type { BlockConfig, ParamType } from '@/blocks/types' import { BEDROCK_SAVED_CREDENTIAL_INPUTS, - getModelOptions, + getModelOptionsWithAuto, getProviderCredentialSubBlocks, - getSerializedModelProviderId, PROVIDER_CREDENTIAL_INPUTS, + resolveModelProviderId, } from '@/blocks/utils' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' const logger = createLogger('EvaluatorBlock') @@ -168,8 +169,8 @@ export const EvaluatorBlock: BlockConfig = { type: 'combobox', placeholder: 'Type or select a model...', required: true, - defaultValue: 'claude-sonnet-5-5', - options: getModelOptions, + defaultValue: DEFAULT_BLOCK_MODEL, + options: getModelOptionsWithAuto, }, ...getProviderCredentialSubBlocks({ bedrockSavedCredential: true }), getModelFallbackSubBlock(), @@ -236,7 +237,7 @@ export const EvaluatorBlock: BlockConfig = { 'deepseek_reasoner', ], config: { - tool: (params: Record) => getSerializedModelProviderId(params.model), + tool: (params: Record) => resolveModelProviderId(params.model), }, }, inputs: { diff --git a/apps/sim/blocks/blocks/router.ts b/apps/sim/blocks/blocks/router.ts index a978d261f18..60aa7ef7436 100644 --- a/apps/sim/blocks/blocks/router.ts +++ b/apps/sim/blocks/blocks/router.ts @@ -3,11 +3,12 @@ import { getModelFallbackSubBlock, MODEL_FALLBACK_INPUTS } from '@/blocks/model- import { AuthMode, type BlockConfig } from '@/blocks/types' import { BEDROCK_SAVED_CREDENTIAL_INPUTS, - getModelOptions, + getModelOptionsWithAuto, getProviderCredentialSubBlocks, - getSerializedModelProviderId, PROVIDER_CREDENTIAL_INPUTS, + resolveModelProviderId, } from '@/blocks/utils' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' interface TargetBlock { id: string @@ -161,8 +162,8 @@ export const RouterBlock: BlockConfig = { type: 'combobox', placeholder: 'Type or select a model...', required: true, - defaultValue: 'claude-sonnet-5-5', - options: getModelOptions, + defaultValue: DEFAULT_BLOCK_MODEL, + options: getModelOptionsWithAuto, }, ...getProviderCredentialSubBlocks({ bedrockSavedCredential: true }), getModelFallbackSubBlock(), @@ -194,7 +195,7 @@ export const RouterBlock: BlockConfig = { 'deepseek_reasoner', ], config: { - tool: (params: Record) => getSerializedModelProviderId(params.model), + tool: (params: Record) => resolveModelProviderId(params.model), }, }, inputs: { @@ -253,8 +254,8 @@ export const RouterV2Block: BlockConfig = { type: 'combobox', placeholder: 'Type or select a model...', required: true, - defaultValue: 'claude-sonnet-5-5', - options: getModelOptions, + defaultValue: DEFAULT_BLOCK_MODEL, + options: getModelOptionsWithAuto, }, ...getProviderCredentialSubBlocks({ bedrockSavedCredential: true }), getModelFallbackSubBlock(), @@ -269,7 +270,7 @@ export const RouterV2Block: BlockConfig = { 'deepseek_reasoner', ], config: { - tool: (params: Record) => getSerializedModelProviderId(params.model), + tool: (params: Record) => resolveModelProviderId(params.model), }, }, inputs: { diff --git a/apps/sim/blocks/utils.test.ts b/apps/sim/blocks/utils.test.ts index 9d81b8f0d4e..fbcd10bdb24 100644 --- a/apps/sim/blocks/utils.test.ts +++ b/apps/sim/blocks/utils.test.ts @@ -1,7 +1,7 @@ import { resetEnvFlagsMock, setEnvFlags } from '@sim/testing' import { oauthUtilsMock } from '@sim/testing/mocks/oauth-utils.mock' import { providersUtilsMock } from '@sim/testing/mocks/providers-utils.mock' -import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' afterAll(resetEnvFlagsMock) @@ -26,6 +26,9 @@ const { mockProviders } = vi.hoisted(() => ({ litellm: { models: [] as string[], isLoading: false }, openrouter: { models: [] as string[], isLoading: false }, fireworks: { models: [] as string[], isLoading: false }, + 'ollama-cloud': { models: [] as string[], isLoading: false }, + together: { models: [] as string[], isLoading: false }, + baseten: { models: [] as string[], isLoading: false }, }, }, })) @@ -62,16 +65,20 @@ import { evaluateSubBlockCondition } from '@sim/workflow-code/catalog/canonical- import { S3Icon } from '@/components/icons' import type { BlockConfig } from '@/blocks/types' import { + getAgentModelOptions, getApiKeyCondition, + getModelOptions, + getModelOptionsWithAuto, getProviderCredentialSubBlocks, getSelectedBedrockCredential, - getSerializedModelProviderId, parseOptionalBooleanInput, parseOptionalJsonInput, parseOptionalNumberInput, requiresProviderFamilyCredentials, + resolveModelProviderId, withSavedCredential, } from '@/blocks/utils' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' import { getProviderFromModel } from '@/providers/utils' const BASE_CLOUD_MODELS: Record = { @@ -213,6 +220,9 @@ describe('getApiKeyCondition / shouldRequireApiKeyForModel', () => { litellm: { models: [], isLoading: false }, openrouter: { models: [], isLoading: false }, fireworks: { models: [], isLoading: false }, + 'ollama-cloud': { models: [], isLoading: false }, + together: { models: [], isLoading: false }, + baseten: { models: [], isLoading: false }, } mockGetHostedModels.mockReturnValue([]) mockGetProviderModels.mockReturnValue([]) @@ -323,33 +333,78 @@ describe('parseOptionalBooleanInput', () => { }) }) -describe('getSerializedModelProviderId', () => { +describe('model options', () => { + const ids = (options: { id: string }[]) => options.map(({ id }) => id) + + const empty = { models: [] as string[], isLoading: false } + const originalProviders = mockProviders.value + + beforeEach(() => { + mockProviders.value = { + base: { models: ['gpt-4o'], isLoading: false }, + ollama: empty, + 'ollama-cloud': empty, + vllm: empty, + litellm: empty, + openrouter: empty, + fireworks: empty, + together: empty, + baseten: empty, + } + }) + + afterEach(() => { + mockProviders.value = originalProviders + setEnvFlags({ isHosted: false }) + }) + + it('offers Auto on hosted Sim only to blocks that resolve it through the model router', () => { + setEnvFlags({ isHosted: true }) + + expect(ids(getModelOptions())).toEqual(['gpt-4o']) + expect(ids(getModelOptionsWithAuto())).toEqual(['gpt-4o', 'sim-auto']) + expect(ids(getAgentModelOptions())).toEqual(['gpt-4o', 'sim-auto']) + }) + + it('never offers Auto on self-hosted Sim', () => { + expect(ids(getModelOptionsWithAuto())).toEqual(['gpt-4o']) + expect(ids(getAgentModelOptions())).toEqual(['gpt-4o']) + }) +}) + +describe('resolveModelProviderId', () => { const resolver = vi.mocked(getProviderFromModel) beforeEach(() => { resolver.mockReset() resolver.mockImplementation(((model: string) => { if (model.startsWith('openrouter/')) return 'openrouter' - if (model === 'gpt-4o') return 'openai' - if (model === 'claude-sonnet-5') return 'anthropic' + if (model === DEFAULT_BLOCK_MODEL) return 'anthropic' throw new Error(`No provider found for model: ${model}`) }) as unknown as typeof getProviderFromModel) }) it('resolves a gateway model that the base model map deliberately omits', () => { - expect(getSerializedModelProviderId('openrouter/meta-llama/llama-4-maverick')).toBe( - 'openrouter' - ) + expect(resolveModelProviderId('openrouter/meta-llama/llama-4-maverick')).toBe('openrouter') }) - it('uses the fallback model when the model is still an unresolved reference', () => { - expect(getSerializedModelProviderId('openrouter/')).toBe('openai') + it('uses the default block model when the model is unset or still an unresolved reference', () => { + expect(resolveModelProviderId('openrouter/')).toBe('anthropic') + expect(resolveModelProviderId(undefined)).toBe('anthropic') expect(resolver).not.toHaveBeenCalledWith('openrouter/') }) + it('looks up sim-auto as the model it falls back to, never as itself', () => { + expect(resolveModelProviderId('sim-auto')).toBe('anthropic') + expect(resolveModelProviderId(' SIM-AUTO ')).toBe('anthropic') + expect(resolver).toHaveBeenCalledWith(DEFAULT_BLOCK_MODEL) + expect(resolver).not.toHaveBeenCalledWith('sim-auto') + expect(resolver).not.toHaveBeenCalledWith(' SIM-AUTO ') + }) + it('never throws when the resolver rejects the model', () => { - expect(() => getSerializedModelProviderId('totally-unknown-model')).not.toThrow() - expect(getSerializedModelProviderId('totally-unknown-model')).toBe('openai') + expect(() => resolveModelProviderId('totally-unknown-model')).not.toThrow() + expect(resolveModelProviderId('totally-unknown-model')).toBe('openai') }) }) diff --git a/apps/sim/blocks/utils.ts b/apps/sim/blocks/utils.ts index 160dbbbf276..529d556ee8f 100644 --- a/apps/sim/blocks/utils.ts +++ b/apps/sim/blocks/utils.ts @@ -14,6 +14,7 @@ import type { OutputFieldDefinition, SubBlockConfig, } from '@/blocks/types' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' import { findProviderFromModel, getBaseModelProviders, @@ -238,18 +239,47 @@ function dependOnCredential( } /** - * Returns model options for combobox subblocks, combining all provider sources. + * Model options for a combobox whose block sends the chosen model straight to its provider: + * every provider source, without the sim-auto pseudo-model, which only a block that runs + * the model router can resolve. */ export function getModelOptions() { - return buildModelOptions(false) + return buildModelOptions({ includeEvaluation: false, includeAuto: false }) } -/** Agent supports both conversational and native evaluation models. */ +/** + * {@link getModelOptions} plus Auto (hosted only), for a block whose handler resolves + * sim-auto through the model router before any provider lookup (router, evaluator). + */ +export function getModelOptionsWithAuto() { + return buildModelOptions({ includeEvaluation: false, includeAuto: true }) +} + +/** Agent supports Auto and both conversational and native evaluation models. */ export function getAgentModelOptions() { - return buildModelOptions(true) + return buildModelOptions({ includeEvaluation: true, includeAuto: true }) } -function buildModelOptions(includeEvaluation: boolean) { +/** + * The model-option sources whose values editing validation checks against Sim's model + * catalog, and whether each offers Auto (so accepts sim-auto on hosted Sim). + * + * {@link getAgentModelOptions} is deliberately absent: the agent's model field also takes + * bare Ollama names, free-typed ids (Bedrock inference profiles, fine-tunes) and retired + * ids, so validation passes its values through unchanged. + */ +export const MODEL_OPTION_SOURCES: ReadonlyMap = new Map([ + [getModelOptions, { auto: false }], + [getModelOptionsWithAuto, { auto: true }], +]) + +function buildModelOptions({ + includeEvaluation, + includeAuto, +}: { + includeEvaluation: boolean + includeAuto: boolean +}) { const providersState = useProvidersStore.getState() const baseModels = orderModelIdsByReleaseDate(providersState.providers.base.models) const ollamaModels = providersState.providers.ollama.models @@ -288,7 +318,7 @@ function buildModelOptions(includeEvaluation: boolean) { // Hosted-only automatic model. Deliberately LAST in the list (limited // visibility for the initial release): available to anyone who scrolls or // searches for it, but never the first thing the dropdown offers. - if (getDeploymentShape().hosted) { + if (includeAuto && getDeploymentShape().hosted) { options.push({ label: 'Auto', id: SIM_AUTO_MODEL_ID, icon: SimAutoIcon }) } @@ -396,37 +426,34 @@ export function shouldRequireApiKeyForModel(model: string): boolean { return true } -/** Model whose provider is recorded when a block's own `model` cannot be resolved. */ -const SERIALIZATION_FALLBACK_MODEL = 'gpt-4o' - -/** Last-resort provider for when even {@link SERIALIZATION_FALLBACK_MODEL} cannot be resolved. */ +/** Provider recorded when the model's own lookup throws (a blacklisted provider or model). */ const SERIALIZATION_FALLBACK_PROVIDER: ProviderId = 'openai' /** - * Provider id a model-driven block records for `model` during serialization. + * Best-effort provider id for a model a block has not executed yet, for serialization and + * the editor's provider-dependent UI (API-key reset, tool-usage control, attachment cap). * * Serialization runs before variable resolution, and every model block's handler * re-derives the provider from the *resolved* model without ever reading this - * value — so it only has to be shape-correct, and it must never throw. Two cases - * reach here that {@link getBaseModelProviders} cannot answer: `model` may still - * hold a `` reference, and gateway providers (OpenRouter, vLLM, - * LiteLLM, Ollama, …) are deliberately absent from that map even when the model - * id is perfectly valid. A reference resolves to {@link SERIALIZATION_FALLBACK_MODEL}'s - * provider; anything else is left to `getProviderFromModel`, which defaults an - * unrecognised id to `ollama` rather than failing serialization with an error the - * user cannot act on. + * value — so it only has to be shape-correct, and it must never throw. Three cases + * reach here that {@link getBaseModelProviders} cannot answer: `model` may be unset or + * still hold a `` reference, it may be sim-auto, which has no provider until + * the model router resolves it, and gateway providers (OpenRouter, vLLM, LiteLLM, Ollama, …) + * are deliberately absent from that map even when the model id is perfectly valid. The + * first two answer as {@link DEFAULT_BLOCK_MODEL}; anything else is left to + * `getProviderFromModel`, which defaults an unrecognised id to `ollama` rather than + * failing with an error the user cannot act on. * * The remaining throw is a blacklisted provider or model, which is env-driven and - * can name the fallback itself — so recovery returns + * can name the default itself — so recovery returns * {@link SERIALIZATION_FALLBACK_PROVIDER} outright rather than resolving a second * time through the function that just threw. */ -export function getSerializedModelProviderId( - model: unknown, - fallbackModel: string = SERIALIZATION_FALLBACK_MODEL -): ProviderId { +export function resolveModelProviderId(model: unknown): ProviderId { const candidate = - typeof model === 'string' && model && !containsReference(model) ? model : fallbackModel + typeof model === 'string' && model && !containsReference(model) && !isAutoModel(model) + ? model + : DEFAULT_BLOCK_MODEL try { return getProviderFromModel(candidate) diff --git a/apps/sim/ee/access-control/utils/permission-check.test.ts b/apps/sim/ee/access-control/utils/permission-check.test.ts index 3b7c907a599..fccff74d9bb 100644 --- a/apps/sim/ee/access-control/utils/permission-check.test.ts +++ b/apps/sim/ee/access-control/utils/permission-check.test.ts @@ -349,6 +349,26 @@ describe('validateModelProvider', () => { ).rejects.toBeInstanceOf(ModelNotAllowedError) }) + it('lets sim-auto through a provider allowlist, since the router gates each pool candidate', async () => { + queueGroupResolution([{ config: { allowedModelProviders: ['anthropic'] } }]) + mockGetProviderFromModel.mockReturnValue('ollama') + + await expect( + validateModelProvider('user-123', 'workspace-1', 'sim-auto') + ).resolves.toBeUndefined() + expect(mockGetProviderFromModel).not.toHaveBeenCalledWith('sim-auto') + }) + + it('refuses sim-auto when the denylist names it, even under a provider allowlist', async () => { + queueGroupResolution([ + { config: { allowedModelProviders: ['anthropic'], deniedModels: ['sim-auto'] } }, + ]) + + await expect( + validateModelProvider('user-123', 'workspace-1', 'sim-auto') + ).rejects.toBeInstanceOf(ModelNotAllowedError) + }) + it('enforces the denylist even when no provider allowlist is set', async () => { queueGroupResolution([{ config: { allowedModelProviders: null, deniedModels: ['gpt-4'] } }]) mockGetProviderFromModel.mockReturnValue('openai') diff --git a/apps/sim/ee/access-control/utils/permission-check.ts b/apps/sim/ee/access-control/utils/permission-check.ts index 03c35cd1e31..7cda2581a5f 100644 --- a/apps/sim/ee/access-control/utils/permission-check.ts +++ b/apps/sim/ee/access-control/utils/permission-check.ts @@ -30,6 +30,7 @@ import { mergeEnvAllowlist, } from '@/lib/permission-groups/resolve.server' import type { ExecutionContext } from '@/executor/types' +import { isAutoModel } from '@/providers/models' import { getProviderFromModel } from '@/providers/utils' /** @@ -309,7 +310,11 @@ function assertModelAllowed( model: string, subject: PermissionSubject ): void { - if (config.allowedModelProviders !== null) { + /** + * sim-auto has no provider to allowlist: the model router gates every pool candidate + * through this check before it resolves to one. Naming it outright still refuses it. + */ + if (config.allowedModelProviders !== null && !isAutoModel(model)) { const providerId = getProviderFromModel(model) if (!config.allowedModelProviders.includes(providerId)) { diff --git a/apps/sim/ee/organization-usage/components/usage-consumers.tsx b/apps/sim/ee/organization-usage/components/usage-consumers.tsx index 347bef20b2b..129ce5aa90f 100644 --- a/apps/sim/ee/organization-usage/components/usage-consumers.tsx +++ b/apps/sim/ee/organization-usage/components/usage-consumers.tsx @@ -35,6 +35,7 @@ import { OpenAIIcon, OpenRouterIcon, SakanaIcon, + SimAutoIcon, TogetherIcon, TypeSafeIcon, VertexIcon, @@ -101,6 +102,8 @@ const PROVIDER_ICONS: Readonly