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
icon: 🧠
AI Providers
Lets platform admins configure one or more LLM backends for AI pieces in flows. Also auto-provisions an "Activepieces" provider (backed by OpenRouter) whose credit balance and auto-top-up are metered by Autumn billing. Registered in every edition (aiProviderModule sits outside the edition switch in app.ts).
Entities & services
- AIProvider — platform-scoped:
displayName,platformId(indexed withprovider, NOT unique — a platform can hold multiple keys per provider since the 2026-08 providers redesign),provider(AIProviderName enum),auth(EncryptedObject, AES-256 at rest),config(JSON),enabledForChat, plus per-key scoping:modelScope(all|selected) +modelIds[], andprojectScope(all|selected|except) +projectIds[](GIN-indexed). - Backend under
packages/server/api/src/app/ai/; shared schemas incore/shared/.../ai-providers/. - Supported providers (19):
openai,anthropic,google,azure,openrouter,bedrock,vertex,mistral,cloudflare-gateway, the OpenAI-compatible vendorsxai,deepseek,zai,qwen,minimax,moonshot,meta,nvidia,custom(OpenAI-compatible, e.g. Ollama/LM Studio), andactivepieces(auto-provisioned via OpenRouter).
How it works
GET /list (auto-creates ACTIVEPIECES whenaiCreditsEnabled);GET /:provider/models(cached);POST /create (validates creds first);POST /:idupdate;DELETE /:id.- For ACTIVEPIECES, update is blocked by an early return (only enabling
enabledForChatis allowed); deletion is allowed and self-healing —listProvidersrecreates the managed row. The delete revokes the row's OpenRouter key, and the platform hard delete does the same throughdeleteManagedProvider, because theON DELETE CASCADEfromplatformwould otherwise leave the key live. The recreated row mints a fresh $500 key, so a limit raised byincreaseAiCreditsdoes not survive a delete. - Engine integration: the AI piece no longer fetches credentials. It POSTs
/v1/ai/execute, the server enqueues anEXECUTE_AIworker job, and the worker resolves the provider over theresolveAiProviderRPC.GET /:provider/configwas removed in #15494. - For the managed ACTIVEPIECES provider that config route is also the credit gate:
assertCreditsAndAppSumoNotExceeded(platform/billing-provider.ts) throwsQUOTA_EXCEEDEDwhen the Autumn credit or AppSumo balance is blocked — fires per AI call, but usage is only metered post-run, so in-flight spend is invisible to it. See decision 000016 (brain/decisions/000016-managed-ai-metering-moves-to-centralized-worker-execution.md). - Activepieces provisioning:
getOrCreateActivePiecesProviderAuthConfig()→enrichWithKeysIfNeeded()mints an OpenRouter key. No system job is scheduled — renewal/top-up is driven by Autumn (autoTopUpsinautumn-billing.ts), not Stripe.
AI Credits (Autumn-metered)
- Rate: 1000 credits = $1 USD; OpenRouter meters usage per API key; usage cached 180s.
- New managed keys are minted with a hard spend guardrail of $500/month (
MANAGED_OPENROUTER_KEY_MONTHLY_LIMIT_USDinai-provider-service.ts,limit_reset: 'monthly') — a runaway-cost ceiling independent of the Autumn credit balance. Keys minted before the 2026-07 change carry $1000/monthly from a one-off OpenRouter backfill. - There is no monthly credit-reset job and no direct Stripe invoicing; the only "monthly" mechanism is the key's
limit_reset. - Model lists are cached in memory, cleared daily at midnight via cron.
Provider visibility
isActivepiecesAiProviderHiddenhides the managed provider when theaiCreditsEnabledflag is off (OPENROUTER_PROVISION_KEYunset — typical self-hosted) or whenshouldHideActivepiecesAiProviderreturns true, which is gated only onplan.embeddingEnabled.- Hidden means treated as absent everywhere:
listProviders()omits the row andgetChatProvider()/getChatProviderName()return null (findAvailableChatProviderRow). This keeps a staleenabledForChat(e.g. from the 0.82.1 migration) from pinning chat to a provider that 402s with no top-up path (GIT-1620).
Model catalog
Per-model metadata (context window, max output, release date, per-million input/output price,
tool-calling / reasoning / vision) for the models a provider lists. Sourced from
models.dev (MIT), generated by npm run sync-model-catalog and published by a
weekly workflow to https://cdn.activepieces.com/ai/model-catalog.json — nothing is committed and no
process imports it. modelCatalog.lookup({ provider, modelId }) is the single accessor: it is async,
fetches the object once and caches it for 24h, dedupes concurrent callers on one in-flight promise, and
backs off for 5 minutes after a failure so a CDN outage cannot slow the models endpoint. Enrichment
happens once, in the modelsCache re-map inside fetchModels, so the web picker, the AI piece dropdown
and ap_list_ai_models all get it from the same place. See decision 000032.
Prices are rounded to three decimals in the generator, both to kill float artefacts
(0.049999999999999996) and because a handful of OpenRouter models — deepseek/deepseek-v4-flash
among them — carry continuously floating five-decimal prices. Three decimals is below anything the UI
renders and preserves every real price; the cheapest in the set is 0.01.
Model tiers
The published tier file, https://cdn.activepieces.com/ai/pricing.json, carries two lists: flow tiers
(tiers, defaultTierId, fastTierId) for the surfaces that name their own model (FLOW_STEP and AGENT),
and chat tiers (chatTiers, chatDefaultTierId, chatFastTierId) for CHAT and AGENT_BUILDER. The
chat keys are optional; when absent, chat reads the flow list. Each list must contain its own default and
fast tier and have unique ids. There are no cross-list rules: the same id may sit on both lists pointing at
different models, and a tier may exist on one list only. A file that fails any rule is rejected whole and
the release's bundled tiers serve instead.
modelTierCatalog.current(surface) (packages/server/utils/src/model-tier-catalog.ts) is the single
accessor: synchronous, never throws, serves the cached file or ACTIVEPIECES_CHAT_TIERS, and refreshes in
the background every 15 minutes with a 5-minute back-off after a failure. warmUp() runs at API boot from
aiProviderService.setup(), bounded to 2 s so a dead CDN cannot block boot. The resolution family in
ee/agent/agent-model-resolution.ts (findTier, resolveTier, resolveNamedModelId, resolveModelIdForProvider,
defaultModelIdForProvider, resolveModelIdForAnalytics) and the fast-model helpers in agent-helpers.ts read it,
every one with a required surface argument. surfaceOf({ source }) in that file is the only place the run
source maps to a list (FLOW_STEP and AGENT to flow, CHAT and AGENT_BUILDER to chat), and agent-config-rpc.ts
derives namesItsOwnModel from it. The AI piece's text steps resolve through aiModelResolution.resolveTierModelId
(src/app/ai/ai-model-resolution.ts, CE), always on the flow surface, in ai-execute-controller.ts before the job is
enqueued. AP_MODEL_TIERS_URL overrides the URL. The file is published from the console in ap-analytics; see
decision 000041. The console publishes both lists and both fast pointers on every Publish, and on its first load
after a file without chat keys it seeds the chat list from the live flow list.
Platform tiers
Platform tier — an admin-built, platform-owned list of up to 5 {configId, modelId} entries (main + ranked fallbacks, any keys), table platform_model_tier, API /v1/platform-model-tiers. A tier follows key scope: in a project it runs only the entries whose key serves that project, and it is listed there only when its main entry can run; see decision 000048 (replaces 000044's grant). The admin Tiers page (/platform/ai/tiers) is listed in the AI Center sidebar and global search on cloud only (edition === CLOUD, search requiresEdition); self-hosted can still open it by URL. Avoid: "model tier" alone — that is the console credits tier (ModelTier, above).
Specific model — a model a builder picks directly from one key ({provider, configId, model}), as opposed to a tier. The admin switch platform_configuration.aiSpecificModelsVisible (Tiers tab, "Visible to builders") hides them from builders. Avoid: "Advanced" (an early mockup word for the same section)
Gotchas
The Activepieces credits row is created lazily, so any read of provider rows must call
ensureManagedProviderRowfirst.listVisibleRowsandfindAvailableChatProviderRowboth do. A brand-new platform has no row until one of them runs. Before AI-173, agent creation read the table directly, so a new cloud signup whose first AI action was "New agent" got an agent with no model, and its first message failed with a 409. A test that seeds the row withmockAndSaveAIProvidercan't catch this, so cover the fresh-platform path without seeding.Every AI Center page links its admin guide from the header, through
adminPageResources(packages/web/src/app/components/admin/admin-page-resources.ts).aiProviders→admin-guide/guides/setup-ai-providers(Providers and the key page),aiTiers→ai-tiers,aiCapabilities→ai-capabilities,aiUsage→ai-usage(overview, list and detail). A new AI Center page needs a guide underdocs/admin-guide/guides/, an entry in the docs.json AI Center group, and aresources=on itsAdminPageHeader.A new provider shows "—" for context and price until the catalog is republished from
main. ItsMODELS_DEV_PROVIDERentry only takes effect when the weeklysync-model-catalogworkflow runs onmain(trigger it by hand after the merge), and the API caches the catalog for 24h. Even then only ids models.dev knows fill in: of NVIDIA's 85 hosted models about 26 match, and its prices are $0 because the hosted catalogue is free.The AI usage read API (
/v1/ai-usage/*) works in UTC days and scales today's partial day inside the SQL. Every previous-range sum is multiplied by a weight that is below 1 only on the day matching today, so totals, cards, lists and related items all compare the same way. Scaling after the query, in TypeScript, can't reach per-item numbers and makes the views disagree.Usage tracking starts per platform, at its copy cursor.
trackingSinceis the cursor'sstartedAt, or the platform's creation if that is later. A period that starts earlier hides its change %, so a fresh platform never shows fake growth. A platform without a cursor has no tracking start.Usage ids are not always entity ids.
no-projectis platform chat,activepieces-creditsandunknown-<provider>are keys with no config, and a model id isbase64url(provider|modelId). Lists stop at 1000 rows.ACTION_RUNrows have noflowId, so the flows card never adds up to the flow-steps slice.AI usage analytics come from Autumn events, not our own stream (decision 000053). Every Autumn
trackfor an AI call carries ausageblock v1 (ai/usage/ai-usage-block.ts). The block is built insidetryCatch: if pricing fails, the billed track still goes out without it, so billing never depends on analytics.Usage-only calls send a value-0
apCreditstrack with only{ usage }. That covers BYOK chat and agent turns, compaction, memory, personalization, own-key embeddings and managed calls without a cost. Source isai_usage, with no top-levelprojectId, so the billing page'sgroupBy projectIdisn't crowded. The value is a literal 0:chargeForwould returntoolCalls.AI_USAGE_COPYreads a delayed, non-overlapping window. Each run reads[copiedUntil, min(now − 2 min, copiedUntil + 10 min)). The 2 minutes cover Autumn's 10–20 s visibility lag. The cursor moves with a compare-and-swap on epoch milliseconds in the same transaction as the upserts. The run's end time is fixed once, at its start: chasingnowloops on tiny windows until the budget runs out. A window that needs more than 3 pages is halved and retried (down to 1 s, which reads uncapped), and the run's 40 s budget is only checked between windows: aborting mid-window would re-read the same busy window forever. The smaller window is saved in Redis per platform for an hour, so a run that spends its budget on a capped read still leaves the next run a smaller window instead of the full 10 minutes again. A full-size window that reads in one page doubles back toward 10 minutes (the short leftover window at the end of a run never grows it, or a busy platform would grow and re-halve every run), and the Redis entry is deleted at full size, so one busy spell does not leave a platform on tiny windows. A bad event must be skipped at parse time (token counts are integers, the block is run throughsanitizeObjectForPostgresql): one row Postgres rejects fails the whole window's write and pins that platform's cursor until someone fixes it.Autumn drops
nullvalues from event properties, including inside the nestedusageblock. The stored event has noagentIdoruserIdkeys at all. The block's id fields therefore accept missing and turn it intonull(nullish().transform). A schema that requires the key rejects every event, and the cursor still moves past them, so the page stays empty with no errors.events.listisn't fail-open and can only filter by feature. It throws on 5xx or timeout, so the job wraps it and retries the window next minute. It also returns flow-run, MCP and chat-turn events; the job skips anything without ausageblock.Runs are counted through
ai_usage_run(run ids kept 24 h). The earliest event of a new run getsruns = 1. A run whose AI calls are more than 24 h apart counts twice.models.dev already has cache prices (
cost.cache_read,cost.cache_writefor a 5-minute write) and long-contexttiersfor most Anthropic, OpenAI and Bedrock models.tools/scripts/sync-model-catalog.tshas to copy them, or every estimate ignores caching. It has no batch, flex/fast or 1-hour cache-write prices; LiteLLM'smodel_prices_and_context_window.json(MIT) does. We send noserviceTier, so every call bills at the standard rate.billingis a required argument ofcreateModel,createEmbeddingModelandsearchWeb. A call that is really unbilled passesnull, so a new call site can't silently drop out of usage.The SDK's input token total already includes cache reads and writes. The estimate subtracts both before pricing uncached input.
Production runs are queued, so their
flow_runrow may not exist yet.aiCallContext.runOfreads the queued-run metadata hash in Redis first, then the saved row, and caches the result in-process. MCP, trigger and property executions use placeholder run ids (DEFAULT_MCP_DATA.flowRunId,execute-trigger,execute-property). They becomeACTION_RUNand never count as runs.enabledForChatnow means "the Default AI key", not "the key every chat runs on". Chats pin their own key (seeai-agents.md); the flag only seeds the legacy and default paths, knowledge-base embeddings (when no Embeddings capability is set), and platform-wide work. Memory and personalization run on it, else on the Default tier's main model when that key serves every project, else on Credits (agentHelpers.resolvePlatformWorkModel).listForProjectstill reports the flag so a web client from before the 7b deploy keeps working; no current web code reads it.Embedding models are a short curated list per provider (
EMBEDDING_MODELSin core-piece-types), first entry = default. The KB column isvector(768), and embeddings are truncated to 768 dims, which is only safe for Matryoshka-trained models, so a live provider listing is not used. Embedding ids are never in a key's chat model scope, so the Embeddings capability skipskeyOffersModel/losesModel. Changing the Embeddings key or model leaves old files on their old vectors: search mixes two embedding spaces until those files are re-uploaded. There is no per-file pin and no re-embed.The replay eval can't judge a model swap where the new model takes a different tool path. Two separate things cause it:
- Replay divergence. Every fixture gets the same tool set from
buildEvalToolSet(local, display, cross-project and thinking tools). The recording only fixes which results come back and in what order. Calling a registered tool out of the recorded order returns__evalDivergence. - Tools the eval doesn't have. The flow and table tools (
ap_duplicate_flow,ap_build_flow,ap_find_records) aren't in that set at all, soap_get_tool_schemaanswers "There is no tool named". The tool does exist in production.
Either one makes a candidate give up for reasons that aren't the model's, so
--candidate-modelscores read low. On 13 Oct, Sonnet 5.5 scored 9/26 against 14/26, and 4 of its 6 regressions were one of these two. Use--baseline-model/--candidate-modelfor cost and for judge-only cases. Check tool-heavy behaviour withagent-evals:livebefore changing a tier.- Replay divergence. Every fixture gets the same tool set from
Change which model a tier runs in the AI Tiers console, not in code. A model a tier points at runs on credits without being in
ANTHROPIC_OPENROUTER_CHAT_MODELS(assertManagedModelAllowedallows every tiermodelId). Keep Claude Sonnet 5.5 and Opus 5.5 out of that list: everything in it counts as reasoning-optional (canDisableReasoning), and their OpenRouter endpoints rejectreasoning: {enabled: false}with "Reasoning is mandatory for this endpoint", which would fail the thinking-off first step of every turn. Unlisted, they geteffort: minimal, which works. Haiku 5.5 acceptsenabled: false(checked 13 Oct).New shared AI-provider schemas go inside
packages/core/shared/src/lib/management/ai-providers/index.ts, not in a sibling file that imports from it.index.tsre-exports its siblings, so a sibling that importsAIProviderModelback from./indexgetsundefinedwhen the module loads, and every importer crashes withCannot read properties of undefined (reading 'optional').platform-model-tier.tsworks only because it imports fromcore-utils.The admin Tiers tab applies a key's
modelScopeitself.GET /v1/ai-providers/configs/:id/modelsreturns the unfiltered list on purpose (admins pick the allow-list from it), so the tier pickers and the Specific models list narrow it client-side inmodelMeta.scopedTextModels(packages/web/src/features/agents/ai-model/). The server still refuses an out-of-scope entry on save (assertEntriesValid), so the client filter is convenience, not the guard.A key a live platform tier uses cannot be deleted, and its
modelScopecannot drop a tier's model.aiProviderService.deleteandupdatecallplatformModelTierService.assertKeyCanBeDeleted/assertKeyScopeKeepsTiersunder aplatformrowFOR NO KEY UPDATElock and answer 409 with the tier names. The same lock serialises every tier write, so a tier save can't race a key delete into a dangling entry. The same update also refuses removing a typed-in model (Vertex, OpenAI-compatible, Cloudflareconfig.models) that a tier uses, even whenmodelScopeisall, and limiting the projects of a key that a capability (web search, scraping, image) uses, or dropping the capability'smodelIdfrom its model list: capability keys must serve every project and keep their model (assertCapabilitiesKeepKey).A key's model list is enforced when a specific model runs, not only in pickers.
/v1/ai/executechecksaiProviderService.assertModelAllowedbefore queueing (the managed Activepieces key is skipped: it allows every model), and the worker'sresolveAiProviderRPC sendsmodelIdso the server checks it again against the key it resolves at run time (a model removed while the job waited fails then).resolveNamedModelIdrefuses any own-key model outside the list with no tier-id exemption: an own key never translatessmart/fast, so a name that looks like a tier is just a customer model id. At platform scope,rankRowsprefers keys open to every project; at project scope it still prefers the most specific key. Key edits and capability choices both take theplatformrow lock, and a capability save re-reads its key under that lock, so the two cannot interleave. One helper,aiKeyScope.keyOffersModel, decides whether a key still offers a model: its model scope, plus its typed-inconfig.modelslist when it has one. The tier and capability guards on a key edit both use it, and so does the locked re-check when a capability is saved. A key edit that removes a typed-in model a capability uses is refused like a model-scope change.Deleting a platform tier needs a replacement, except the last live tier, and there is no usage count. Refs to a deleted tier are never rewritten; they reach a live tier through
replacedBy(flattened to one hop on delete). The last tier may always go with no replacement: without that exit, a platform's last tier and the key it uses could never be removed, because the key guard refuses keys a live tier uses. Tier delete is also deliberately not plan-gated (writes are), so a platform that downgrades can still clear its tiers and then remove its key. Its refs then point at a tier withreplacedBy: null, and the resolver must fail them with a clear "tier removed" error. An exact "used by N flows" count needs aLIKEscan over every flow version'striggertext, plus agent jsonb and conversations, on the whole platform. We dropped it rather than pay that. If counts come back, add a denormalizedflow_version.modelTierIdsarray + GIN index (theconnectionIdspattern) instead of scanning. Deleting the last live tier also setsplatform_configuration.aiSpecificModelsVisible = truein the same transaction, so "hidden needs at least one tier" holds without the client flipping it first (a client-side flip left models visible when the delete then failed, #16116). The other direction holds too:platformConfigurationService.updatesaves every field in one transaction that first callsplatformModelTierService.assertSpecificModelsVisibilityAllowed(sameplatformrow lock, refuses a hide when no live tier is left), so a refused hide changes no other setting either, so a concurrent last-tier delete and hide cannot leave builders with nothing.PlatformConfigurationSettings(the infra Configurations form) does not carry the flag; onlyUpdatePlatformConfigurationRequestBodydoes, so saving that form never rewrites it.The Tiers tab re-implements the server's project-scope rule on the client.
modelMeta.keyServesProject/entryRunsInmirrorrowAllowsScope+scopeAllows, and power the per-tier "Not available in N projects" lines, the Preview as project select and the confirm dialog when a key's projects are narrowed (modelMeta.keyScopeImpact). Change one side and change the other, or the admin sees a tier as available where the server refuses it.The keys page mirrors the tier-model rule above in the UI.
keyScopeImpactonly checks project scope, so the key's model lists (KeyModelList, andManualModelListfor typed-in models) lock tier-used rows ("Used by {tier}") and always keeps their ids in the draft; switching All models → Only selected prefills every listed model plus those ids. Stats come fromAIProviderModel.metadata; models outside the catalog show—.The live-name unique index is
lower("name"), whichEntitySchemacannot express. The entity declares itsynchronize: false(socheck-migrationsskips it), which means test DBs built bysynchronizedon't have it. The case-insensitive check that tests rely on is the service'sassertNameIsFree, which is race-free because it runs under theplatformrow lock; the index is the backstop.lockPlatformtakesFOR NO KEY UPDATE, notFOR UPDATE. Every FK insert that referencesplatform(projects, users, …) takesFOR KEY SHAREon the platform row, whichFOR UPDATEblocks until commit.FOR NO KEY UPDATEserialises tier writes just the same without stalling those inserts.Tier entries go through the same project check as specific picks.
platformModelTierService.getForRuntakes aProviderScopeand appliesaiKeyScope.rowAllowsScope+scopeAllowsto every entry; if the stored main entry fails, the whole tier is unavailable (it is checked before the healthy-first sort, so a down main doesn't change the answer). TheconfigIds still come from a live tier on the caller's platform, never from the caller. Only the label lookups (getManyForRun,firstCandidates) use platform scope, because they return no credentials.Agent and chat runs read the tier grant from the conversation row, never from the worker. CHAT and AGENT_BUILDER take
modelTierIdfrom the row (set by create/update). AGENT and FLOW_STEP take it from the job and write it onto the row afteracquireStreamingLock, including null. Tool RPCs then callaiModelCandidates.grantedEntryConfigwith the run's project, which honours a worker-sentproviderConfigIdonly as an exact{configId, modelId}entry of that tier or of the Fast tier that runs in that project. A tier row switches projects throughagentModelTier.assertProjectSwitchKeepsTier: every key the run can use (after the tool-calling filter, Fast tier included) must serve the new project. Clearing the project counts as moving to every project, so it needs keys open to all projects; a switch from no project checks the tier's platform-wide entries, because nothing records which keys the run kept. Any otherproviderConfigIdgoes through the normal scope check.A platform tier step falls back only on provider failures, decided by
isFallbackWorthyon a signal fromaiProviderSignal.fromError. 401/402/403/404/408/429/5xx, network errors (ai 7 throws them asAPICallErrorwith no status andisRetryable: true) and billing bodies (Anthropic sends low credit as a 400) fall back; any other 4xx and our own errors (classify mismatch, no structured data, web search unsupported) stop. No fallback once a web-search step finished, since it was already billed.Never flatten a provider error with
String(error); usetoErrorfrom@activepieces/core-utils. A provider can end a stream with a plain object instead of anError.String()turns it into"[object Object]"and drops the status, soisFallbackWorthyhas nothing to judge, the tier never moves to its next model, and the user sees[object Object](incident 20 Oct 2026, AI-63).toErrorkeeps the raw value ascause, which is what letsaiProviderSignal.fromErrorreach the status.Worker-built models report no key health through
createModel: no reporter is installed in the worker. Tier steps report explicitly via thereportAiKeyOutcomeRPC, and only provider signals (fromProvider) plus recoveries of non-active keys. Reporting our own errors would demote healthy keys tounreachable. The API never writes a worker-reported status for most providers:confirmReportedOutcomeruns in the background and only triggers arecheckof the real key (once per key per 10s) when the report disagrees with the stored status. The exception is providers flaggedvalidationSkipsModelEndpoint(CUSTOM, Vertex): their check never reaches the model, so a recheck would always pass, and the report is recorded as-is. Any directaiProviderHealth.recordfrom concurrent callers must passexpectVersion(thestatusVersionit read), or an older report landing late overwrites a newer one. The worker token is shared and a shared worker serves every platform, so a report can't be bound to a platform; a forged one can at most cause a recheck. Don't passplatformId/providerConfigIdtocreateModelin the worker, or a future reporter double-counts.ExecuteAiJobDatais a zod schema that strips unknown keys (JobData.parseinworker.tsandjob-broker.ts). A field added only to the TS type silently never reaches the worker; add it toAiStepJobBase.Builders read the slim tier list (
GET /v1/platform-model-tiers) with noconfigIdor key names; the full entries areGET /adminonly. Don't widen the builder view: it would show project users the ids of keys scoped away from them.The managed key only runs models the tiers or the chat allow-list permit, enforced in
aiUtils.createModel. The managed provider is OpenRouter underneath, so before this guard a crafted step naming any OpenRouter model ran on our key; the picker hid it but nothing denied it.assertManagedModelAllowed(server/utils/src/ai-utils.ts) checksmanagedChatModelIds()plus both surfaces' published tiermodelIds and throws aVALIDATIONerror. Image models are checked too, increateModel(imageGeneration: true) andcreateModelForImages: onlyACTIVEPIECES_IMAGE_TIERSmodel ids, plus the id the chat path passes asadminChosenImageModelId(the server-chosen Capabilities model). The worker now callsmodelTierCatalog.warmUp()at start so a cold worker does not judge a newly published tier against the bundled list.A catalog change takes up to ~2 days to reach a dropdown, through three caches in series. CDN edge (
--cache-control max-age=3600, 1h) → the server's in-memory catalog (CATALOG_TTL_MS, 24h) →modelsCache(flushed by the nightlycron.schedule('0 0 * * *')). So "I republished but the UI still shows the old price" is expected, not a bug; restarting the API short-circuits the two in-process layers. The edge TTL is deliberately 1h and not the 604800 thatpublish-embed-sdk.ymluses — that path is version-stamped, ours is a stable key rewritten in place, so a week-long edge cache would pin stale prices for a week.Sync AI Model Catalogis the only workflow that proves the CDN S3 credentials still work — a greenPublish Embed SDKproves nothing. Both read the sameCDN_S3_ACCESS_KEY_ID/CDN_S3_SECRET_ACCESS_KEY/CDN_S3_BUCKET/CDN_S3_ENDPOINTsecrets, butpublish-embed-sdk.ymlguards its upload job onneeds.check.outputs.publish == 'true', which is false whenever the version inpackages/ee/embed-sdk/package.jsonis already on the CDN. Its daily cron then finishes in about nine seconds with the upload skipped and the run still marked success, so the key can rot for weeks behind a green tick — that is how the model-catalog cron came to fail withInvalidAccessKeyIdon three consecutive Mondays while the embed SDK looked healthy. To date a dead key, find the last embed-SDK run whosepublishjob actually ran (gh run list --workflow=publish-embed-sdk.yml, look for a duration in minutes rather than seconds) and compare it against the first model-catalog failure. To test a rotated key, dispatchsync-model-catalog.yml— it uploads unconditionally.Publishing is an overwrite of one S3 key, and it only ever happens on the Monday cron or a manual
workflow_dispatch. Never on merge, deploy or release. There is no versioning and no history: last write wins and the previous contents are gone, which is why the object carriesgeneratedAt—curl -s https://cdn.activepieces.com/ai/model-catalog.json | jq .generatedAtis the only way to tell how fresh what you are serving is. Editing the generator changes nothing in production until someone dispatches the workflow.No egress to the CDN means no model metadata, permanently and silently. Air-gapped installs, networks with an outbound allowlist, and CDN outages all fall back to the plain
{ id, name }row with no message explaining it — every metadata field is optional, so nothing throws.AP_MODEL_CATALOG_URLpoints at a self-hosted mirror and is the only fix. This is a knowing exception to.claude/rules/self-hosting.md(decision 000032), so treat "self-hoster says prices are missing" as a network question, not a bug.A new provider needs an entry in the generator's
MODELS_DEV_PROVIDERmap or it silently ships with no metadata. models.dev provider ids do not match ours:bedrock→amazon-bedrock,qwen→alibaba,moonshot→moonshotai,activepieces→ aliased ontoopenrouterat lookup time. The six OpenAI-compatible vendors were merged before the map was updated and produced exactly this — the run printsno upstream source: …, which is the thing to read after adding a provider.cloudflare-gatewayandcustomlegitimately have no source.The catalog object must be published before the code that reads it ships. There is no bundled copy, so until a
workflow_dispatchrun puts it on the CDN, every install — including local dev — shows no metadata at all.The pricing console shows bundled constants when no file is published, and says nothing.
overview()inai-pricing-service.tshas three states, and two of them render the same numbers: absent (NoSuchKey) silently seeds the editor fromDEFAULT_PRICING_DRAFT, the console's own checked-in copy of the tiers and weights, while unreadable (any other S3 error) shows those same constants plus a banner and blocks publishing. Only present is live data. So a screen full of plausible tiers is not evidence that anything was ever published —curl -I https://cdn.activepieces.com/ai/pricing.jsonis. The absent state is deliberate, it is how the first publish bootstraps, but it means "I can see the tiers" and "the prices are live" are unrelated facts. Worse, absent and misconfigured are the same state:cdnClient.getJsoncatchesNoSuchKeyand returnsundefined, so a wrong bucket or an endpoint with the bucket in its path reads as "nothing published yet" and hides behind the defaults. The tell is the History tab —listdoes not catchNoSuchKey, so the same misconfiguration that reads as empty on the pricing page returns a 500 there. A 500 on history with a normal-looking pricing page means the S3 addressing is wrong, not that the history is empty.Deleting the live tier file is safe for customers and confusing for everyone else.
ai/pricing.jsonwas deleted on 2026-09-24 to drop a leftover test tier, and Activepieces kept serving the right tiers throughout: the 404 makesfetchTiersthrow, the failure is logged and backed off, andcurrent()keeps serving the last good copy the process fetched; only a process that never fetched one, a fresh boot during the outage, runs theACTIVEPIECES_CHAT_TIERSshipped with the release. Two things do change. Each server logs 'Failed to refresh the AI model tiers file' (or 'Failed to load…' on a process that never got a copy) on every failed attempt, and attempts happen at boot and whenevercurrent()is called with a stale or missing copy, at most once per five minutes (FAILURE_BACKOFF_MS), so a permanent 404 is retried the same way as a blip. And the console reads the missing key as absent, so the next publish starts again atversion: 1while theai/pricing/history/objects from the old numbering are still there — the version number islive.version + 1, not a counter, so it is only meaningful between two publishes that never lost the live key. To remove one bad tier, edit and publish; do not delete the object.CDN_S3_*andAP_S3_*are two different buckets on two different providers, and mixing them puts public objects in customer data.cdn.activepieces.comis a DigitalOcean Spaces bucket,activepieces-cdninfra1, fronted by Cloudflare — a 200 from it carriesx-rgw-object-typeandx-do-cdn-uuid, which is how you tell. That is whereai/model-catalog.json,ai/pricing.jsonandsdk/embed/*.jslive, and the credentials are theCDN_S3_*GitHub secrets.AP_S3_BUCKETis something else entirely: the Cloudflare R2 file-storage bucket (ap-files-prodin production) holding run logs, step checkpoints, webhook payloads and flow bundles. The names are similar enough that the pricing console was once configured with the R2 file-storage key by mistake, which would have written apublic-readai/pricing.jsoninto the customer-data bucket whilecdn.activepieces.comstayed 404. When wiring anything that publishes to the CDN, confirm the endpoint is the Spaces region origin (https://fra1.digitaloceanspaces.com, never with the bucket in the path — the SDK appendsBucketitself and the doubled path returnsNoSuchKeyon every call).The weekly sync workflow now pages Discord on failure, but the alert needs
DISCORD_ON_CALL_WEBHOOKin this repo.sync-model-catalog.ymlends with the sameif: failure()step asrelease-pieces.yml. Before that it had no alert, and the only signal that it broke is a 404 on the object, which every reader swallows. Its run on 2026-08-31 failed withInvalidAccessKeyId— theCDN_S3_ACCESS_KEY_IDsecret in this repo does not match a live key — soai/model-catalog.jsonhas never actually landed. Checkgh run list --workflow=sync-model-catalog.ymlbefore believing the CDN is the problem. That sameCDN_S3_*credential also publishes the AI tier fileai/pricing.jsonfromap-analytics(decision 000039), so one dead key silently breaks model metadata and the published tiers at once: the console hides model costs (model-catalog-service.tslogs 'model prices will be hidden' and returns an empty list) while Activepieces keeps serving the tiers bundled in the release. Two features, one credential, no alarm on either.A fresh Cloud platform cannot connect any AI provider, and the UI says nothing about why. The admin page at
/platform/aisetsallowWrite = platform.plan.aiProvidersEnabled, and that column defaults to false on thefreeplan (migration1776…AddDefaultToAiProvidersEnabled), so the connect button is simply absent rather than disabled-with-a-reason. On Cloud the flag is owned by Autumn (autumn-utils.tslists it among the synced features), so there is nothing to configure locally and noDEV_ENTERPRISE_PLANescape hatch on main. For local Cloud testing, flip it directly:UPDATE platform_plan SET "aiProvidersEnabled" = true. Then connect a BYO key, not the managedACTIVEPIECESprovider — per Provider visibility above, the managed row is hidden wheneverOPENROUTER_PROVISION_KEYis unset, which is the normal local state, and a hidden provider makesgetChatProvider()return null. Anything gated on a chat provider (chat itself, personalization research) stays silently disabled until a BYO row exists.Since the AI steps moved to the worker, the server sees every step's model id, and
ai-execute-controlleris the one place to act on it. The piece POSTs/v1/ai/executewithproviderandmodelId, the controller builds theEXECUTE_AIjob from that body, and the worker runs whatever model id the job carries. So anything that needs to rewrite or validate the model a flow step is about to use belongs there, not in the piece — one server-side edit covers all five AI steps, and an old pinned piece bundle keeps working because it only forwards the string it stored. This is what makes storing a tier id in a step cheap: the bundle never has to understand it. Note the agent step does not come through here — it resolves separately overgetAgentConfig, inagent-config-rpc. Two conditions sit under that. An old bundle only forwards the string from0.11.0up —AI_PIECE_COST_BILLING_VERSION, the first version whoseai-step.tsPOSTsv1/ai/execute. A step pinned below it runs the pre-worker code that calls the provider from the sandbox, so a tier id there would reach OpenRouter as the literal string. That case is already closed:migrate-v26-ai-piece-cost-billingbumps every savedpiece-aistep below0.11.0up to it, which is why a later migration can rewrite what a step stores without touchingpieceVersionfor the runtime. And resolve on the API, never in the worker:ExecuteAiRequest.modelIdis a barez.string()so a tier id passes validation,getEffectiveProviderAndModelandaiUtils.buildWebSearchToolsOrThrowboth readdata.modelIdas a real model, and theresolveAiProviderRPC does not carry the model at all, so using it as the seam would mean widening the worker contract.Managed billing can only price an OpenRouter call, and a call it cannot price is simply not billed.
openRouterCostOf(server/utils/activepieces-ai-cost.ts) readsproviderMetadata['openrouter'].usage.cost, with one fallback that GETsopenrouter.ai/api/v1/generation?id=and takestotal_cost. If neither answers,createBillingInforeturnsundefinedand the turn is never reported — it runs, the customer keeps the output, and nothing is charged. Nothing logs "unbilled". This is what actually welds the managed provider to OpenRouter, more than the client does:create-language-model.tsshares one branch forOPENROUTERandACTIVEPIECES, every tiermodelIdis an OpenRouter id, andopenrouter-api.tsmints the per-platform key fromOPENROUTER_PROVISION_KEY. So putting managed credits on any other gateway needs a second cost extractor and a second generation lookup first, or every call through it bills zero. For reference, no Vercel AI Gateway code exists here at all — the only gateway in the repo is Cloudflare's (CLOUDFLARE_GATEWAY, theai-gateway-providerpackage), and@ai-sdk/gatewayappears only as a transitive dep ofaithat nothing imports. A BYOK user can already reach Vercel's gateway today throughAIProviderName.CUSTOM, which takes a base URL plus hand-typed model ids.A tier id that no longer exists resolves to the default tier of its surface, on every door, with a warning.
resolveNamedModelId(the path FLOW_STEP and AGENT take) tells a tier id from a model id by the slash rule: a bare slug is a tier id and goes throughresolveTier, which returns the surface default for an id the file no longer carries and logsTier is no longer published; running the surface defaultwith the tier id and surface; a slashed id is a managed model id and is still refused withThe model "X" is not available on Activepieces AI creditsunless the release ships it or a published tier on that surface carries it. Every other source goes throughresolveModelIdForProvider→resolveTier, the same default. So removing a tier from the file never fails a flow or an agent; it moves them onto the default until they are re-picked. The console may keep saying that removing a tier is safe. Decided 2026-09-26 with PR 2 of the configurable tiers work.The console's Publish writes the live key directly; there is no draft, no staging and no filter.
ai-pricing-service.tsinap-analyticswritesLIVE_PRICING_KEYon Publish, and its "add tier" row seedsid: tier-N,label: New tier, so a half-finished experiment is one click from every server's cached tier list, with only the CDN cache plus the 15-minute in-process TTL in between (see the next bullet: the CDN part can be days, not minutes). Test against a local file withAP_MODEL_TIERS_URL(serve it on127.0.0.1and add127.0.0.1toAP_SSRF_ALLOW_LIST, which takes IPs or CIDRs, not hostnames, solocalhostis still refused), never by publishing.A console Publish can take days to reach servers: the plain
ai/pricing.jsonURL is cached far longer than themax-age=300the console sets. On 2026-10-15 origin had v7 (published 10:00 UTC) whilehttps://cdn.activepieces.com/ai/pricing.jsonstill served v6 withcache-control: max-age=604800andage≈ 28h. The cache is the DigitalOcean Spaces CDN (x-do-cdn-uuidheader), not Cloudflare (cf-cache-status: DYNAMIC): its edge cache TTL is 7 days and it overrides the object's ownCache-Control.fetchTiersfetches the plain URL, so every server keeps refreshing the stale copy. To verify a publish, comparecurl -s https://cdn.activepieces.com/ai/pricing.json | jq .versionwith the same URL plus?cb=$(date +%s). To see what a cloud server actually serves, look atGET /api/v1/ai-providers/tiersin the browser Network tab. If the versions differ, purge that key (doctl compute cdn flush 046c3101-e4a3-49bd-a6f7-3dcd29a2a3d5 --files ai/pricing.json, or Spaces →activepieces-cdn→ Settings → CDN → Purge cache); re-publishing does not help.A console older than the two-list change, or a rollback to one, strips the chat keys on read, and its next Publish drops them with no diff line. The console parses the live file with a zod object, and zod strips keys it does not declare, so
chatTiers,chatDefaultTierIdandchatFastTierIdvanish from the draft the moment an old console reads it. Publish writes the draft back, and the history diff shows nothing because that console never knew the keys. Activepieces then serves chat from the flow list again, silently, since the chat keys are optional. After any console rollback, republish from a current build and checkcurl -s https://cdn.activepieces.com/ai/pricing.json | jq keyslists all nine keys.A managed text step stores a tier id from AI piece 0.12.0 on, and every managed model id stored before that came from a tier pick. For the managed provider and a text step,
props.ts(packages/pieces/community/ai/src/lib/common/props.ts) readsGET /v1/ai-providers/tierswith the engine token and offers theflowlist as{ label, value: tier.id }. On any failure (a server without the route, a network error, an empty list) it offers the release'sACTIVEPIECES_CHAT_TIERS, still as tier ids, so a step saved on 0.12.0 always holds a tier id./modelsis still called for managed image steps (managedImageModelLabelfilters toACTIVEPIECES_IMAGE_TIERS) and for own-key providers. Up to 0.11.0 the dropdown filtered/modelsto the bundled tier models and stored the concrete id, with no way to pin a model deliberately. So the migration from stored model ids to tier ids (ENG-753) has a trivially complete mapping: each stored id is one of the three bundled tier model ids of the release it was saved on. Until it runs, those steps follow the release, not the file.A managed text step on 0.12.0 that still holds a concrete model id shows 'Select AI Model' and keeps running that model. The options are tier ids now.
searchable-select.tsxrenders the placeholder when the value matches no option and keeps the value, anddynamic-dropdown-piece-property.tsxonly clears it when a refresher (hereprovider) changes. The run is unaffected, because the slash rule passes a concrete id through. It only happens when something bumpspieceVersionin place, as a flow migration does. Options are fetched against the step's saved exact version, so a step left on 0.11.0 keeps its old options, and the update dialog's minor bump resets every input (getInputAfterVersionChange,MINOR_OR_MAJOR), so the user re-picks the model with everything else.The AI step resolver skips image steps, because image tiers reuse the text tier ids.
ACTIVEPIECES_IMAGE_TIERSarefast/smart/premiumtoo, andaiJobFor's sharedmodelIdfeeds all five actions. Resolving aGENERATE_IMAGEjob against the flow list would hand an image step a text model. The controller gates onbody.action; any future image-tier resolution needs its own list.AIProviderModelis declared twice, and a field added to one half is stripped on the wire. There is one incore/piece-types(what pieces import, since they cannot import@activepieces/shared) and one incore/shared(what the server and the response schema use). They are not re-exports of each other — today the shared copy carriesmetadataand the piece-types copy does not. Fastify serialises the response against the shared schema and drops every key it does not declare, so adding a field to the piece-types copy alone type-checks in the piece, type-checks in the server, and arrives asundefined. A published tier label was nearly shipped that way. Any new field on a provider model needs both files.No image model belongs to a chat tier, so a tier-based filter empties the image picker. The managed provider is OpenRouter underneath and
openrouter-provider.listModelstags a modelIMAGEwhen itsarchitecture.output_modalitiessays so —ACTIVEPIECESis deliberately absent fromNO_IMAGE_GENERATION_PROVIDERS, andgoogle/gemini-2.5-flash-imageand friends are real managed models. ButACTIVEPIECES_CHAT_TIERSis three chat tiers, so no image model can ever match one. Any filter of the form "a managed model must belong to a tier" therefore drops every image model silently, leavingaiProps({ modelType: 'image' })with an empty dropdown and no error. Gate that filter onmodelType === 'text'.The api test suite runs on the bundled tiers, never the live file.
packages/server/api/vitest.setup.tspointsAP_MODEL_TIERS_URLatmodel-tiers.invalid, so boot warm-up fails fast and every test resolves againstACTIVEPIECES_CHAT_TIERS. CI runners have egress, and the first time a resolver read the file in CI the livedefaultTierIdwasfast, which turned a test asserting the release default (Expert) red with no code change behind it. A test that wants the published shape mocksmodelTierCatalog(test/unit/app/ee/agent/model-tier-fixture.ts); an integration test that boots the app cannot be handed a file.A published tier without
nativeModelIdkeeps every BYOK key on the release's model for that tier id.nativeModelIdFor(ee/agent/agent-model-resolution.ts) takes the tier's ownnativeModelId, else thenativeModelIdof the bundledACTIVEPIECES_CHAT_TIERSentry with the same id, else null, which sends a curated provider to its first curated model and a catalogue-less provider to the first text model its key lists. The fallback is keyed by tier id only, so two lists sharing an id resolve to the same native model on every own-key provider, whatever their managed models are. The BYOK tier map (PR 6 of the configurable tiers work) is the real fix.premiumpairsmodelId: anthropic/claude-opus-4.8withnativeModelId: claude-opus-4-7on purpose. The managed tier runs Opus 4.8 through OpenRouter; a customer's own Anthropic key runs Opus 4.7. The reason is cost on the customer's key: Heavy on a BYOK key must not silently move the customer onto the most expensive model without them choosing it. The console'sdefaults.tscarries the same pair. Do not "fix" either copy.Whatever the console publishes is in every Cloud customer's picker within about 20 minutes on a fresh page load, and about 35 minutes on a page left open: no draft, no staging, no filter.
GET /v1/ai-providers/tiers(ListModelTiersinai-provider-controller.ts) returnsmodelTierCatalog.current(surface)for both lists, keyedflowandchat, to USER and ENGINE principals with no platform or project scope, because the tiers are global; the response schema puts onlyid,labelandmodelIdon the wire. The web reads it through one hook,aiProviderQueries.useModelTiers(surface)(features/platform-admin/hooks/ai-provider-hooks.ts): the chat selector passeschat, the agent picker passesflow, and nothing but a test checks which one a caller passed, since the surface argument the server requires does not reach this layer. Both pickers show the release's bundled tiers while the call is in flight or has failed, so they never render empty. The web query is stale after 15 minutes and refetches on that interval while the tab is visible (staleTimealone only gates the mount, focus and reconnect triggers, so a tab left open would never refetch), which is where the two bounds come from: CDNmax-age5 min plus the server's 15-min TTL for a fresh load, plus one 15-min client tick for an open page, and the server serves its old copy once while it refreshes. The AI piece's own model dropdown reads the same route from piece 0.12.0 (the props.ts bullet above).Every provider auth schema is written twice, and only one copy is the one the server reads.
packages/core/utils/src/lib/ai-provider-credentials.ts(plain zod) backs the API and the web app;packages/core/piece-types/src/lib/ai-providers.ts(zod/mini, so.check(z.minLength(1))andz.optional(x)instead of.min(1)/.optional()) is what@activepieces/pieces-frameworkre-exports to pieces and the engine. Adding a credential field to only one leaves the other silently stripping it — zod objects drop unknown keys, so the upsert still returns 200 and the failure surfaces later as a provider-side auth error. Change both.A schema change in
packages/core/utilsis invisible to another package's tests until you build it. Sibling packages resolve@activepieces/core-utilsthrough itsmain(dist/src/index.js), so vitest incore/ai-providerskeeps parsing against the stale build and a new optional field reads back as dropped.cd packages/core/utils && npm run buildfirst. The API dev server is the opposite:serveruns under tsx with the tsconfig path alias, so it readssrcdirectly — but it only watchespackages/core/shared/src/**, notcore/utils, so a core-utils-only edit needs a restart to take effect. The same staleness makes a branch look green when it is not:distis gitignored, so aftergit checkoutit still holds whatever the previous branch built, and a test that depends on a field added by a sibling PR passes locally and fails in CI. Rebuildcore/utilsafter every branch switch before trusting a run.getEffectiveProviderAndModelexists for one provider, and skipping it makes Cloudflare Gateway fall off the end of any per-provider switch. It looks like generic provider resolution; it is not. It returns its input untouched for everything exceptCLOUDFLARE_GATEWAY, where it splits the model id and maps the submodel prefix (anthropic,openai,google-ai-studio,google-vertex-ai) back to the real provider. So a gateway model ofanthropic/claude-…only reaches an Anthropic-keyed branch if you called it first. Any table or lookup keyed onAIProviderName— the web-search tool table, capability checks — has noCLOUDFLARE_GATEWAYentry and returns nothing for one that skipped the call: no tool, no error, no log. The AI piece calls it at the top ofbuildWebSearchConfig; server-side code that dispatches per provider needs the same call or the same resolution built in.The Agent and the Direct AI steps disagree about whether OpenAI does web search, and both are right.
WEB_SEARCH_MODE_BY_PROVIDERhas noOPENAIentry, sosupportsWebSearch(OPENAI)isfalse— the Agent asks that question before offering the tool and therefore has never had OpenAI web search (it needed the Responses API, which agents did not use until GIT-1848; every OpenAI call is on Responses now, so addingOPENAI: 'native'is the open follow-up). Ask AI never asks it; it builds the tool straight from its own props and has had OpenAI web search all along. SosupportsWebSearchis the agent's policy, not a statement of fact about the provider — reusing it as a general gate silently removes a capability Ask AI users have today. Whoever unifies the two paths has to keep the OpenAI branch reachable without routing it through that gate. The two paths also disagree about the unsupported tail: the piece'swebSearchprop is a plain checkbox with no provider gating, andcreateWebSearchToolends indefault: throw new Error('Provider X is not supported for web search')— so ticking it on Azure, Mistral, xAI, or a Cloudflare Gateway model whose submodel prefix is not one of the four inCF_GATEWAY_SUBMODEL_TO_PROVIDERfails the step. The server'sbuildWebSearchToolsreturns{}for the same input, because the agent gates before calling it. The builder cannot simply be made to throw:supportsWebSearchis true for thepluginproviders (openrouter,activepieces), the agent calls the builder for them, and there is no native entry for either because the plugin rides on the model settings instead — so{}is the correct answer there. The piece has the same shape, returning early for OpenRouter before the switch that throws. Hence two entry points:buildWebSearchToolsstays total for callers that gate first,buildWebSearchToolsOrThrowreproduces the piece's error for callers that do not.The AI-provider create/update endpoints reject unknown
authkeys rather than stripping them (strictAuthinpackages/core/shared/src/lib/management/ai-providers/index.ts). This is deliberately the request boundary only:aiProviderCredentials()still parses stored rows through the loose schemas, because a strict parse of a legacy row falls through to theauth: {}fallback and silently empties a working key. If you tighten the shared schemas themselves, you move a loud 400 into a quiet credential loss.aiProviderModuleis registered unconditionally,agentModuleis not. Inapp.ts,aiProviderModulesits outside the edition switch, whileagentModuleappears only in theCLOUDandENTERPRISEarms — so an AI route hung off the provider module is on Community for free, and the same route hung off the agent module 404s there. That asymmetry is the cheapest way to satisfy 000036: pick the module and there is no edition branch left to get wrong.Chat falls back to the managed Activepieces row, so "no key is flagged for chat" is no longer a wall.
pickChatRowtakes theenabledForChatrow if there is one and otherwise the visibleACTIVEPIECESrow;findAvailableChatProviderRowand both list endpoints share it, so what the picker shows is what a turn will actually run on. Before that, a platform whose managed row sat atenabledForChat = false— and nothing else flagged — gotSetupRequiredState("Set up an AI provider to get started") a second after the chat loaded. Migration1802…AddChatRolloutFreeCreditGrantwas meant to repair exactly that state and matched zero rows: it compared"provider" = 'ACTIVEPIECES'whileAIProviderNamevalues are stored lowercase ('activepieces'). Enum values in raw SQL are the lowercase string, never the TS member name — grep the enum before writing the WHERE clause.Multi-key resolution is deterministic, not configurable. When several keys of one provider are eligible for a project,
resolveEligibleRowpicks by most specificprojectScope(selected>except>all), newestcreatedbreaking ties — there is no priority/default field (decision: providers-redesign-before-routing). The ACTIVEPIECES provider stays a singleton —create()rejects it (aiProvider.activepiecesIsManaged). That ranking is the fallback: a step or agent may also pin a key outright (decision: 000030), in which caseresolveRowForScopeserves that row after checking it is eligible for the caller's project.Every resolver takes a required
ProviderScope; there is no "no project" default (decision: 000027).getConfigOrThrow/getChatProvider/getChatProviderName/listModelsall takescope: { type: 'project', projectId } | { type: 'platform' }. This is deliberate and load-bearing: the first cut madeprojectIdoptional and treated its absence as "every key is eligible", so each new call site that forgot to thread it silently bypassed project scoping — the agent piece/knowledge-base tool handlers, the chat model picker, and theconfigIdmodel lookup each reopened the same hole in turn. Making the argument required turns an omission into a compile error, and{ type: 'platform' }at a call site is a reviewable claim rather than an accident. Only three consumers are legitimately platform-wide: the tool-search embedder, chat memory extraction, and the managed-ACTIVEPIECES singleton.The last fail-open scope lived in the helper that builds the scope, not in the resolvers. Chat resolves the project a turn runs in (
selectRunProject) before it resolves a credential, and that project is nullable — a user who can no longer see any project getsnull. The first cut turnednullinto{ type: 'platform' }, which hands the run every key on the platform and is exactly the hole a requiredProviderScopewas meant to close.agentHelpers.runScopeOrThrowrefuses the run instead; the analytics and billing paths, which want the provider's name and not a credential, take the nullable project id themselves (resolveChatProviderName) and report no provider for a conversation that has none. Rule of thumb: a nullable id feeding a scope constructor is the shape to look for, not a missing argument.The managed ACTIVEPIECES row is a singleton the database enforces, not the code.
create()rejecting it only covers the admin route; the row is also auto-provisioned fromlistVisibleRowson every list, so two concurrentGET /v1/ai-providersboth missed theexistsByand inserted once the unique(platformId, provider)index was dropped.idx_ai_provider_platform_id_managed— unique on(platformId)WHERE provider = 'activepieces'— keeps it single, and the insert carriesON CONFLICT DO NOTHINGso the losing racer is a no-op rather than a 500. Preferred over a distributed lock because the invariant holds even for a writer that never takes one.Reads are split by trust level, and mixing them back together is how the scope bypass keeps returning. Runtime/project reads are
GET /v1/ai-providers?projectId=(deduped to one entry per provider,{provider, name, enabledForChat}only) andGET /v1/ai-providers/:provider/models?projectId=— bothsecurityAccess.project([USER, ENGINE], undefined, QUERY), so an ENGINE principal supplies its own project and a USER must name a project it belongs to, and both always apply the resolved key'smodelScopeallow-list. Admin reads areGET /v1/ai-providers/configsandGET /v1/ai-providers/configs/:id/models—platformAdminOnly, addressing an exact row and returning the unfiltered model list because that is what an admin picks the allow-list from. Never widen the project routes to accept a config id, and never handprojectIds/modelIdsto a project caller: those are other projects' identifiers. That rule is pinned by a guard test asserting the exact key set of a project entry (and of each item in itskeysarray), so adding a field to the project-facing response is meant to failai-provider.test.tsuntil someone states the field is safe to expose.Two keys may legitimately hold the same secret, and you could not detect it anyway. One API key scoped to two rows with different
modelScope/projectScopeallow-lists is a supported setup, not a mistake. Blocking it is also impractical:encryptUtils.encryptObjectuses a fresh random IV per write, so the same credential stores as different ciphertext every time — deduping would need a separate HMAC column. Key names are the thing worth constraining, since a picker showing two rows called "Anthropic key" is unpickable.mockAndSaveAIProviderusessave, not upsert — the old(platformId, provider)ON CONFLICT target died with the unique index; seeding the same provider twice now creates two keys, which is usually what a test wants.ACTIVEPIECES auto-provision needs
OPENROUTER_PROVISION_KEYenv var set ANDaiCreditsEnabledtrue.secret: trueon a credential field is not about masking, it is what stops a stored credential being prefilled back into the form. InPROVIDER_CREDENTIAL_FIELDSthe flag feedssecretKeysOf, and the dialog's default-values builder blanks exactly those keys when reopening an existing key; the password-styleInputis a side effect of the same flag, not its purpose. So dropping it to change how a field renders silently turns a stored secret into a prefilled value. Render differently instead:type(dictionary,textarea) is checked ahead ofsecretinCredentialFieldInput, so a field can keep the flag and still draw as something other than a masked input — that is how the Vertex service-account JSON gets a monospace textarea while staying blanked on edit. Both the initialiser and the required-field check filter onlydictionary, so any othertypeis initialised and validated like a normal credential.Adding a provider is a leaf change, and the credential fields are the only part that is not. A new vendor touches six places: the
AIProviderNameenum (packages/core/utils/.../permission.ts), its auth/config schemas plus the two unions andProviderConfigUnioninpackages/core/shared/.../management/ai-providers/index.ts(all in the per-provider region, well above the generic request/response schemas at the bottom), a strategy file registered inai/providers/index.ts, the model factory switch, name/logo/markdown inpackages/web/src/features/agents/ai-providers.ts, and translation keys. None of that is the credential form: extra fields beyondapiKey(Azure'sresourceName, Bedrock's region) are declared in one file —PROVIDER_CREDENTIAL_FIELDSin.../setup/ai/providers-tab/provider-credentials.ts, which falls back toDEFAULT_CREDENTIAL_FIELDS(a singleapiKey) for any provider with no entry, so a plain API-key vendor needs no UI work at all. That file replaced the deleteduniversal-pieces/upsert-provider-config-form.tsxin the multi-key redesign, so a provider authored against an older branch loses its custom fields on merge silently — git resolves delete-vs-modify by taking the deletion, no conflict marker, and the provider just becomes unconfigurable in the admin UI. A vendor with no/modelsendpoint also belongs inMANUAL_MODEL_PROVIDERSin that same file (CUSTOM,CLOUDFLARE_GATEWAY) so the admin enters model ids by hand. Everything else about a provider is orthogonal to multi-key: that is a table-level change (dropUNIQUE (platformId, provider), add the four scope columns, keep a unique partial index foractivepiecesonly), so a provider inherits multi-key with no provider-side code, and the admin providers-tab enumeratesSUPPORTED_AI_PROVIDERSfrompackages/web/src/features/agents/ai-providers.tsrather than a catalog of its own, so a new vendor appears there on its own. When basing provider work off a branch that predates the redesign, re-checkprovider-credentials.tsafter the merge.The OpenAI-compatible vendors (xAI, DeepSeek, Z.ai, Qwen, MiniMax, Moonshot) share one strategy rather than a file each, via
openAiCompatibleVendor({ name, provider })inai/providers/, with defaults inOPENAI_COMPATIBLE_VENDOR_BASE_URLSand an optional per-keybaseUrloverride because four of them run separate China and international endpoints. TheirlistModelsGETs{baseUrl}/models, which the vendor docs mostly do not document — confirmed working against live keys for DeepSeek, Z.ai, MiniMax and Moonshot (Qwen still unverified), so don't redo that research. If a future vendor turns out to lack/models, the fallback is the manual-models path rather than a bespoke strategy. Unlike its siblings this factory usessafeHttp.axios, nothttpClientfrompieces-common: the base URL is admin-supplied, so it must go through the SSRF filter.Adding an API-key vendor touches these files, and two misses only fail at runtime.
AIProviderName(core/utils/.../permission.ts); theAiProviderCredentialsunion (core/utils/.../ai-provider-credentials.ts) — miss it andaiProviderCredentials()throws at run time, becausecreateLanguageModel'snevercheck cannot see a provider the union never admits;ProviderConfigUnion(core/shared/.../management/ai-providers) — miss it and creating a key returns 400;OpenAiCompatibleVendor,OPENAI_COMPATIBLE_VENDOR_BASE_URLS,NO_IMAGE_GENERATION_PROVIDERSand the exhaustiveAI_PROVIDER_CAPABILITIES(core/piece-types/.../ai-providers.ts); thecreateLanguageModelswitch; the exhaustiveaiProvidersregistry (server/api/.../ai/providers); webSUPPORTED_AI_PROVIDERS, the API-key group inprovider-request.ts, and the markdown translation key;MODELS_DEV_PROVIDERintools/scripts/sync-model-catalog.ts; the two provider lists indocs/admin-guide/guides/setup-ai-providers.mdx; a slot inPROVIDERS_BY_IMPORTANCE(setup/ai/providers-tab/index.tsx), which orders the Providers page and otherwise drops the new vendor after Other (OpenAI Compatible); and a CDN logo. The AI piece no longer has its own factory:ai-sdk.ts/buildLanguageModelwere deleted in #15495 and AI steps run in the worker throughcreateLanguageModel.NO_IMAGE_GENERATION_PROVIDERSis still load-bearing for text-only vendors, becausecreateImageModelreturnsundefinedfor them and that list is what turns an image request into a clear error. Core libraries resolve each other fromdist, so rebuildcore-utilsandcore-piece-types(npm run buildin each) before running a dependent package's tests, or the new enum value reads asundefined.Overriding
fetchon a provider silently switches off key-health reporting....observedis afetch(observedProviderFetch), so any laterfetchin the same options object replaces it rather than adding to it — spread order decides, and nothing errors or logs. A path that needs its ownfetch(the Responses header-stripping one, the Cloudflare gateway'sAuthorization-deleting one) must takeobservedProviderFetch(options.onOutcome)as a delegate and call it, not callglobalThis.fetch. Resolve the delegate at call time rather than capturing it at model-construction time; late binding is both more correct and the only way a test can stub the global. This is the same family as the merge hazard above — the failure is always one provider, or one path within a provider, quietly not reporting.A provider branch merges cleanly and still opts out of whatever the switch gained meanwhile.
createLanguageModelapplies cross-cutting behaviour by spreading it into every case —...observed(observedProviderFetch, added by the key-health work) is the current one. Git treats a long-lived branch's newcaseas an added block, so it lands with none of the spreads its siblings picked up, and the merge reports no conflict: the new provider is simply the one that never reports health. Nothing fails, nothing logs. After merging main into any provider branch, diff yourcaseagainst a neighbouring one and check the spreads match, rather than trusting a clean merge.Only two
Record<AIProviderName, …>maps are exhaustive, so the enum addition barely fights back.AI_PROVIDER_CAPABILITIES(piece-types) andaiProviders(ai/providers/index.ts) must gain an entry;PROVIDER_CREDENTIAL_FIELDS,ALLOWED_CHAT_MODELS_BY_PROVIDER,PROVIDER_MAX_CONTEXT_TOKENS,EMBEDDING_MODELSandWEB_SEARCH_MODE_BY_PROVIDERare allPartial<Record<…>>and degrade silently to defaults.grep -rn 'Record<AIProviderName' | grep -v 'Partial<'is the whole compile-time safety net — every other consequence of a new provider is a runtime question you have to reason about yourself.The repo runs three
@ai-sdkgenerations at once, and the vendor package version is what pins you to one.@activepieces/ai-providersis on ai@7 (@ai-sdk/google4.0.29,openai-compatible3.0.18, provider-utils 5.0.16); the AI piece is on ai@6 (google 3.0.65, openai-compatible 2.0.42, provider-utils 4.0.24); older code sits on the ai@5 line (google 2.0.71, provider-utils 3.0.24). A vendor SDK therefore needs a different release per factory —@ai-sdk/google-vertexis 5.0.36 for ai@7 and 4.0.113 for ai@6 — and taking the newest for both silently mixesLanguageModelV3/V4and fails at the engine boundary. Match transitive deps rather than guessing:curl -s https://registry.npmjs.org/@ai-sdk/<pkg>and pick the version whosedependenciesequal the target package's own pins. Faster still,ls node_modules/.bun/ | grep '<pkg>@'usually already lists every generation bun has resolved.The OpenAI-compatible provider can speak the Responses API, and
@ai-sdk/openai-compatibleis not how you get there. That SDK exposes onlychatModel(/chat/completions) andcompletionModel— no responses model in any version. The route is@ai-sdk/openai, which accepts a custombaseURL+headersand exposes.responses(); the Cloudflare gateway's openai branch already did this before theapiStyle: 'chat' | 'responses'config field existed. Header precedence is the subtlety: the SDK builds{ Authorization: Bearer <apiKey>, ...options.headers }, so a caller header wins onAuthorization(the Bedrock case, where the key is the bearer token) but a customapiKeyHeadersuch asx-api-keyleaves the SDK's defaultAuthorizationriding along.withUserAgentSuffixdropsundefinedvalues, butOpenAIProviderSettings.headersis typedRecord<string, string>, so the way to strip it is the header-strippingfetchthe Cloudflare branch uses — no cast needed, and worth reaching for straight away rather than writing the duplicate header up as an accepted limitation. Strip only whenapiKeyHeaderis not itself Authorization, compared case-insensitively: HTTP header names are, and an admin can typeauthorization. Confirmed shape, since it is easy to assert on the wrong key: the SDK lowercases everything, so a mis-set provider really does emit{authorization: 'Bearer <key>', 'x-api-key': '<key>'}— the credential twice.AWS's OpenAI-compatible surface is two endpoints, and "Bedrock Mantle" is a real AWS product name, not a customer's nickname.
bedrock-runtime.{region}.amazonaws.com/openai/v1(AWS-recommended) andbedrock-mantle.{region}.api.aws/v1both serve Chat Completions and Responses, both authenticate with a Bedrock API key asAuthorization: Bearer, and both take an unmodified OpenAI SDK. Mantle alone adds server-side tools and web search,background=trueasync inference, and Projects/Workspaces; bedrock-runtime alone has Guardrails, cross-Region inference and intelligent prompt routing. So a ticket claiming "Mantle only supports responses" is half right — it serves chat/completions too, and the real loss is the Responses-only capabilities.Vertex is a different door onto the same models, not a different vendor. The
GOOGLEprovider is the Gemini Developer API (generativelanguage.googleapis.com, static API key);VERTEXis Vertex AI ({region}-aiplatform.googleapis.com/v1beta1/projects/{project}/locations/{region}/publishers/google, service-account OAuth2 with ~1h tokens) — the same Gemini models, but billed to the customer's GCP account and inheriting IAM, VPC-SC, CMEK, data residency and audit logs, plus Model Garden's Claude/Llama/Mistral. That rotating token is why the CUSTOM provider can never reach Vertex:buildOpenAICompatibleHeadersinjects one static header, which is why the workaround used to be a LiteLLM proxy.@ai-sdk/google-vertexdoes the JWT-to-token exchange itself, so the native provider needs no proxy. Vertex models are entered by hand (MANUAL_MODEL_PROVIDERS) on purpose: availability is project-, region- and Model-Garden-specific, and apublishers/googlelisting would miss exactly the third-party models that motivate choosing Vertex. But "same models" only holds for Gemini. Model Garden also serves Anthropic, Meta, Mistral and xAI, and those do not share Gemini's API surface —@ai-sdk/google-vertexships separate/anthropic,/maasand/xaientry points for exactly that reason, so onecreateVertex(...)call does not cover Vertex. Because models are typed in by hand, a Claude id reaches the factory as an ordinary string and, unrouted, gets built with the Gemini client and fails at the endpoint.create-language-model.tsroutes ids containingclaudetocreateVertexAnthropic;vertexClientForpicks the client from the id shape, so all three are routed. Because the shapes are unambiguous the check is a lookup, not a tuned heuristic — and note the publisher prefix has to be tested before theclaudeone, or a MaaS path containing "claude" routes to the Anthropic client. Routing is cheap because the id shapes are distinct, not because a heuristic was tuned:gemini-2.5-prois bare, Anthropic carries an@date(claude-3-5-sonnet@20241022), and MaaS is publisher-prefixed and suffixed (meta/llama-4-scout-17b-16e-instruct-maas). The publisher prefix is a stronger discriminator than theincludes('claude')match currently shipped, and it looks like an argument for listing models rather than taking them by hand — but it is not, see below: the listing is scoped to a single publisher, so Model Garden ids stay hand-typed and the string matching stays with them. Listing was considered and rejected, and the reason is worth keeping so it does not get reopened, and the response shape does not need a GCP account to learn — every Google API publishes an unauthenticated discovery document:curl -s 'https://aiplatform.googleapis.com/$discovery/rest?version=v1beta1'returns ~5MB of JSON whoseschemasare the authoritative request/response types.publishers.models.listreturns{ publisherModels: PublisherModel[], nextPageToken }, andPublisherModelis{ name: 'publishers/google/models/<id>', versionId, versionState (STABLE|UNSTABLE), launchStage (GA|PUBLIC_PREVIEW|PRIVATE_PREVIEW|EXPERIMENTAL), openSourceCategory, supportedActions, predictSchemata, frameworks, parent }. There is nodisplayNameon it — the one ingoogle-vertexai's piece comes from@google/genai'sModeltype, which is a different shape, so copying that code gives every row a blank label with nothing failing.displayNameexists only on the nestedparent, which is the base model a tuned model derives from. The decisive fact is in that same doc:publishers.models.listtakesparentmatching^publishers/[^/]+$— one publisher per call. Listing everything therefore means hardcoding the set of publishers to enumerate, which is the same shape of hardcoding it was meant to remove, and Model Garden models would still need hand entry, leaving two mechanisms where there is now one.VERTEXstays inMANUAL_MODEL_PROVIDERSalongsideCUSTOMandCLOUDFLARE_GATEWAY, which fits: Vertex model availability really is per-project. Reach for the discovery doc before a live probe on any*.googleapis.comintegration; a curl against the real endpoint needs billing attached to the project even for a read (403 BILLING_DISABLED), so it is the slower path and it is not free to set up. Thex-goog-user-projectheader is not optional when probing with a personal login: without it aiplatform answers403 SERVICE_DISABLEDnamingconsumer: projects/32555940559, which is Google's shared gcloud CLI project rather than yours, and the message talks about quota projects rather than the missing header. This is a user-credential quirk only — a service account carries its ownproject_id, so the provider itself never hits it. The multi-vendor story is text only. Vertex's image models are Google's own Imagen (imagen-3.0-*,imagen-4.0-*), not Model Garden's third parties, andcreateVertex(...)also exposesimageModel,video,speech,transcriptionandtextEmbeddingModel— none of which we wire today. Imagen is wired (createVertex(...).imageModel(), with aVERTEXcase in the piece's image switch, soVERTEXis no longer inNO_IMAGE_GENERATION_PROVIDERS); video, speech, transcription and embeddings are not. Embeddings still have noEMBEDDING_MODELSentry, so those paths fail with an explanatory message instead of reaching a switch that has no case for it.Chat-tier resolution answers "which model" from three places, and only one of them is the key.
resolveModelIdForProvider(ee/agent/agent-model-resolution.ts, spread intoagentHelpers) now prefers the resolved key's own configured text models when its config carries amodelsarray — that is theMANUAL_MODEL_PROVIDERScase (Vertex, Custom, Cloudflare Gateway), where the admin typed the exact ids the key exposes. An empty catalog is not a missing one, and collapsing the two is how the first cut of this went wrong: a helper returningstring[] | undefinedtreated "lists zero text models" the same as "has no catalog", so a key configured with only image models fell through to the curated list and resolved to a Gemini id it never offered. An admin-listed catalog is the whole truth about a key, so an empty one now refuses the turn with a message rather than guessing. Otherwise it falls back to the staticALLOWED_CHAT_MODELS_BY_PROVIDER, and if the provider is missing from that too it returns the raw tier id with its vendor prefix stripped — which is how a Vertex key once resolved toclaude-sonnet-4-6and handed it to the Gemini client. That map isPartial<, so omitting a chat-capable provider compiles cleanly and fails only at the endpoint. The key's ownmodelScope/modelIdsallow-list is applied last, to whichever candidate list was chosen, and a resolution with nothing left refuses the turn rather than returning a model the key forbids.GetProviderConfigResponsecarries both fields for that, populated at all three construction sites (getChatProvider,getConfigOrThrow,enrichWithKeysIfNeeded); adding fields there is backward compatible because the AI piece reads the response as a typed shape rather than parsing it. I first recorded this as too big for a provider PR — "a wire contract the engine and the AI piece both consume" — having never measured it. It was about thirty lines across four files. Measure before recording something as out of scope; the estimate outlives the guess. The resolver is exported and has five call sites across four files, and only two of them are runs.agent-rpc-handlersresolves the chat turn's model and its fast model, andchat-personalization-serviceresolves both for research — those four must be given the resolved row'sconfig,modelScopeandmodelIds, or the key's constraints are bypassed on exactly the paths a user takes.resolveTierModelinsideagent-helpersis the fifth.agent-servicealso calls it but holds only a provider name and sets a stored default on a draft, so it is correctly left thin (agent-draft-aidid too, until #15676 deleted it). Adding a parameter here means greppingresolveModelIdForProvider|resolveFastModelIdacrosspackages/server, not editing the call site in front of you — threading onlyresolveTierModellooks complete, passes every test, and still leaves the real chat path unconstrained. Thesurfaceargument was added as a required key on the whole family for exactly that reason: a missed call site is a compile error, except inside avi.mockfactory, which is not type-checked and has to be updated by hand. One trap when touching this function: a tier id (fast,smart) is not a model id, so the preferred pick must be the resolved native id unless the selection is itself among the candidates — passingselectedModelstraight through makesresolveFastModelIdreturn the first curated model instead of the fast tier's.A failed credential validation tells the admin nothing, for every provider except Cloudflare Gateway.
aiProviderService.validateProviderCredentialsgates the upstream message behindincludeHttpErrorInMessage, which isprovider === CLOUDFLARE_GATEWAYand nothing else, so everyone else gets a bareFailed to validate credentials for <name>. The cause is not lost — it is logged one line earlier (log.error({ error }, '[aiProviderService#validateProviderCredentials] ...')) and passed as thehttpErrorResponseerror param — but web never rendershttpErrorResponse, so the only way to diagnose a rejected key is the server log. Grep the log forvalidateProviderCredentialsbefore assuming the provider integration is broken — that text is the whole diagnosis, and it is often not about credentials at all. Confirmed case: a brand-new xAI team with no credits purchased answersGET /v1/modelswith403 permission-denied — Your newly created team doesn't have any credits or licenses yet, naming the console page that fixes it, and we render that as "Failed to validate credentials for xAI" — sending the admin off to regenerate a key that was never wrong. Vendors also phrase real key failures inconsistently (xAI uses400 Incorrect API key provided, not a 401). The corollary: a provider that saves without error is not a working provider. A no-credits 403 and a bad key are indistinguishable in the UI, so only an actual generation proves a key end to end. This is an admin-only surface (platformAdminOnly), so there is little reason to keep hiding it.A provider's logo is an asset someone has to upload, not something the code ships.
AiProviderInfo.logoUrlinpackages/web/src/features/agents/ai-providers.tsis a plain string rendered into an<img src>, and every provider points athttps://cdn.activepieces.com/pieces/<slug>.png— nothing is bundled. Adding a provider therefore carries a cross-team dependency with no compile-time or test signal: a slug with no asset behind it renders a broken-image icon in the platform admin list, and only a live request tells you. Check the URL withcurl -o /dev/null -w '%{http_code}'before assuming it works — a vendor that already ships as a piece usually has its logo there already (deepseek.png,grok-xai.pngdid), so start the upload request only for the genuinely missing ones. A Vite asset import also satisfieslogoUrl(seeGoogleIconinplatform/security/sso/index.tsx) and removes the runtime CDN dependency for air-gapped installs, but it diverges from every other provider — treat it as a fallback, not the default. Upload it trimmed, with no built-in whitespace and no solid background:ProviderLogodraws every logo at 22px inside a 36pxLogoPlate, so padding baked into the PNG (Qwen, Azure) makes it look smaller than its neighbours and a filled square (xAI) looks heavier. No code fixes that. Use the symbol only, square, never a wordmark lockup: Meta's and NVIDIA's first uploads were full brand lockups and rendered as unreadable blobs. To cut one from a lockup:magick in.png -crop WxH+X+Y +repage -fuzz 8% -transparent white -trim +repage -background none -gravity center -extent "%[fx:max(w,h)*1.08]x%[fx:max(w,h)*1.08]" -resize 256x256 out.png.The manual-models panel stores a model id and nothing else, so every model an admin adds is typed
TEXT.MANUAL_MODEL_PROVIDERS(Vertex, Custom, Cloudflare Gateway) persist aProviderModelConfigof{ modelId, modelName, modelType }, but since #14825 the UI keeps onlystring[]:ManualModelListis a chip list of ids, andconfig-detail.tsxrebuilds the objects on save with?? { modelId, modelName: modelId, modelType: TEXT }. The olduniversal-pieces/model-form-popover.tsxhad all three fields; replacing it with chips dropped two of them, and no schema or test noticed because the reconstruction is type-correct. The visible damage is not just a mislabelled model:cloudflareGatewayProvider.validateConnectionpings only text models with a/chat/completionsrequest, so one image model added through the UI is validated as chat, fails, and takes the whole key down withThese models have issues: ...— the admin cannot save a key that has an image model on it at all. Anything readingmodelTypedownstream (the agent text-model filter,ap-list-ai-models, the builder's image pickers) is wrong the same way. Fixed by holdingProviderModelConfig[]in the draft rather thanstring[](no migration; stored rows always had the right shape), so the standing rule is that a manual-models UI must carrymodelTypeall the way to the payload — a panel that collapses models to ids reintroduces exactly this, and nothing downstream will complain until an admin adds an image model. Keys saved while the bug was live still hold image models typedTEXT; the type badge on each chip flips one in place, which is why it is editable rather than display-only.Custom keys get model suggestions; Vertex and Cloudflare Gateway stay typed by hand on purpose.
GET /v1/ai-providers/configs/:id/suggested-modelscalls the strategy's optionalsuggestModels, which onlyopenAICompatibleProviderimplements:GET {baseUrl}/modelswith the key's own header, throughfetchOpenAiModelIds(shared with the vendor list), filtered byisChatModelId. The ids feed a<datalist>on the manual-models input, so free text still works and the admin still picksmodelType(/modelsdoes not say text or image). Suggestions never touchlistModels, which staysconfig.modelsbecause tiers and key scope read it. A failed fetch returns[]and logs, so a LAN or localhost base URL thatsafeHttpblocks (self-hosted Ollama, unless inAP_SSRF_ALLOW_LIST) just shows no suggestions. Vertex is not listed for the reason in the Vertex bullet (one publisher per call), and Cloudflare's gateway has no models endpoint. Any fetch to an admin-supplied URL needs three bounds, not one: axios'stimeoutonly fires when the connection goes idle, so a server that drips bytes holds it open, and a huge body is read into memory in full.fetchOpenAiModelIdspassestimeout,signal: AbortSignal.timeout(...)andmaxContentLength. Trim a trailing slash with/\/$/, not/\/+$/: the+form is quadratic on a long run of slashes andbaseUrlhas no length limit (both from review on #16382).AIProviderConfigis an untaggedz.union, so a new provider's config schema must sit ahead of the empty ones — and "empty" includes a schema whose every field is optional. Zod strips unknown keys and a union returns the first member that parses, soAnthropicProviderConfig(z.object({})) matches any object: list it before a{ baseUrl?: string }config and a configured base URL is silently reduced to{}— no error, no log, the admin's override just stops existing on the next read. The file carries anOrder matterscomment, but it says "empty ones last", which reads as though only a literalz.object({})is at risk. The rule is not "after the last schema with a required field" — that phrasing reads as "append afterBedrockProviderConfig" and is how a Vertex config got silently reduced to{ region }, losingprojectandmodelswith no error. What matters is the subset relation, not the count:BedrockProviderConfigis{ region }, a strict subset of{ project, region, models }, so it matches a Vertex object first and strips the rest. Order by specificity — any schema whose required keys are a subset of yours must sit after you. Check with a one-line parse before trusting the order:AIProviderConfig.parse(yourConfig)must return every field it was given.ProviderConfigUnionis discriminated onproviderand so is immune; only the two untagged unions (AIProviderConfig,AIProviderAuthConfig) bite. Both live twice —packages/core/shared/.../management/ai-providers/index.ts(zod classic) andpackages/core/piece-types/.../ai-providers.ts(zod/mini, the copy pieces use) — and every provider edit has to land in both. The third copy moved rather than disappearing..../setup/ai/universal-pieces/is gone and the connect dialog now builds fromPROVIDER_CREDENTIAL_FIELDS, butconfig-detail.tsxdeclares its ownManualProviderConfig = z.union([...])that gates whether the manual-models panel sendsconfigat all. A provider missing from it failssafeParse, its models are dropped from the payload, and they silently vanish on reload — which for aMANUAL_MODEL_PROVIDERSmember means the only way to choose a model does not work. So it is still three unions per provider: the two shared copies plus this one, and it is the easiest to miss because it lives in a component and nothing references the provider by name. The rest of this sentence describes that deleted file and is kept only as history:createFormSchemain the admin dialog (.../setup/ai/universal-pieces/upsert-provider-dialog.tsx) re-declares a per-provider schema, branching explicitly on Azure / Cloudflare / Custom / Bedrock and falling through to a generic case whoseconfigis a union of three empty objects. A provider with a non-empty config and no branch there loses that config entirely —zodResolverhands react-hook-form the parsed value, so the strip happens before submit and the setting is never sent, with no error anywhere. Fixing the shared union does not fix this one; grep for every union of config schemas when adding a provider. The dialog only diverges from the correctProviderConfigUnionto make auth optional in edit mode, so collapsing it onto the shared discriminated union is the real repair. (Testing that file directly is awkward: importing it pulls in a transitive dep that touchesdocumentat import time, which a node-env vitest cannot load — the schema factory would have to move out of the component file first.)Every catalog field is optional, and two providers never match at all. Azure's
listModelsreturns deployment names (arbitrary admin-chosen strings), and CUSTOM / CLOUDFLARE_GATEWAY ids are hand-typed, somodelCatalog.lookupreturnsundefinedfor them by design. Any UI readingmodel.metadatamust degrade to the bare{ id, name }row rather than render an empty unit. Azure could be matched —azure-provider.tsdiscards the upstreammodelfield, which is the underlying base model id.Bedrock ids arrive region-prefixed.
bedrock-provider.tsreturns an inference-profile id (us.anthropic.claude-…-v1:0) when one exists, but models.dev keys the foundation id (anthropic.claude-…-v1:0). The lookup stripsus./eu./apac./global.and keeps the:Nversion suffix, which is part of the upstream key.PROVIDER_MAX_CONTEXT_TOKENSis still a per-provider guess and still drives compaction. The catalog exposes the real per-model window on the API, butaiProviderUtils.getMaxContextTokenswas not rewired: all five call sites (shouldCompact/compactMessagesinee/agent/agent-compaction.ts,runawayTokenCeiling/boundContextForStepin the worker'srun-agent-turn.ts) threadproviderand nomodelId. So EE agent compaction still fires at, say, 200k for every Anthropic model including the 1M ones. Fixing it is plumbing plus anagent-evalsrun.AI is billed on what the call cost, and the weight tables are gone.
MANAGED_MODEL_WEIGHTS,DEFAULT_MANAGED_MODEL_WEIGHT,CHAT_BYOK_CREDIT_WEIGHTandACTIVEPIECES_CHAT_TIERS[].creditWeightwere a static pricing ladder calibrated at about a thousand tokens per call, so a long call billed the same as a short one. Every language model is now built throughbilledLanguageModel(packages/server/utils/src/activepieces-ai-cost.ts): the managed provider bills the dollar cost OpenRouter reports divided byAP_AI_CREDIT_USD_VALUE, and any other provider bills one flat credit. Tool calls stay at one credit each. The own-key credit is per model call for a direct AI step and per turn for an agent — an agent turn is many model round-trips, so charging it per call would have silently raised the price of every agent on a customer's own key. The caller says which it wants withownKeyCredit, and the agent's turn credit is charged inchatToolBilling.chargeForLatestTurnalongside its tool calls. The worker does not know the edition, so the one own-key credit is reported on Community too; the API is what drops it.aiChargeForreturns fixed credits for any non-ACTIVEPIECESprovider, and only the CLOUD and ENTERPRISE arms ofapp.tsset the AutumnbillingProvider; the default provider'strackFeatureis a no-op, so Community records nothing and itsgetCreditsAndAppSumoStatenever blocks. Enterprise records the credit butshouldBlockRunOnCreditsreturns false for that edition, so only Cloud can refuse an AI call for being out of credits. Self-hosters on their own OpenRouter key pay OpenRouter directly, not us.OpenRouter only reports
usage.costwhen the request asks for it. The provider sendsusage: this.settings.usagein the request body and copiescostintoproviderMetadataonly when the response carries one, so withoutusage: { include: true }every managed call reports no cost, bills nothing, and raises no error.openRouterModelSettingsinpackages/server/utils/src/ai-utils.tssets it for the ACTIVEPIECES provider and a test pins it. A call that still reports no cost bills zero, is counted, and pages on-call — there is deliberately no fallback to a table.Ask AI's conversation history is hard-capped at 512 KB, on the write path. The history lives in
context.storeunderask-ai-conversation:<key>, and the store-entry controller refuses a value overSTORE_VALUE_MAX_SIZE. So the history cannot grow unbounded and cannot outgrow a request body — no separate limit is needed wherever it is passed along. An older version of the action could write a{ messages: [] }wrapper instead of a bare array, so any reader has to accept both shapes.A failed
enrichWithKeysIfNeeded()is self-sustaining, and it takes chat down with it.createKeyruns on the chat hot path —chatHelpers.resolveChatProvider→getChatProvidercalls it whenever the platform's managed ACTIVEPIECES row has noapiKey— and thesavehappens after the OpenRouter call, so a failure persists nothing and the next chat turn callscreateKeyagain. The mint runs under a per-platformdistributedLockand re-reads the row inside it, and the write lands only ifauthstill matches the ciphertext it read (ajsonbcompare; the row is then read back, sinceaffectedis unreliable on PGlite). A key that loses that write, or whose write throws, is revoked withopenRouterApi.deleteKey. Two leaks stay open until a reconcile sweep overlistKeysexists: a crash betweencreateKeyand the write, and acreateKeythat times out after OpenRouter has made the key. Seen in prod 2026-07-30:keys-modify-api-rpd-v2429 (OpenRouter's key create/modify bucket, 10k/day on the provision key — a separate limit from inference), which killed every chat turn for the affected platform ingetChatConfigbefore the first token, with no recovery until the bucket reset at 00:00 UTC.A freshly minted managed OpenRouter key can answer 401 "User not found." for up to about 20s, so
enrichWithKeysIfNeededonly saves a new key once it answers. In prod that failed the first chat turns of about 15% of new platforms (AI-158).GET /api/v1/keyis not a good enough check: in a 150-key run (2026-10-27) 7 keys passed it 3 times in a row and then still failed 1 to 3 completions. SoopenRouterApi.isKeyLivesends a 1-token completion and counts only a 401 or no answer as not live (so a retired or down probe model can't stall every new platform for 30s), and the wait needs 3 passes in a row 1s apart. With that, 1 of 150 keys failed one call afterwards, which chat's single retry absorbs (median wait 5.4s, p95 22s). How long a key takes varies with OpenRouter's load, and hammering it with 5+ new keys at once makes keys flap, so measure at most 3 at a time. The wait runs for up to 30s inside the mint lock, before the save, so a concurrent call still sees an empty row and queues on the lock instead of reading a key that isn't live (lock timeout 60s, so waiters outlast a 15s mint plus the wait plus one 10s check). On timeout it logswaitUntilKeyIsLiveand saves the key anyway.openrouter-api.tshas no retry, and every failure is a plainError. Calls go throughsafeHttp.axioswith a 15 s timeout, andopenRouterRequestrethrows any failure as[OpenRouter] <METHOD> <path> error: <status> <body>, so a caller cannot tell a 429 from a 500 without parsing the message.Chat model tiers are Activepieces-only.
ACTIVEPIECES_CHAT_TIERS(fast/smart/premium, shown as Fast/Expert/Heavy) hold OpenRouter-shaped Anthropic ids, so they only mean anything for the ACTIVEPIECES and OPENROUTER chat providers. Any provider that declaresALLOWED_CHAT_MODELS_BY_PROVIDER(openai, anthropic, google) picks a real model id from that list instead. Naively stripping the tier's vendor prefix for every provider is what once sentclaude-haiku-4-5to OpenAI and broke every message.A short model list in the key's picker is the vendor's catalog, not a truncation.
listModelsreturns whatever the provider's own/modelsendpoint gives and filters nothing except the key'smodelScopeallow-list. Anthropic ships roughly a dozen models, OpenAI ~80 (mostly embeddings/tts/whisper), while OpenRouter is an aggregator and returns 400+ from every vendor it proxies — so the counts differ by an order of magnitude by design. Anthropic pages at 20 by default, which is why its request pins?limit=1000. If the list shows exactly three Claude models, that is the chat dropdown reading the curatedANTHROPIC_CHAT_MODELS, a different surface from the admin picker.Read the chat model list through
aiProviderUtils.getCuratedChatModels({ provider }). It is the one accessor the server resolver (agentHelpers.resolveModelIdForProvider) and the chat dropdown share, so the two cannot drift; it returns{ id, label }orundefined— never an empty list, so callers may treat a result as non-empty. Labels come from the hardcodedCHAT_MODEL_LABELS(falling back to the id) rather thanAIProviderModel.name, because the livelistModelsresponse cannot supply one for every provider: anthropic returnsdisplay_nameand googledisplayName, but OpenAI's/v1/modelsreturns ids only.conversation.modelNamecarries either a tier id or a real model id — it is a free string with no discriminator. A legacy tier id resolves to the tier's equivalent model when the provider ships it, else the provider's first curated model, so old conversations keep working after a provider switch. Notepremiummaps to opus 4.8, which the native anthropic list does not carry, so a legacypremiumon anthropic lands on Sonnet. A new web chat sends no model at all until the user picks one (use-chat.tsstartsmodelNameat null): the server resolves the published chat default for that turn and the worker stamps the tier it ran onto the conversation, so the chat default lives in one place, the published file, and the picker shows it as selected by readingchat.defaultTierIdfrom the tiers endpoint. Before that change the web sentsmartexplicitly on every new chat, which is why a publisheddefaultTierIdnever reached web chats. That holds only where the picker shows tiers. An own-key provider with a curated model list shows concrete models, but a null model still resolves the published chat default tier and then that tier'snativeModelId, which is in the Anthropic curated list: a published default offastran Haiku on every Anthropic-key chat while the picker showed Sonnet, and the worker's tier stamp kept it there. Since 7b the chat uses the sharedModelPickerand a new chat sends the pick the pill shows (model-optionsdefaultChoicewhen untouched); agent chats send none, since the agent's job carries its own model. A message sent before the options load goes out with no pick and the server'sdefaultPickresolves it. Caught in review on #15838.Chat-provider resolution is first
enabledForChatrow wins, else the visible managed ACTIVEPIECES row —pickChatRow, shared byfindAvailableChatProviderRowand both list endpoints. So a platform with[openai, activepieces]both chat-enabled still resolves to openai (an explicit pick beats the fallback), while a platform with nothing flagged resolves to the managed row instead of to nothing. The flag a list endpoint reports is therefore the resolved one, not the stored column —ai_provider.enabledForChatcan sayfalseon the row chat actually runs on, andensureManagedProviderRowno longer writes it. The web no longer reads it (7b removeduseChatProvider). There is no Default AI key control any more: it is derived from the platform's Default chat model setting (the "Default chat model" card on Providers), so it always matches the model new chats start on. A chat with no pick and no usable tier stores the Default AI key's first curated model (the pill's default); if that key's models can't be listed it keeps the legacy path rather than failing. A project entry is chat-enabled when it owns the picked row, whichever of its keys carries the flag: ranking (selected>except>all, newest first) and chat selection answer different questions, so readingrows[0].enabledForChatmakes the client report "no provider configured" whenever the chat-enabled key is not the ranking winner.findBy()has noORDER BY, so "first" is not guaranteed stable when several providers are chat-enabled.Listing providers is not a pure read: both
listConfigsandlistForProjectgo throughlistVisibleRows, which inserts the ACTIVEPIECES provider row whenaiCreditsEnabled && !activepiecesExists. AGET /v1/ai-providerscan therefore create a row. It also applies the hidden-provider filter (plan.embeddingEnabledhides the managed provider), which is why the client can trust its output without re-checking flags.A managed chat turn is charged in two events, not one. The model cost arrives per model call from the billing wrapper, and the turn's own-key credit and tool calls are charged by
chatToolBilling.chargeForLatestTurn— which also owns the rule for which tool calls count (mcp__*plus a short allow-list, completed only). Both land onCreditUsageSource.CHAT, so the total is unchanged, but no single event holds a turn's whole cost. There is no fixed per-model price left to show a user: the model picker and the Credits FAQ now say the charge follows the call.Azure model listing (
azureProvider.listModels) is pinned to the retired data-plane api-version2023-03-15-preview— newer versions 404 and breakvalidateConnection; the configuredapiVersiononly affects inference via@ai-sdk/azure(GIT-1310).@activepieces/ai-providersisai@7, so onlyai@7code may call it — a piece must build its own language models. The sharedcreateLanguageModelfactory pinsai@7/@ai-sdk/openai@4/@openrouter@3, whilepackages/pieces/community/ai(and the engine that runs pieces) sit onai@6/@ai-sdk/openai@3/@openrouter@2. #14446 pointed the piece at the factory anyway, which broke it two ways:tscrejects the result (specificationVersion "v4" is not assignable to "v2",LanguageModelV4vs the piece'sLanguageModelV2 | V3), and at runtime the piece's ownai@6generateTextwould refuse a v4 model. CI hid it because the pieces build only runs when a PR's diff touchespackages/pieces/**, and a post-merge run on main diffsHEADagainstorigin/main— empty, so no piece is ever built there. Fixed by giving the piece back a localbuildLanguageModelswitch built on its own SDKs; the factory is server-side only until the pieces move to AI SDK 7. Cloudflare Gateway is the one provider the factory refuses (throw) because its routing is caller-specific; each caller builds that one itself. The standing consequence: a new provider must be added to BOTH switches —createLanguageModelinpackages/core/ai-providersandbuildLanguageModelinpackages/pieces/community/ai/src/lib/common/ai-sdk.ts— and the piece one is the easy half to forget, because nothing before step execution touches it. Miss it and the provider connects, validates, lists its models and saves without complaint, then every AI-piece step dies at run time on the switch'sdefault:withProvider <name> is not supported. Since pieces cannot import@activepieces/shared, anything the piece-side case needs (base-url maps, config types) also has to be re-exported throughpackages/pieces/framework/src/index.ts. Thegit show --statof the commits that added Mistral (#13088) and Bedrock (#12712) is the reliable checklist for what a provider actually touches — both includeai-sdk.ts.Attribution headers are for
ACTIVEPIECESonly, and go through the factory'sextraHeadersoption rather than a localcreateOpenRoutercall. The managed provider is OpenRouter under the hood on our own key, so thex-ap-*headers are what tag our account's events:x-ap-platform-id/x-ap-conversation-id/x-ap-run-idon the agent path,x-ap-project-id/x-ap-flow-id/x-ap-run-idon the piece path. BYOKOPENROUTERis a customer's own account and must not get them. Constructing the provider inline to attach headers is also what silently dropsopenRouterSettings(the web-search plugin), since the factory is the only place that still passes them. (CUSTOMseparately receives the piece-path metadata headers — that is #11700's metadata forwarding for self-hosted OpenAI-compatible endpoints, older than either the rename or the Autumn work and unrelated to OpenRouter attribution. Its precedence is deliberate: admin-configureddefaultHeadersoverride thex-ap-*metadata, and the api key is applied last.)mistralViaOpenRouterdoes not mean "the managed provider"; it is read only inside theMISTRALcase, and that branch looks like dead legacy.ACTIVEPIECESroutes through OpenRouter unconditionally and ignores the flag, so the only thing the agent path'smistralViaOpenRouter: truedoes is send aMISTRALchat row to openrouter.ai — carrying that row's Mistral key, which cannot authenticate there.MISTRALalso has noALLOWED_CHAT_MODELS_BY_PROVIDERentry, sogetCuratedChatModelsreturnsundefinedfor it and the resolver falls back to a tier's OpenRouter-shaped id. The fall-through arrived as a drive-by in #13489, not as a routing decision. Don't infer "this provider is AP-managed" from that case group.AI Tool Configs are a sibling feature (same
ai/dir), distinct from AI Providers: they give the chat assistant external capabilities via/v1/ai-tools(platform-admin, EE/Cloud). AiToolCapability =WEB_SEARCH/WEB_SCRAPING/IMAGE_GENERATION; AiToolProvider =TAVILY/FIRECRAWL/APIFY/FAL. One config per capability (unique on platformId+capability); consumed by chat viagetEnabledTools(). Because the config is per-platform, it can never serve a first-run flow on Cloud. A self-serve signup lands on a brand-new platform with no configs at all, sogetEnabledTools()returns{}for exactly the users a new-signup feature is aimed at, and any capability read from it silently no-ops rather than failing loudly. A capability that has to work for someone who just signed up needs a cloud-wideAppSystemPropkey instead, the wayTURNSTILE_SECRET_KEY,FEATUREBASE_API_KEYandAPPSUMO_TOKENare sourced. Note there is noENRICHMENTcapability here, so anything needing people or company enrichment has nowhere to read a key from today./v1/ai-toolsis registered only in the CLOUD and ENTERPRISE branches ofapp.ts, but the AI Center page that reads it is not edition-gated — so a Community admin opening the Capabilities tab fireduseAiToolConfigs, got Fastify'sRoute not found, and the page showed the global "Failed to load data" dialog of the day. Shipped that way from #13911 until the tab was gated onApFlagId.EDITIONin the page. What made this class of bug hard to place is that the surface was then page-independent (raised fromQueryCache.onErrorinquery-client.ts) and React Query's 3 default retries meant it landed several seconds later on whatever page you navigated to next (the report was against/platform/general). The tab now rendersDataFetchErrorStatein place instead, so a repeat would at least accuse the right page. When a screenshot's edition is in doubt, read the sidebar: Billing & subscription and Usage carry a lock only whenedition === COMMUNITY, every other lock there is plan-driven. Any new EE-only route needs its UI entry point gated the same way,enabled:on the query or hiding the surface.The AI Center providers page renders its whole state machine off one query, so every branch needs an
isLoadinggate above it.ProvidersTabderives the empty state, the grouped list and the?config=<id>detail view fromuseAiProviderConfigs(). While that query is pending,dataisundefined—configsis[], so the empty "Connect your first provider" screen paints for a frame, and a hard refresh on a?config=URL finds no matching row and falls through to the list before flipping to the detail page. The parentSuspenseWrapperdoes not cover it: the route chunk and the suspense-backed projects collection resolve first, then the component mounts with no providers yet. Any new branch added to this page belongs below theif (isLoading) return <ProvidersSkeleton />gate, not beside it.A save bar in the AI Center needs a full-height column, not
fixedand not baresticky. The page sits inside two nested scrollers —PlatformLayout'sflex flex-col flex-1 overflow-autoand the AI Center's ownflex-1 overflow-autocolumn — sofixed inset-x-0centres the bar on the viewport, roughly a sidebar-width left of the content column it belongs to. Swapping it tosticky bottom-4fixes the centring for free but pins nothing when the content is shorter than the viewport: the bar just lands wherever the content ends, mid-page. The working shape ismin-h-full+flex flex-colon the tab-content wrapper,flex-1on theTabsContent,growon the panel root, thensticky bottom-4 mt-autoon the bar —mt-autohandles the short page,stickyhandles the long one.min-h-fullresolves only because every ancestor up toSidebarInset h-fullhas a definite height; that chain is what makes the whole thing work, so check it before reusing this elsewhere.A chat tier is our own idea, so it has no meaning on a provider we ship no curated model list for — resolve it by asking the key what it offers.
ACTIVEPIECES_CHAT_TIERS(fast/smart/premium) only maps to a real id throughALLOWED_CHAT_MODELS_BY_PROVIDER, which covers Anthropic, OpenAI, Google, Vertex and Activepieces. Everything else — Bedrock, Azure, Mistral, xAI, DeepSeek and the other OpenAI-compatible vendors — has an empty candidate list. The resolver used to invent an id from the tier (strip the vendor prefix, dots to dashes:anthropic/claude-haiku-4.5->claude-haiku-4-5), which Bedrock rejected as "The provided model identifier is invalid" (GIT-1840, Pylon 5836). #15355 removed the invention and left a throw in its place, which was worse: every agent turn on those providers died withENTITY_NOT_FOUND: this AI provider key allows no text model a chat turn can run onbefore the configured model handled anything (Pylon 6069). The missing ingredient was never a smarter guess, it was the key's own model list.agentHelpers.resolveModelIdis now the single resolver for every surface: it tries our catalogue first and, only when that has nothing to say, readsaiProviderService.listModels(process-cached, cleared nightly by cron, already filtered by the key'smodelScope), preferring a model whose id contains the tier'snativeModelId— Bedrock spells themeu.anthropic.claude-sonnet-4-6-..., so a tier still selects the model it names wherever the vendor hosts it, and otherwise degrades to the first text model the waypickAllowedModelalready does for an admin-listed catalogue. Picking from a list the provider returned is the opposite of the fabrication #15355 removed. Two traps, both learned the hard way. First, an agent surface and generic chat are not symmetric: an agent carries a real model id (its picker listslistModelsoutput unfiltered, precisely because these providers have noALLOWED_CHAT_MODELS_BY_PROVIDERentry) while chat carries only a tier name, because the pre-7b chat selector fell back to tier options whengetCuratedChatModelsreturnedundefined. Second, being listed proves the key can see a model, not that the account can invoke it — so where a model is already settled the fast round reuses it rather than choosing again (getAgentConfigpasses the model the turn resolved; the tool RPC gets the run's own model from the worker,modelIdonexecutePieceTool). One more trap, found in review on 2026-09-27: a stored name is not the model the run ran on. The worker stamps the resolved tier id on an agentless inline run's conversation, so reading it back as a model hands a baresmartto a catalogue-less own-key provider, and no rule on the string can save it, because a deployment may be namedsmarttoo. So nothing is read off the conversation or the agent for the fast round any more: the worker says which model the turn resolved,modelIdonExecutePieceToolRequest(core-execution), and the API borrows exactly that. The field is required, not optional, because the dispatch gate keeps worker and app on one release, so an older worker never reaches a newer API. Resolving the fast tier independently once picked a Haiku the account could not invoke and failed a turn whose configured Sonnet worked fine. A borrowed model still has to pass the key's currentmodelScope, or resolution falls through to the list, which applies it. Nothing crosses the worker, so a rolling deploy has no version-skew window.Non-chat models are filtered out centrally in
fetchModels, not per provider strategy. OpenAI's/v1/modelsreturnswhisper-1,tts-1,gpt-4o-transcribe,text-embedding-3-*,omni-moderation-latestandsora-*, and every strategy that cannot tell them apart typed themTEXT— so they were offered in Ask AI / Summarize / Classify / Extract and died at run time on chat completion (#14496). OneaiProviderUtils.isChatModelIddenylist now runs insidefetchModels, which is the single choke point behind both the project route and the adminconfigs/:id/modelsroute, so a new provider is covered without opting in. Three things about it are load-bearing: it tests onlyTEXT-typed rows, so image models are untouched; it never judges a name the customer chose — admin-typed configs ('models' in config— VERTEX, CUSTOM, CLOUDFLARE_GATEWAY) skip it because an admin who typed an id meant it, Azure skips it (modelIdsAreCustomerNamedon the strategy) because it lists deployment names likesupport-voice-agentand filters ondeployment.modelitself, and a fine-tune is judged by its base model only (ft:<base>:<org>:<label>:…, Azure<base>.ft-…) so an org calledvoiceflowor acontent-moderationlabel does not hide a working chat model; andvalidateConnectionbypassesfetchModelsentirely, so a key that lists nothing but whisper still validates as a working key. The rule is a denylist on purpose — an unknown id is treated as chat, so a self-hoster's own model on a custom endpoint never disappears, at the cost of a new modality leaking until a pattern is added. Because pieces may not import@activepieces/core-*(eslintno-restricted-imports), the openai piece'sisLLMreaches the same ruleset through apackages/pieces/framework/src/index.tsre-export. Still leaking, knowingly: vendor-branded generative models on the five compat vendors that publish no modality data (cogview-*,wan*,music-*,video-01), whose real ids nobody could verify without five paid keys — xAI is handled structurally, see the next bullet.xAI is the one compat vendor asked what its models output, because it is the one that answers.
listVendorModelshits/v1/language-modelsfor XAI first and keeps a model only whenoutput_modalitiesincludestext; the OpenAI-shaped/v1/modelsthat the other five vendors use carries no modality field at all, which is whygrok-2-image-1212and the Grok Imagine image/video models were offered as chat. A model that declares no modalities falls back to the id denylist. Every failure mode degrades to the old path rather than emptying the picker: a 404, a changed shape, or an emptymodelsarray all fall through to/v1/models, and because that fallback is what authenticates, a bad key still fails validation with the vendor-prefixed error. The endpoint pair (/language-models,/image-generation-models) was already known in-repo —packages/pieces/community/grok-xaicalls both. Adding a vendor toVENDORS_DECLARING_MODALITIESis the whole opt-in; do it only with a real/modelsresponse in hand, not from recollection of a catalogue.Google is filtered on
supportedGenerationMethods, and that is what keeps Imagen out of the image picker. A model survives only if the field is absent or includesgenerateContent, which is the only way to excludeaqa(generateAnswer) andgemini-embedding-001(embedContent) — no name pattern catches them. The side effect is deliberate:imagen-*was classifiedIMAGE(because'imagen'.includes('image')) and offered in Generate Image, but the AI piece reaches Google image generation throughgenerateText/:generateContent(there is nogooglecase inbuildNativeImageModel), and Imagen only answers:predict— so those options always failed at run time. Gemini image models do exposegenerateContentand are unaffected; Vertex is where Imagen actually works, and it is admin-typed so the filter never sees it.packages/server/api/src/app/ai/— backend module: provider controller, service, entity, module, plus the sibling ai-tool-config filespackages/server/api/src/app/ai/providers/— per-vendor strategies keyed byAIProviderNamepackages/server/api/src/app/platform/billing-provider.ts—assertCreditsAndAppSumoNotExceededcredit gatepackages/server/api/src/app/ee/platform/platform-plan/openrouter/openrouter-api.ts— the OpenRouter provisioning client (createKey/updateKey/getKey/listKeys/deleteKey)packages/core/ai-providers/src/lib/create-language-model.ts— the shared per-provider model factory (createLanguageModel,buildOpenAICompatibleHeaders) used by both the AI piece and the agent pathpackages/core/shared/src/lib/management/ai-providers/index.ts— shared zod schemas, enums, request/response typespackages/core/shared/src/lib/management/ai-tools/index.ts— shared schemas for the AI Tool Configs siblingpackages/web/src/features/platform-admin/api/+packages/web/src/features/platform-admin/hooks/— frontend API clients and TanStack Query hooks (ai-provider-*,ai-tool-config-*)packages/web/src/app/routes/platform/setup/ai/— the AI Center:providers-tab/(provider groups, connect dialog, per-config detail panel with model and project scope pickers) andcapabilities-tab/packages/web/src/app/routes/platform/setup/ai-capabilities/— admin page, capability dialog, provider catalog for AI Tool Configspackages/web/src/features/agents/ai-model/— model selector used in agent step settings
Paths verified 2026-07-26.
OPENROUTER_PROVISION_KEYis a management key and cannot make inference calls; only the per-platform keys it mints can. OpenRouter states it outright: management keys are for creating, listing, updating and deleting other keys and are rejected by every completion or decisions endpoint. So "we already have an OpenRouter key" is true for provisioning and false for anything that needs to call a model at the instance level (the AI Router's Jev call, for example): that needs an ordinary inference key from the same account, created in the dashboard or via the samePOST /keysthe instance already uses, with a creditlimit. The AI Router does exactly that since 2026-09-23: it runs on the platform's managed key where credits are on, else the admin's own OpenRouter row, as a workerEXECUTE_AIjob billed like any AI step.z.enum(SomeTsEnum).exclude([SomeTsEnum.MEMBER])compiles and excludes nothing at the type level; pass the key string,.exclude(['MEMBER']). zod'sexcludeis typed overkeyof Tand returnsZodEnum<Omit<T, U[number]>>. A TS enum member is its own literal type, not the string'MEMBER', soOmitfinds no key to drop and the inferred value type keeps every member, while the runtime check does exclude it. The symptom is one step removed from the cause: a switch over the parsed field is suddenly non-exhaustive (switch-exhaustiveness-checkin lint,TS2366in the build) even though the branch you removed can never arrive./v1/ai/executehit this whenROUTEwas carved out ofAiStepActionfor #15707. Neither vitest nor a package-local eslint run without type information reports it; only the build does.- The managed Activepieces row can never restrict its models, so a finding that the managed picker offers a model the key forbids is not reachable. The row is inserted with
modelScope: 'all', modelIds: [],create()refusesprovider === ACTIVEPIECES(aiProvider.activepiecesIsManaged), andupdate()handles onlyenabledForChatfor it and returns before any scope field is read (ai-provider-service.ts). Every published tier therefore runs on it, and anymodelScopefiltering on the managed path is inert. Reviewers (Greptile on #15871) raise this as a P1; answer with these three facts rather than adding a filter. - OpenAI, Azure and Meta language models run on the Responses API with
store: false; everything else OpenAI-shaped stays on Chat Completions. New OpenAI-shaped vendors default to Responses whenever their API serves an OpenAI-compatible/responses(Meta's does; NVIDIA's hosted API serves only/chat/completions, so NVIDIA stays on chat).createLanguageModelbuilds OpenAI and Azure with.responses(). A Cloudflare Gatewayopenai/*text model goes to the gateway's/openaiendpoint with.responses()on both routes: chat and agents userouting: 'compat', which otherwise sends everything to/compat/chat/completions, so the OpenAI check has to sit before the compat early return.withoutServerStoragewraps them sostore: falseis the default. Chat Completions refuses tools + reasoning from gpt-5.4 on, and the gpt-5.6 family needs Responses for agents and chat (GIT-1848).store: falsematters because the defaulttruemakes the SDK replay saved history asitem_referenceids, which break after OpenAI's 30-day retention, on a key switch, or when compaction drops parts. Azure's Responses model readsproviderOptions.azureand only falls back toopenaiwhen that key is absent, so set options under the provider's own key. The vendors (xAI, DeepSeek, ...), Mistral, every non-OpenAI model on the Cloudflare compat route, and Custom keep Chat Completions, because many of them only speak it. Custom offers Responses throughapiStyle: 'responses'. To teststore: false, give the saved assistant turn a text part with anitemId. Withstore: truethe SDK swaps only text, reasoning and provider-run tool parts foritem_reference, and plain function tool calls are always sent in full, so a tool-call-only fixture passes either way. - Meta's Model API accepts only
tool_choice: auto; anything else is a 400. Two callers force a tool choice: Extract structured data (required) and the agent's last step (a named tool, ornone).createLanguageModelwraps Meta inautoToolChoiceOnly, which sendsrequiredasauto, a named tool asautowith only that tool offered, andnoneas no tools.autoalone lets the model answer in text, so a forced call also gets an instruction naming the tool and one retry when the reply has no tool call, and a second text reply throwsForcedToolNotCalledErrorso callers fail instead of completing without the tool output; a forced streamed call (the agent's last step) is served from that retried generate call throughsimulateStreamingMiddleware. Any middleware that calls the model more than once must return the summedusageof every attempt (addUsagethere):billedLanguageModelbills only the usage on the returned result, so a dropped attempt is unbilled spend. A middleware that throws after spending tokens has to carry the usage on its error the wayForcedToolNotCalledErrordoes, andreportFailedAttemptsinactivepieces-ai-cost.tsmust recognise it (bynameand ausagefield), or the failed call is never billed. Do notimportthe error class intoserver-utils: CI installs two copies of[email protected]with different peer hashes, and pullingai-providers' types in first makes the globalAI_SDK_TELEMETRY_INTEGRATIONScome from the other copy, which fails theserver-utilsbuild inagent-ai-utils.ts(it passes locally, where bun dedupes them). Reuse it for any vendor with the same limit rather than patching callers. The Llama API (api.llama.com) that predates it shut down on 2026-07-06; Meta now means the Muse models onapi.meta.ai/v1. - NVIDIA's hosted keys (build.nvidia.com) are for trial and development only, and its
/modelslists classifiers next to chat models. NVIDIA's terms forbid production use of the hosted catalogue (about 40 RPM, no paid tier), so production users run NIM themselves and connect it through Other (OpenAI Compatible). The catalogue's ids carry no capability field, so theguard,safety,reward,parse,clip,detector,calibrationanddeplotfragments inNON_CHAT_MODEL_ID_FRAGMENTSare what keep guard, reward and parser models out of chat pickers. - Capability cards draw a service's logo from
AI_TOOL_CATALOG(setup/ai-capabilities/catalog.ts,logoUrl), not from a piece. Tavily, Firecrawl and Apify reuse their piece logos on the CDN; fal.ai has no piece, sopieces/fal-ai.png404s and the card shows an "F" until someone uploads it. A new capability also needs a group incapabilityGroups()and a colour inCAPABILITY_LOOK(setup/ai/capabilities-tab), or it never renders. - Replacing a key's credentials remounts the key page.
ConfigDetailis keyed${id}:${credentialsVersion}andonConnectedbumps the version, so any unsaved edit on the page would vanish while the toast says "Saved". The Replace button is therefore disabled while the page is dirty, and?tab=settings(read intoinitialTab) brings the admin back to Settings after the remount. It lives in the URL, not state, so leaving by the breadcrumb or Back and reopening the key starts on Models again. Anything else that refreshes the key from outside the page needs the same guard.