Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(agents): AI-built agent steps only use models AI credits can run, and explain failures when they can't (#15885)

Hazem Adel5d105b005681
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.md
index 42d478fd9b2..d4d06442fe8 100644
--- a/brain/knowledge/ai-intelligence/ai-agents.md
+++ b/brain/knowledge/ai-intelligence/ai-agents.md
@@ -46,7 +46,7 @@ Three things follow. `run_agent` has two modes: pointed at a saved agent (`agent
- **The user-fault statuses are an allow-list (401/403/404), not `!APICallError.isRetryable`.** The SDK calls every 4xx non-retryable, so the tempting one-liner blames the user for a 400 from an illegal generated tool name or a 413 from a prompt still over the window after compaction — requests *we* built, and exactly the laundering the split exists to prevent.
- **The managed `activepieces` provider is never user-fault on auth.** It runs on our own OpenRouter key, so a 401 there fails every platform at once and must page.
- **Credit is read from a status or the specific `insufficient_quota` marker, never loose patterns over a response body.** OpenAI signals billing exhaustion as a *retryable* 429 with the marker in the **body**, so credit is checked before the retryable verdict — but scanning a body for `credits`/`402` made a provider 500 whose HTML error page said "credits" complete as a billing failure and hide a real outage.
- - **`ENTITY_NOT_FOUND` counts only for an AI-provider `entityType`, and `VALIDATION` counts for nothing.** A bare not-found is our bug; the `VALIDATION` that reaches this surface is the conversation concurrency lock, and a conversation stuck `STREAMING` is a state worth keeping visible.
+ - **`ENTITY_NOT_FOUND` counts only for an AI-provider `entityType`, and `VALIDATION` counts for nothing.** A bare not-found is our bug; the `VALIDATION` that reaches this surface is the conversation concurrency lock, and a conversation stuck `STREAMING` is a state worth keeping visible. So a user-config refusal thrown from `getAgentConfig` must be `ENTITY_NOT_FOUND`/`AIProvider` with its text as `ActivepiecesError`'s second argument: text left in `params` never crosses the RPC, which is how a step naming a model the Activepieces credits do not serve failed as a bare internal `VALIDATION` on every scheduled run. The billing text heuristic reads provider text only and skips any error carrying our own code, because `isProviderBillingError` matched our own "Activepieces AI credits" wording; our credit exhaustion is always `QUOTA_EXCEEDED`. Those bad models came from `ap_list_ai_models`, which offered the AI builder the whole OpenRouter catalog for Run Agent steps; it now lists only what the resolver accepts, while `listModels` keeps the full catalog because Ask AI and image lookups need it.
A completed job stores no `errorMessage`, so the `warn` log carrying `agentRun.errorClass` is the only remaining record.
- **A tool name is user text on four paths, and only the worker sees all of them.** `createToolName` is applied by the flow-tool dialog and the piece-tool stores, but a knowledge-base name was stored as typed and the AI piece's `toolName` is free `ShortText`. That string becomes the AI-SDK `ToolSet` key verbatim, which is how a name earned a 400 from Anthropic — *our* request, never the user's fault, which is why widening the status allow-list to 400 would have been the wrong fix. `mcpToolNameUtils.toValidToolName` is the guard, applied by `agentToolPolicy.withValidNames` in `execute-agent-run` — the one place the flow-step, chat and eval enqueue paths converge (`agent-conversation-controller` validates tool names not at all; `agent-run-controller` checks only the reserved prefix and duplicates, and does it on the *raw* names, so it cannot see a collision the rewrite creates). Four things it has to get right:
- **The pattern is the intersection of every provider we ship, not the one from the error we happened to see.** Anthropic's `^[a-zA-Z0-9_.-]{1,64}$` is the loosest: OpenAI and Bedrock reject `.`, and Gemini requires a leading letter or underscore. Guarding with Anthropic's rule leaves `handbook.pdf` — the obvious name for a knowledge base file — still failing everywhere else. The guard is `^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$`.
diff --git a/packages/server/api/src/app/ee/agent/agent-model-resolution.ts b/packages/server/api/src/app/ee/agent/agent-model-resolution.ts
index 564fe3a1025..f9980906911 100644
--- a/packages/server/api/src/app/ee/agent/agent-model-resolution.ts
+++ b/packages/server/api/src/app/ee/agent/agent-model-resolution.ts
@@ -68,10 +68,11 @@ function resolveNamedModelId({ provider, modelName, surface, modelScope, modelId
const requested = isTierId({ modelName }) ? publishedTierModelId({ tierId: modelName, surface, log }) : modelName
const candidates = managedModelCandidates({ surface, modelScope, modelIds })
if (!candidates.includes(requested)) {
+ const message = `The model "${modelName}" is not available on Activepieces AI credits. Available models: ${candidates.join(', ')}`
throw new ActivepiecesError({
- code: ErrorCode.VALIDATION,
- params: { message: `The model "${modelName}" is not available on Activepieces AI credits. Available models: ${candidates.join(', ')}` },
- })
+ code: ErrorCode.ENTITY_NOT_FOUND,
+ params: { entityId: provider, entityType: AI_PROVIDER_ENTITY_TYPES.provider, message },
+ }, message)
}
return requested
}
diff --git a/packages/server/api/src/app/mcp/tools/ap-list-ai-models.ts b/packages/server/api/src/app/mcp/tools/ap-list-ai-models.ts
index 9ec16e2dd3e..2e175c16ed3 100644
--- a/packages/server/api/src/app/mcp/tools/ap-list-ai-models.ts
+++ b/packages/server/api/src/app/mcp/tools/ap-list-ai-models.ts
@@ -1,5 +1,6 @@
import { AIProviderName } from '@activepieces/core-utils'
-import { AIProviderModelType, McpToolDefinition, ProjectScopedMcpServer } from '@activepieces/shared'
+import { modelTierCatalog } from '@activepieces/server-utils'
+import { AIProviderModelType, aiProviderUtils, McpToolDefinition, ProjectScopedMcpServer } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { z } from 'zod'
import { aiProviderService } from '../../ai/ai-provider-service'
@@ -50,7 +51,7 @@ export const apListAiModelsTool = (mcp: ProjectScopedMcpServer, log: FastifyBase
filteredProviders.map(async (p) => {
try {
const models = await service.listModels({ platformId, provider: p.provider, scope: { type: 'project', projectId: mcp.projectId } })
- const textModels = models.filter(m => m.type === AIProviderModelType.TEXT)
+ const textModels = models.filter(m => m.type === AIProviderModelType.TEXT && runAgentCanCall({ provider: p.provider, modelId: m.id }))
const capped = textModels.slice(0, MAX_MODELS_PER_PROVIDER)
structuredProviders.push({
provider: p.provider,
@@ -88,3 +89,9 @@ export const apListAiModelsTool = (mcp: ProjectScopedMcpServer, log: FastifyBase
},
}
}
+
+function runAgentCanCall({ provider, modelId }: { provider: AIProviderName, modelId: string }): boolean {
+ return provider !== AIProviderName.ACTIVEPIECES
+ || aiProviderUtils.isManagedChatModelId({ modelId })
+ || modelTierCatalog.current('flow').tiers.some((tier) => tier.modelId === modelId)
+}
diff --git a/packages/server/api/test/unit/app/ee/agent/agent-model-resolution.test.ts b/packages/server/api/test/unit/app/ee/agent/agent-model-resolution.test.ts
index 603595a7d8a..88a4b08961c 100644
--- a/packages/server/api/test/unit/app/ee/agent/agent-model-resolution.test.ts
+++ b/packages/server/api/test/unit/app/ee/agent/agent-model-resolution.test.ts
@@ -1,6 +1,6 @@
import { ActivepiecesError, AIProviderName, ErrorCode, tryCatchSync } from '@activepieces/core-utils'
import { ModelTierSurface } from '@activepieces/server-utils'
-import { AgentRunSource, AIProviderModelType, aiProviderUtils } from '@activepieces/shared'
+import { AgentRunSource, AI_PROVIDER_ENTITY_TYPES, AIProviderModelType, aiProviderUtils } from '@activepieces/shared'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { agentHelpers } from '../../../../../src/app/ee/agent/agent-helpers'
import { agentModelResolution } from '../../../../../src/app/ee/agent/agent-model-resolution'
@@ -256,7 +256,7 @@ describe('resolveNamedModelId', () => {
it('accepts a model the release does not ship once a published tier on this surface carries it', () => {
expect(named({ provider: AIProviderName.ACTIVEPIECES, modelName: 'anthropic/claude-fable-5.1', surface: 'flow' })).toBe('anthropic/claude-fable-5.1')
- expect(denialFor({ modelName: 'anthropic/claude-fable-5.1', surface: 'chat' })?.code).toBe(ErrorCode.VALIDATION)
+ expect(denialFor({ modelName: 'anthropic/claude-fable-5.1', surface: 'chat' })?.code).toBe(ErrorCode.ENTITY_NOT_FOUND)
})
it('runs a tier the file no longer carries on the surface default, and says so once', () => {
@@ -270,21 +270,21 @@ describe('resolveNamedModelId', () => {
it('never reads a slashed id as a tier, so a model id is validated and never defaulted', () => {
expect(named({ provider: AIProviderName.ACTIVEPIECES, modelName: 'anthropic/claude-haiku-4.5' })).toBe('anthropic/claude-haiku-4.5')
- expect(denialFor({ modelName: 'openai/gpt-6-astra' })?.code).toBe(ErrorCode.VALIDATION)
+ expect(denialFor({ modelName: 'openai/gpt-6-astra' })?.code).toBe(ErrorCode.ENTITY_NOT_FOUND)
expect(warn).not.toHaveBeenCalled()
})
it('refuses a model nobody put on the managed allow-list, on our key and our credits', () => {
for (const modelId of ['google/gemini-3.8-flash', 'openai/gpt-6-astra', 'openai/gpt-6-astra-pro', 'anthropic/claude-fable-6']) {
const denial = denialFor({ modelName: modelId })
- expect(denial?.code, modelId).toBe(ErrorCode.VALIDATION)
- expect(denial?.params, modelId).toMatchObject({ message: expect.stringContaining('not available on Activepieces AI credits') })
+ expect(denial, modelId).toMatchObject({ code: ErrorCode.ENTITY_NOT_FOUND, params: { entityType: AI_PROVIDER_ENTITY_TYPES.provider } })
+ expect(() => named({ provider: AIProviderName.ACTIVEPIECES, modelName: modelId }), modelId).toThrow(`The model "${modelId}" is not available on Activepieces AI credits`)
}
})
it('refuses an empty or junk model name without mistaking it for a tier', () => {
for (const modelName of ['', '../../etc/passwd', 'anthropic/claude-haiku-4.5 ']) {
- expect(denialFor({ modelName })?.code, JSON.stringify(modelName)).toBe(ErrorCode.VALIDATION)
+ expect(denialFor({ modelName })?.code, JSON.stringify(modelName)).toBe(ErrorCode.ENTITY_NOT_FOUND)
}
expect(warn).not.toHaveBeenCalled()
})
@@ -292,8 +292,8 @@ describe('resolveNamedModelId', () => {
it('refuses rather than silently substituting, so a flow never runs a model it did not name', () => {
const scoped = { modelScope: 'selected' as const, modelIds: ['anthropic/claude-haiku-4.5'] }
expect(named({ provider: AIProviderName.ACTIVEPIECES, modelName: 'anthropic/claude-haiku-4.5', ...scoped })).toBe('anthropic/claude-haiku-4.5')
- expect(denialFor({ modelName: 'anthropic/claude-sonnet-4.6', ...scoped })?.code).toBe(ErrorCode.VALIDATION)
- expect(denialFor({ modelName: 'smart', ...scoped })?.code).toBe(ErrorCode.VALIDATION)
+ expect(denialFor({ modelName: 'anthropic/claude-sonnet-4.6', ...scoped })?.code).toBe(ErrorCode.ENTITY_NOT_FOUND)
+ expect(denialFor({ modelName: 'smart', ...scoped })?.code).toBe(ErrorCode.ENTITY_NOT_FOUND)
})
it('leaves a bring-your-own key free to name any model it pays for', () => {
diff --git a/packages/server/api/test/unit/app/mcp/ap-list-ai-models.test.ts b/packages/server/api/test/unit/app/mcp/ap-list-ai-models.test.ts
new file mode 100644
index 00000000000..9e7c4c955cb
--- /dev/null
+++ b/packages/server/api/test/unit/app/mcp/ap-list-ai-models.test.ts
@@ -0,0 +1,52 @@
+import { AIProviderName } from '@activepieces/core-utils'
+import { AIProviderModelType, McpToolResult, ProjectScopedMcpServer } from '@activepieces/shared'
+import { describe, expect, it, vi } from 'vitest'
+
+const listForProject = vi.fn()
+const listModels = vi.fn()
+
+vi.mock('../../../../src/app/ai/ai-provider-service', () => ({
+ aiProviderService: () => ({ listForProject, listModels }),
+}))
+
+vi.mock('@activepieces/server-utils', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ modelTierCatalog: (await import('../ee/agent/model-tier-fixture')).publishedModelTierCatalog,
+}))
+
+import { system } from '../../../../src/app/helper/system/system'
+import { apListAiModelsTool } from '../../../../src/app/mcp/tools/ap-list-ai-models'
+
+const log = system.globalLogger()
+const mockMcp = { id: 'mcp-1', projectId: 'project-1', platformId: 'platform-1', tools: [], flows: [] } as unknown as ProjectScopedMcpServer
+
+function textModel(id: string): { id: string, name: string, type: AIProviderModelType } {
+ return { id, name: id, type: AIProviderModelType.TEXT }
+}
+
+function textOf(result: McpToolResult): string {
+ return result.content.map((part) => part.text).join('\n')
+}
+
+describe('ap_list_ai_models', () => {
+ it('offers a Run Agent step on Activepieces credits only the models it can call', async () => {
+ listForProject.mockResolvedValue([{ provider: AIProviderName.ACTIVEPIECES, name: 'Activepieces' }])
+ listModels.mockResolvedValue([textModel('mistralai/mistral-large'), textModel('openai/gpt-4o'), textModel('anthropic/claude-sonnet-4.6'), textModel('anthropic/claude-fable-5.1')])
+
+ const text = textOf(await apListAiModelsTool(mockMcp, log).execute({}))
+
+ expect(text).toContain('(id: anthropic/claude-sonnet-4.6)')
+ expect(text).toContain('(id: anthropic/claude-fable-5.1)')
+ expect(text).not.toContain('openai/gpt-4o')
+ })
+
+ it('leaves a bring-your-own key free to offer every text model it serves', async () => {
+ listForProject.mockResolvedValue([{ provider: AIProviderName.OPENROUTER, name: 'OpenRouter' }])
+ listModels.mockResolvedValue([textModel('mistralai/mistral-large'), textModel('openai/gpt-4o')])
+
+ const text = textOf(await apListAiModelsTool(mockMcp, log).execute({}))
+
+ expect(text).toContain('(id: mistralai/mistral-large)')
+ expect(text).toContain('(id: openai/gpt-4o)')
+ })
+})
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
index 4e54437c8b6..5a2be29160e 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
@@ -1,6 +1,6 @@
import { ActivepiecesAiBilling, ActivepiecesAiConsumerSource, AIProviderName, ErrorCode, formatPieceError, isNil, isObject, spreadIfDefined, tryCatch, tryCatchSync } from '@activepieces/core-utils'
import { agentAiUtils, aiUtils } from '@activepieces/server-utils'
-import { AgentEvent, AgentEventType, AgentKnowledgeBaseTool, AgentMcpTool, AgentOutputField, AgentPhase, AgentPieceTool, AgentResult, AgentRunSource, AgentTool, AgentToolType, AiProviderCredentials, EngineResponseStatus, ExecuteAgentRunJobData, MAX_AGENT_TURN_WALL_CLOCK_MS, PersistedAgentMessage, PersistedAgentMessageSchema, PersistedAgentPart, PersistedAgentPartType, PersistedAgentRole, ResolvedAgentFlowTool, WorkerJobType } from '@activepieces/shared'
+import { AgentEvent, AgentEventType, AgentKnowledgeBaseTool, AgentMcpTool, AgentOutputField, AgentPhase, AgentPieceTool, AgentResult, AgentRunSource, AgentTool, AgentToolType, AiProviderCredentials, apErrorOf, EngineResponseStatus, ExecuteAgentRunJobData, MAX_AGENT_TURN_WALL_CLOCK_MS, PersistedAgentMessage, PersistedAgentMessageSchema, PersistedAgentPart, PersistedAgentPartType, PersistedAgentRole, ResolvedAgentFlowTool, WorkerJobType } from '@activepieces/shared'
import { createUIMessageStream, generateText, ModelMessage, streamText, ToolSet, toUIMessageStream } from 'ai'
import { FireAndForgetJobResult, JobContext, JobHandler, JobResultKind } from '../../../types'
import { toResolvedAiFile } from '../../ai/ai-files'
@@ -398,7 +398,7 @@ export const executeAgentRunJob: JobHandler<ExecuteAgentRunJobData, FireAndForge
catch (err) {
const errorClass = classifyAgentRunError({ error: err, provider: runProvider })
log[errorClass === 'internal' ? 'error' : 'warn']({ error: err, conversation: { id: conversationId }, provider: runProvider, model: { id: runModelId }, agentRun: { errorClass, source } }, '[executeAgentRun] Agent job failed')
- const errorMessage = formatPieceError(err).message
+ const errorMessage = apErrorOf(err)?.message ?? formatPieceError(err).message
const isCreditError = errorClass === 'credit'
// "User not found" is OpenRouter refusing a key, and reads like a missing account.
const clientMessage = !isCreditError && isTransientFailureText(errorMessage)
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
index c76da90e8b1..f3fc9209de3 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
@@ -1,6 +1,6 @@
import { AIProviderName, ErrorCode, formatPieceError, isNil, isObject, isProviderBillingError, isTransientProviderError, spreadIfDefined, tryCatch, tryCatchSync } from '@activepieces/core-utils'
import { agentAiUtils, ContentPartLike, modelCatalog } from '@activepieces/server-utils'
-import { AgentPhase, AgentRunSource, agentToolClassification, agentToolPhases, aiProviderUtils, apErrorOf, CHAT_CREDITS_PER_TOOL_CALL, chatBilling, ChatToolCall, PersistedAgentPart } from '@activepieces/shared'
+import { AgentPhase, AgentRunSource, agentToolClassification, agentToolPhases, AI_PROVIDER_ENTITY_TYPES, aiProviderUtils, apErrorOf, CHAT_CREDITS_PER_TOOL_CALL, chatBilling, ChatToolCall, PersistedAgentPart } from '@activepieces/shared'
import { APICallError, generateText, isLoopFinished, isStepCount, LanguageModel, LanguageModelUsage, ModelMessage, NoSuchToolError, RetryError, StepResultPerformance, StopCondition, streamText, ToolExecutionOptions, ToolSet } from 'ai'
const MAX_RESPONSE_OUTPUT_TOKENS = 32_000
@@ -14,7 +14,7 @@ const RUNAWAY_TURN_CONTEXT_MULTIPLE = 90
const STREAM_RETRY_BASE_DELAY_MS = 1_000
const USER_FAULT_STATUS_CODES = new Set([401, 403, 404])
const MODEL_UNAVAILABLE_PATTERNS = [/\bis deprecated\b/i, /no longer (available|supported)/i, /\bmodel_not_found\b/i, /\bunknown model\b/i, /\bdecommissioned\b/i]
-const USER_CONFIG_ENTITY_TYPES = new Set(['AIProvider', 'ChatAiProvider'])
+const USER_CONFIG_ENTITY_TYPES = new Set<string>(Object.values(AI_PROVIDER_ENTITY_TYPES))
const CONTINUE_NUDGE = '[system note — not from the user] Your previous response was cut off by the output token limit before it finished. Continue exactly where you stopped. If a tool call was cut off, re-issue it in FULL. Do not repeat content you already produced.'
const EMPTY_OUTPUT_NUDGE = '[system note — not from the user] Your previous step produced no visible reply to the user. Continue the task now: either call the next tool, or write your reply to the user. Do not stop silently.'
@@ -381,7 +381,7 @@ export function classifyAgentRunError({ error, provider }: { error: unknown, pro
const apError = apErrorOf(cause)
const message = formatPieceError(cause).message
const serverSideFault = (apiError?.statusCode ?? 0) >= 500
- const providerText = serverSideFault ? '' : `${apiError?.responseBody ?? ''} ${message}`
+ const providerText = serverSideFault || !isNil(apError) ? '' : `${apiError?.responseBody ?? ''} ${message}`
const saysOutOfMoney = apError?.code === ErrorCode.QUOTA_EXCEEDED
|| apiError?.statusCode === 402
|| isProviderBillingError(providerText)
diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/execute-agent-run-config-failure.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/execute-agent-run-config-failure.test.ts
index 6399a79fa80..c45965cda5c 100644
--- a/packages/server/worker/test/lib/execute/jobs/ee/agent/execute-agent-run-config-failure.test.ts
+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/execute-agent-run-config-failure.test.ts
@@ -1,5 +1,5 @@
import { ActivepiecesError, ErrorCode } from '@activepieces/core-utils'
-import { AgentEvent, AgentEventType, AgentRunSource, EngineResponseStatus, ExecuteAgentRunJobData, LATEST_JOB_DATA_SCHEMA_VERSION, WorkerJobType } from '@activepieces/shared'
+import { AgentEvent, AgentEventType, AgentRunSource, AI_PROVIDER_ENTITY_TYPES, EngineResponseStatus, ExecuteAgentRunJobData, LATEST_JOB_DATA_SCHEMA_VERSION, WorkerJobType } from '@activepieces/shared'
import { describe, expect, it } from 'vitest'
import { executeAgentRunJob } from '../../../../../../src/lib/execute/jobs/ee/agent/execute-agent-run'
import { JobContext } from '../../../../../../src/lib/execute/types'
@@ -69,6 +69,18 @@ describe('executeAgentRunJob — a config failure must not swallow the turn', ()
expect(resumed[0].output).toMatchObject({ failure: expect.stringContaining('ENTITY_NOT_FOUND') })
})
+ it('fails a flow step on a model our credits do not serve with the reason alone, as a user failure', async () => {
+ const reason = 'The model "openai/gpt-4o" is not available on Activepieces AI credits. Available models: anthropic/claude-sonnet-4.6'
+ const { ctx, resumed } = buildContext(Object.assign(new Error(`RPC [getAgentConfig] handler threw: ENTITY_NOT_FOUND: ${reason}`), {
+ apError: { code: ErrorCode.ENTITY_NOT_FOUND, entityType: AI_PROVIDER_ENTITY_TYPES.provider, message: reason },
+ }))
+
+ const result = await executeAgentRunJob.execute(ctx, buildJobData({ source: AgentRunSource.FLOW_STEP, flowRunId: 'flow-run-1', waitpointId: 'waitpoint-1' }))
+
+ expect(result.status).toBe(EngineResponseStatus.USER_FAILURE)
+ expect(resumed[0].output).toMatchObject({ failure: reason })
+ })
+
it('tells the chat client the turn failed instead of leaving it streaming', async () => {
const { ctx, events } = buildContext()
diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-guards.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-guards.test.ts
index 0b439cf03cd..232055f5d34 100644
--- a/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-guards.test.ts
+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-guards.test.ts
@@ -1,5 +1,5 @@
import { ActivepiecesError, AIProviderName, ErrorCode } from '@activepieces/core-utils'
-import { AgentRunSource } from '@activepieces/shared'
+import { AgentRunSource, AI_PROVIDER_ENTITY_TYPES } from '@activepieces/shared'
import { APICallError, RetryError } from 'ai'
import { describe, expect, it } from 'vitest'
@@ -162,6 +162,12 @@ describe('classifyAgentRunError', () => {
}))).toBe('user')
})
+ it('treats a flow step naming a model our credits do not serve as user config, not an empty wallet', () => {
+ expect(classify(Object.assign(new Error('RPC [getAgentConfig] handler threw: ENTITY_NOT_FOUND: The model "openai/gpt-4o" is not available on Activepieces AI credits.'), {
+ apError: { code: ErrorCode.ENTITY_NOT_FOUND, entityType: AI_PROVIDER_ENTITY_TYPES.provider },
+ }))).toBe('user')
+ })
+
it('keeps an unrecognised error internal', () => {
for (const input of [new Error('Cannot read properties of undefined'), undefined, null, 'a string', {}]) {
expect(classify(input)).toBe('internal')