Skip to content

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

feat(ai): read the model tiers from a published file, with a chat list and a flow list (#15823)

Louai Boumedieneb13fd7b1d159
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.md
index 988c63e0c76..b791144568c 100644
--- a/brain/knowledge/ai-intelligence/ai-agents.md
+++ b/brain/knowledge/ai-intelligence/ai-agents.md
@@ -10,6 +10,16 @@ A flow step type (the `run_agent` action of `@activepieces/piece-ai`) that runs
- A step either carries its own configuration in the flow version's step settings — `settings.input` holds `agentTools`, `structuredOutput`, `prompt`, `maxSteps` and `aiProviderModel` (`{ provider, model, configId }`) — or stores the `externalId` of a saved **Agent** (`agent` table, `ee/agent/agent-entity.ts`) under `agentId` and carries nothing else. A linked step is resolved at run start, so improving the agent improves the next run of every flow using it. The two are exclusive: a step that sends both is refused.
- Configured entirely in the Flow Builder (`web/src/app/builder/step-settings/agent-settings/`); a test panel runs a single agent step. `AgentTimeline` renders `AgentStepBlock[]` from the output as markdown blocks + expandable tool-call cards.
+- **One engine, four doors.** Chat, agent chat, the agent builder and `run_agent` are not four systems. Each creates an `agent_conversation` row and runs the same `EXECUTE_AGENT_RUN` worker job, and the worker calls back over `getAgentConfig` (`ee/agent/rpc/agent-config-rpc.ts`) to ask which model, tools and instructions to use. The assistant chat is an agent turn with no agent row. Which tier list a door resolves against follows `namesItsOwnModel` in that RPC: FLOW_STEP and AGENT name their own model and read the flow tiers; CHAT and AGENT_BUILDER read the chat tiers. An agent therefore resolves the same model everywhere it is used: configured, chatted with, or dropped in a flow.
+
+| Door (`AgentRunSource`) | Model comes from | Stored as |
+|---|---|---|
+| `CHAT` | `conversation.modelName`, picked in the UI | tier id |
+| `AGENT` | `agent.draft.modelName`; no picker is shown while chatting (`ai-chat-box.tsx` hides it when `agentId` is set) | concrete id |
+| `AGENT_BUILDER` | `conversation.modelName` | tier id |
+| `FLOW_STEP` | `agent.published.modelName`, or the step's own `input.aiProviderModel.model` | concrete id |
+
+Three things follow. `run_agent` has two modes: pointed at a saved agent (`agentId` set) the step sends no model and the agent row decides; inline, it sends `input.aiProviderModel.model`. An agent row carries two configs: agent-page chat reads `agent.draft`, a `run_agent` step reads `agent.published` (via `resolvePublishedAgent`), so the same agent can already run different models through different doors. The fast model crosses every door: `firstStepUsesFastModel` (`run-agent-turn.ts`) runs the first step of almost every turn on the fast tier, flow steps included, whatever the user picked. `execute-agent-run.ts` persists `config.tier.id` onto `conversation.modelName` when the job carried no `modelName`, so conversations already hold tier ids today (inline `run_agent`, eval runs, every `AGENT_BUILDER`), read back by `chat-tool-billing.ts`, `chat-analytics-sync.ts` and `pinnedModelOf`.
### Tool types (AgentTool discriminated union)
@@ -20,6 +30,8 @@ A flow step type (the `run_agent` action of `@activepieces/piece-ai`) that runs
- **PredefinedInputsStructure** — per-field `AGENT_DECIDE` / `CHOOSE_YOURSELF` / `LEAVE_EMPTY` baked into the tool so the agent knows which inputs it controls.
### Gotchas
+- **A chat turn's data lives in jsonb, so recording something per turn needs no migration.** `agent_conversation.messages` is a `jsonb` column and each entry is a `PersistedAgentMessageSchema`, which already carries optional per-turn fields (`thinkingDurationMs`, `feedback`). Adding another optional one is a zod field plus a `@activepieces/shared` patch bump — no column, no migration, no rollback flag. The conversation row itself only has `modelName`, which is why "record it on the conversation" is usually the wrong instinct: a user can switch tier mid-conversation, so anything that describes one turn belongs on the message, not the row.
+- **But the server does not build those messages, so "no migration" does not mean "cheap".** `messages` arrives already assembled from the worker over RPC (`saveAgentMessages` in `rpc/conversation-rpc.ts`), and the server only persists it and bills off it. Putting a new per-turn field on a message therefore means changing the RPC request schema and the worker that fills it, not editing a server file. Costing this off the jsonb shape alone gave an estimate of about an hour for work that is really a change to the engine contract. Check who authors the object before you price a change to it.
- **`CHAT_HIDDEN_TOOL_NAMES` is load-bearing for the MCP Activity feed, not just for chat UX.** The chat reaches the MCP server as an ordinary HTTP client, and `mcp_activity` records `ap_run_action`. The only thing keeping chat activity out of that feed is `ap_run_action` sitting in `CHAT_HIDDEN_TOOL_NAMES` (`core/shared/src/lib/ee/agent/tool-phases.ts`), filtered worker-side in `agent-mcp-client.ts`. Remove it and the chat starts writing rows into a tab meant for external MCP clients, with no test failing. See the MCP Server page for the enforcement that was designed and deliberately not built.
- Gated by `platform.plan.agentsEnabled`; when off, the step type is hidden from the piece selector. Off by default on Community, on for Cloud plans that include it.
diff --git a/brain/knowledge/ai-intelligence/ai-providers.md b/brain/knowledge/ai-intelligence/ai-providers.md
index be0a26e5ebb..6c9620816de 100644
--- a/brain/knowledge/ai-intelligence/ai-providers.md
+++ b/brain/knowledge/ai-intelligence/ai-providers.md
@@ -12,9 +12,9 @@ Lets platform admins configure one or more LLM backends for AI pieces in flows.
- Supported providers (10): `openai`, `anthropic`, `google`, `azure`, `openrouter`, `bedrock`, `mistral`, `cloudflare-gateway`, `custom` (OpenAI-compatible, e.g. Ollama/LM Studio), `activepieces` (auto-provisioned via OpenRouter).
### How it works
-- `GET /` list (auto-creates ACTIVEPIECES when `aiCreditsEnabled`); `GET /:provider/config` returns decrypted auth (engine-only); `GET /:provider/models` (cached); `POST /` create (validates creds first); `POST /:id` update; `DELETE /:id`.
+- `GET /` list (auto-creates ACTIVEPIECES when `aiCreditsEnabled`); `GET /:provider/models` (cached); `POST /` create (validates creds first); `POST /:id` update; `DELETE /:id`.
- For ACTIVEPIECES, update is blocked by an early return (only enabling `enabledForChat` is allowed); deletion is allowed and self-healing — `listProviders` recreates the managed row.
-- Engine integration: AI pieces call `GET /v1/ai-providers/{provider}/config` on **every AI action execution** (no per-run caching), authorized by the engine token.
+- Engine integration: the AI piece no longer fetches credentials. It POSTs `/v1/ai/execute`, the server enqueues an `EXECUTE_AI` worker job, and the worker resolves the provider over the `resolveAiProvider` RPC. `GET /:provider/config` was removed in [#15494](https://github.com/activepieces/activepieces/pull/15494).
- For the managed ACTIVEPIECES provider that config route is also the **credit gate**: `assertCreditsAndAppSumoNotExceeded` (`platform/billing-provider.ts`) throws `QUOTA_EXCEEDED` when 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 (`autoTopUps` in `autumn-billing.ts`), not Stripe.
@@ -45,6 +45,23 @@ Prices are rounded to three decimals in the generator, both to kill float artefa
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. Today only `warmUp()` calls it: the
+resolution helpers in `ee/agent/agent-model-resolution.ts` (`findTier`, `resolveTier`, `FAST_TIER_ID`) still read
+the bundled list and are the next thing to move. `AP_MODEL_TIERS_URL` overrides
+the URL. The file is published from the console in `ap-analytics`; see decision 000041.
### Gotchas
- **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 nightly `cron.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 that `publish-embed-sdk.yml` uses — 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 Catalog` is the only workflow that proves the CDN S3 credentials still work — a green `Publish Embed SDK` proves nothing.** Both read the same `CDN_S3_ACCESS_KEY_ID` / `CDN_S3_SECRET_ACCESS_KEY` / `CDN_S3_BUCKET` / `CDN_S3_ENDPOINT` secrets, but `publish-embed-sdk.yml` guards its upload job on `needs.check.outputs.publish == 'true'`, which is false whenever the version in `packages/ee/embed-sdk/package.json` is 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 with `InvalidAccessKeyId` on three consecutive Mondays while the embed SDK looked healthy. To date a dead key, find the last embed-SDK run whose `publish` job 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, dispatch `sync-model-catalog.yml` — it uploads unconditionally.
@@ -52,7 +69,19 @@ renders and preserves every real price; the cheapest in the set is 0.01.
- **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_URL` points 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_PROVIDER` map or it silently ships with no metadata.** models.dev provider ids do not match ours: `bedrock` → `amazon-bedrock`, `qwen` → `alibaba`, `moonshot` → `moonshotai`, `activepieces` → aliased onto `openrouter` at lookup time. The six OpenAI-compatible vendors were merged before the map was updated and produced exactly this — the run prints `no upstream source: …`, which is the thing to read after adding a provider. `cloudflare-gateway` and `custom` legitimately 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_dispatch` run 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()` in `ai-pricing-service.ts` has three states, and two of them render the same numbers: **absent** (`NoSuchKey`) silently seeds the editor from `DEFAULT_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.json` is. 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.getJson` catches `NoSuchKey` and returns `undefined`, 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 — `list` does *not* catch `NoSuchKey`, 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.json` was deleted on 2026-09-24 to drop a leftover test tier, and Activepieces kept serving the right tiers throughout: the 404 makes `fetchTiers` throw, the failure is logged and backed off, and `current()` keeps serving the last good copy the process fetched; only a process that never fetched one, a fresh boot during the outage, runs the `ACTIVEPIECES_CHAT_TIERS` shipped 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 whenever `current()` 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. Today only `warmUp()` calls it, so that is one line per boot. And the console reads the missing key as **absent**, so the next publish starts again at `version: 1` while the `ai/pricing/history/` objects from the old numbering are still there — the version number is `live.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_*` and `AP_S3_*` are two different buckets on two different providers, and mixing them puts public objects in customer data.** `cdn.activepieces.com` is a **DigitalOcean Spaces** bucket, `activepieces-cdn` in `fra1`, fronted by Cloudflare — a 200 from it carries `x-rgw-object-type` and `x-do-cdn-uuid`, which is how you tell. That is where `ai/model-catalog.json`, `ai/pricing.json` and `sdk/embed/*.js` live, and the credentials are the `CDN_S3_*` GitHub secrets. `AP_S3_BUCKET` is something else entirely: the **Cloudflare R2** file-storage bucket (`ap-files-prod` in 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 a `public-read` `ai/pricing.json` into the customer-data bucket while `cdn.activepieces.com` stayed 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 appends `Bucket` itself and the doubled path returns `NoSuchKey` on every call).
+- **The weekly sync workflow can fail and nobody is told.** `sync-model-catalog.yml` has no alert on failure, and the only signal that it broke is a 404 on the object, which every reader swallows. Its run on 2026-08-31 failed with `InvalidAccessKeyId` — the `CDN_S3_ACCESS_KEY_ID` secret in this repo does not match a live key — so `ai/model-catalog.json` has never actually landed. Check `gh run list --workflow=sync-model-catalog.yml` before believing the CDN is the problem. **That same `CDN_S3_*` credential also publishes the AI tier file `ai/pricing.json` from `ap-analytics`** (decision [000039](../decisions/000041-ai-model-tiers-are-published-to-the-cdn-from-a-second-console.md)), so one dead key silently breaks model metadata *and* the published tiers at once: the console hides model costs (`model-catalog-service.ts` logs '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/ai` sets `allowWrite = platform.plan.aiProvidersEnabled`, and that column defaults to **false** on the `free` plan (migration `1776…AddDefaultToAiProvidersEnabled`), so the connect button is simply absent rather than disabled-with-a-reason. On Cloud the flag is owned by Autumn (`autumn-utils.ts` lists it among the synced features), so there is nothing to configure locally and no `DEV_ENTERPRISE_PLAN` escape hatch on main. For local Cloud testing, flip it directly: `UPDATE platform_plan SET "aiProvidersEnabled" = true`. Then connect a **BYO key**, not the managed `ACTIVEPIECES` provider — per *Provider visibility* above, the managed row is hidden whenever `OPENROUTER_PROVISION_KEY` is unset, which is the normal local state, and a hidden provider makes `getChatProvider()` 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-controller` is the one place to act on it.** The piece POSTs `/v1/ai/execute` with `provider` and `modelId`, the controller builds the `EXECUTE_AI` job 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 over `getAgentConfig`, in `agent-config-rpc`. Two conditions sit under that. **An old bundle only forwards the string from `0.11.0` up** — `AI_PIECE_COST_BILLING_VERSION`, the first version whose `ai-step.ts` POSTs `v1/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-billing` bumps every saved `piece-ai` step below `0.11.0` up to it, which is why a later migration can rewrite what a step stores without touching `pieceVersion` for the runtime. **And resolve on the API, never in the worker**: `ExecuteAiRequest.modelId` is a bare `z.string()` so a tier id passes validation, `getEffectiveProviderAndModel` and `aiUtils.buildWebSearchToolsOrThrow` both read `data.modelId` as a real model, and the `resolveAiProvider` RPC 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`) reads `providerMetadata['openrouter'].usage.cost`, with one fallback that GETs `openrouter.ai/api/v1/generation?id=` and takes `total_cost`. If neither answers, `createBillingInfo` returns `undefined` and 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.ts` shares one branch for `OPENROUTER` and `ACTIVEPIECES`, every tier `modelId` is an OpenRouter id, and `openrouter-api.ts` mints the per-platform key from `OPENROUTER_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`, the `ai-gateway-provider` package), and `@ai-sdk/gateway` appears only as a transitive dep of `ai` that nothing imports. A BYOK user can already reach Vercel's gateway today through `AIProviderName.CUSTOM`, which takes a base URL plus hand-typed model ids.
+- **A tier id that no longer exists resolves two different ways, and only the run source decides which.** `getAgentConfig` branches on `namesItsOwnModel` (true for `AgentRunSource.FLOW_STEP` and `AGENT`): those go through `resolveNamedModelId`, which **throws** `The model "X" is not available on Activepieces AI credits` for an id it cannot find, while every other source goes through `resolveModelIdForProvider` → `resolveTier`, which **silently returns the default tier**. So deleting a published tier moves existing chats onto the default with no error and no notice, and that is genuinely safe only while flow steps and agents still store concrete model ids. The moment a step stores `premium` it takes the throwing branch and every run of that flow fails, because the candidate list is model ids and never contains a tier id. Whoever lands the tier-id switch has to decide what a removed tier means before the console keeps telling admins that removing one is safe.
+- **The console's Publish writes the live key directly; there is no draft, no staging and no filter.** `ai-pricing-service.ts` in `ap-analytics` writes `LIVE_PRICING_KEY` on Publish, and its "add tier" row seeds `id: tier-N`, `label: New tier`, so a half-finished experiment is one click from every server's cached tier list, with only the CDN `max-age=300` plus the 15-minute in-process TTL in between. Test against a local file with `AP_MODEL_TIERS_URL` (add the host to `AP_SSRF_ALLOW_LIST` for loopback), never by publishing.
+- **The AI piece's managed dropdown only ever offers tier models, so every stored managed model id came from a tier pick.** `props.ts` (`packages/pieces/community/ai/src/lib/common/props.ts`) builds its options from `ACTIVEPIECES_CHAT_TIERS`, the constant compiled into the release, in two places: `managedModelLabel` supplies the label, and the same lookup is the `.filter` that decides which models are offered at all. There is no way to pin a model deliberately through it. Two consequences. A re-pointed tier is invisible to the AI piece in both directions: a saved step keeps its concrete model id, and a new step cannot pick the new model because it matches no bundled tier. And any migration from stored model ids to tier ids has a trivially complete mapping, since each stored id is one of the three bundled tier model ids of the release it was saved on. Until the dropdown emits tier ids, the AI piece only ever follows the release.
+- **`AIProviderModel` is declared twice, and a field added to one half is stripped on the wire.** There is one in `core/piece-types` (what pieces import, since they cannot import `@activepieces/shared`) and one in `core/shared` (what the server and the response schema use). They are not re-exports of each other — today the shared copy carries `metadata` and 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 as `undefined`. 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.listModels` tags a model `IMAGE` when its `architecture.output_modalities` says so — `ACTIVEPIECES` is deliberately absent from `NO_IMAGE_GENERATION_PROVIDERS`, and `google/gemini-2.5-flash-image` and friends are real managed models. But `ACTIVEPIECES_CHAT_TIERS` is 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, leaving `aiProps({ modelType: 'image' })` with an empty dropdown and no error. Gate that filter on `modelType === 'text'`.
+- **`premium` pairs `modelId: anthropic/claude-opus-4.8` with `nativeModelId: claude-opus-4-7` on 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's `defaults.ts` carries the same pair. Do not "fix" either copy.
- **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))` and `z.optional(x)` instead of `.min(1)` / `.optional()`) is what `@activepieces/pieces-framework` re-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/utils` is invisible to another package's tests until you build it.** Sibling packages resolve `@activepieces/core-utils` through its `main` (`dist/src/index.js`), so vitest in `core/ai-providers` keeps parsing against the stale build and a new optional field reads back as dropped. `cd packages/core/utils && npm run build` first. The API dev server is the opposite: `serve` runs under tsx with the tsconfig path alias, so it reads `src` directly — but it only watches `packages/core/shared/src/**`, not `core/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: `dist` is gitignored, so after `git checkout` it 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. Rebuild `core/utils` after every branch switch before trusting a run.
@@ -84,7 +113,7 @@ renders and preserves every real price; the cheapest in the set is 0.01.
- **The OpenAI-compatible provider can speak the Responses API, and `@ai-sdk/openai-compatible` is not how you get there.** That SDK exposes only `chatModel` (`/chat/completions`) and `completionModel` — no responses model in any version. The route is `@ai-sdk/openai`, which accepts a custom `baseURL` + `headers` and exposes `.responses()`; the Cloudflare gateway's openai branch already did this before the `apiStyle: 'chat' | 'responses'` config field existed. Header precedence is the subtlety: the SDK builds `{ Authorization: Bearer <apiKey>, ...options.headers }`, so a caller header wins on `Authorization` (the Bedrock case, where the key *is* the bearer token) but a custom `apiKeyHeader` such as `x-api-key` leaves the SDK's default `Authorization` riding along. `withUserAgentSuffix` drops `undefined` values, but `OpenAIProviderSettings.headers` is typed `Record<string, string>`, so the way to strip it is the header-stripping `fetch` the 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 when `apiKeyHeader` is not itself Authorization, compared **case-insensitively**: HTTP header names are, and an admin can type `authorization`. 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) and `bedrock-mantle.{region}.api.aws/v1` both serve Chat Completions *and* Responses, both authenticate with a Bedrock API key as `Authorization: Bearer`, and both take an unmodified OpenAI SDK. Mantle alone adds server-side tools and web search, `background=true` async 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 `GOOGLE` provider is the Gemini Developer API (`generativelanguage.googleapis.com`, static API key); `VERTEX` is 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: `buildOpenAICompatibleHeaders` injects one static header, which is why the workaround used to be a LiteLLM proxy. `@ai-sdk/google-vertex` does 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 a `publishers/google` listing 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-vertex` ships separate `/anthropic`, `/maas` and `/xai` entry points for exactly that reason, so one `createVertex(...)` 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.ts` routes ids containing `claude` to `createVertexAnthropic`; `vertexClientFor` picks 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* the `claude` one, 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-pro` is 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 the `includes('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 whose `schemas` are the authoritative request/response types. `publishers.models.list` returns `{ publisherModels: PublisherModel[], nextPageToken }`, and `PublisherModel` is `{ name: 'publishers/google/models/<id>', versionId, versionState (STABLE|UNSTABLE), launchStage (GA|PUBLIC_PREVIEW|PRIVATE_PREVIEW|EXPERIMENTAL), openSourceCategory, supportedActions, predictSchemata, frameworks, parent }`. **There is no `displayName` on it** — the one in `google-vertexai`'s piece comes from `@google/genai`'s `Model` type, which is a different shape, so copying that code gives every row a blank label with nothing failing. `displayName` exists only on the nested `parent`, which is the base model a tuned model derives from. The decisive fact is in that same doc: `publishers.models.list` takes `parent` matching `^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. `VERTEX` stays in `MANUAL_MODEL_PROVIDERS` alongside `CUSTOM` and `CLOUDFLARE_GATEWAY`, which fits: Vertex model availability really is per-project. Reach for the discovery doc before a live probe on any `*.googleapis.com` integration; 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. The `x-goog-user-project` header is not optional when probing with a personal login: without it aiplatform answers `403 SERVICE_DISABLED` naming `consumer: 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 own `project_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, and `createVertex(...)` also exposes `imageModel`, `video`, `speech`, `transcription` and `textEmbeddingModel` — none of which we wire today. Imagen is wired (`createVertex(...).imageModel()`, with a `VERTEX` case in the piece's image switch, so `VERTEX` is no longer in `NO_IMAGE_GENERATION_PROVIDERS`); video, speech, transcription and embeddings are not. Embeddings still have no `DEFAULT_EMBEDDING_MODELS` entry, so that path 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-helpers.ts`) now prefers the resolved key's own configured text models when its config carries a `models` array — that is the `MANUAL_MODEL_PROVIDERS` case (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 returning `string[] | undefined` treated "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 static `ALLOWED_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 to `claude-sonnet-4-6` and handed it to the Gemini client. That map is `Partial<`, so omitting a chat-capable provider compiles cleanly and fails only at the endpoint. **The key's own `modelScope`/`modelIds` allow-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. `GetProviderConfigResponse` carries 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-handlers` resolves the chat turn's model *and* its fast model, and `chat-personalization-service` resolves both for research — those four must be given the resolved row's `config`, `modelScope` and `modelIds`, or the key's constraints are bypassed on exactly the paths a user takes. `resolveTierModel` inside `agent-helpers` is the fifth. `agent-service` and `agent-draft-ai` also call it but hold only a provider name and set a stored default on a draft, so they are correctly left thin. Adding a parameter here means grepping `resolveModelIdForProvider|resolveFastModelId` across `packages/server`, not editing the call site in front of you — threading only `resolveTierModel` looks complete, passes every test, and still leaves the real chat path unconstrained. 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 — passing `selectedModel` straight through makes `resolveFastModelId` return the first curated model instead of the fast tier's.
+- **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 into `agentHelpers`) now prefers the resolved key's own configured text models when its config carries a `models` array — that is the `MANUAL_MODEL_PROVIDERS` case (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 returning `string[] | undefined` treated "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 static `ALLOWED_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 to `claude-sonnet-4-6` and handed it to the Gemini client. That map is `Partial<`, so omitting a chat-capable provider compiles cleanly and fails only at the endpoint. **The key's own `modelScope`/`modelIds` allow-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. `GetProviderConfigResponse` carries 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-handlers` resolves the chat turn's model *and* its fast model, and `chat-personalization-service` resolves both for research — those four must be given the resolved row's `config`, `modelScope` and `modelIds`, or the key's constraints are bypassed on exactly the paths a user takes. `resolveTierModel` inside `agent-helpers` is the fifth. `agent-service` also calls it but holds only a provider name and sets a stored default on a draft, so it is correctly left thin (`agent-draft-ai` did too, until #15676 deleted it). Adding a parameter here means grepping `resolveModelIdForProvider|resolveFastModelId` across `packages/server`, not editing the call site in front of you — threading only `resolveTierModel` looks complete, passes every test, and still leaves the real chat path unconstrained. 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 — passing `selectedModel` straight through makes `resolveFastModelId` return 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.validateProviderCredentials` gates the upstream message behind `includeHttpErrorInMessage`, which is `provider === CLOUDFLARE_GATEWAY` and nothing else, so everyone else gets a bare `Failed to validate credentials for <name>`. The cause is not lost — it is logged one line earlier (`log.error({ error }, '[aiProviderService#validateProviderCredentials] ...')`) and passed as the `httpErrorResponse` error param — but **web never renders `httpErrorResponse`**, so the only way to diagnose a rejected key is the server log. Grep the log for `validateProviderCredentials` before 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 answers `GET /v1/models` with `403 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 uses `400 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.logoUrl` in `packages/web/src/features/agents/ai-providers.ts` is a plain string rendered into an `<img src>`, and every provider points at `https://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 with `curl -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.png` did), so start the upload request only for the genuinely missing ones. A Vite asset import also satisfies `logoUrl` (see `GoogleIcon` in `platform/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.
- **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 a `ProviderModelConfig` of `{ modelId, modelName, modelType }`, but since #14825 the UI keeps only `string[]`: `ManualModelList` is a chip list of ids, and `config-detail.tsx` rebuilds the objects on save with `?? { modelId, modelName: modelId, modelType: TEXT }`. The old `universal-pieces/model-form-popover.tsx` had 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.validateConnection` pings **only text models** with a `/chat/completions` request, so one image model added through the UI is validated as chat, fails, and takes the whole key down with `These models have issues: ...` — the admin cannot save a key that has an image model on it at all. Anything reading `modelType` downstream (the agent text-model filter, `ap-list-ai-models`, the builder's image pickers) is wrong the same way. Fixed by holding `ProviderModelConfig[]` in the draft rather than `string[]` (no migration; stored rows always had the right shape), so the standing rule is that **a manual-models UI must carry `modelType` all 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 typed `TEXT`; the type badge on each chip flips one in place, which is why it is editable rather than display-only.
diff --git a/brain/knowledge/ai-intelligence/index.md b/brain/knowledge/ai-intelligence/index.md
index 88d81a4e6e8..1fdb7365f62 100644
--- a/brain/knowledge/ai-intelligence/index.md
+++ b/brain/knowledge/ai-intelligence/index.md
@@ -13,9 +13,18 @@ A configured LLM backend (OpenAI, Anthropic, Google, Azure, OpenRouter, Cloudfla
The metered currency for AI usage — one credit is `AP_AI_CREDIT_USD_VALUE` of model spend, $0.0005 by default — backed by per-key OpenRouter limits. A quota, not a wallet. A managed call is billed on the dollar cost the provider reports; a call on a customer's own key is billed one flat credit. See [decision 000037](../decisions/000037-ai-is-billed-on-what-the-call-cost-observed-at-the-worker.md).
- *Avoid:* "tokens" for the billing unit; tokens are the model's unit, credits are ours. *Avoid:* "credit weight" — the per-model weight table is gone.
+### 🎚️ Model Tier
+A named slot, Fast, Expert or Heavy, that a customer picks instead of a model, so we can move it to a newer model without a deploy. It carries `id`, `label`, `modelId`, an optional `nativeModelId` for a customer on their own key, and a `thinkingBudget`. Tiers are published to the CDN by the console (decision [000041](../decisions/000041-ai-model-tiers-are-published-to-the-cdn-from-a-second-console.md)) in two lists and fall back to `ACTIVEPIECES_CHAT_TIERS` in the release. Tier ids are `fast` / `smart` / `premium`; only `fast` matches its label (`smart` is Expert, `premium` is Heavy), so match on `id`, never the label. A tier id never contains `/`; a managed model id always does.
+- **Flow tiers** — the `tiers` list; what FLOW_STEP and AGENT resolve against, the surfaces that name their own model. **Chat tiers** — the `chatTiers` list; what CHAT and AGENT_BUILDER resolve against. The chat list is optional and falls back to the flow list. In code the pair is `ModelTierSurface = 'chat' | 'flow'`.
+- *Avoid:* "chat tier" for a model tier in general; say "model tier", and "chat tiers" only for the chat list. The other real axis is text vs image (`ACTIVEPIECES_IMAGE_TIERS`).
+
### 🤖 Agent
A flow step that runs an autonomous LLM loop rather than a single call. Its **AgentTool**s are Piece, Flow, MCP, or Knowledge Base handles.
+### 🚪 Run source
+The door an agent turn came through. `AgentRunSource` is CHAT (the assistant chat, an agent turn with no agent row), AGENT (chatting with a saved agent), AGENT_BUILDER (the chat that builds an agent) and FLOW_STEP (the `run_agent` action). All four create an `agent_conversation` row and run the same `EXECUTE_AGENT_RUN` worker job; the source decides the tool set, the system prompt and which tier list the model resolves against. See the four-doors table on the AI Agents page.
+- *Avoid:* "surface" for the door itself; surface is the two-way `chat | flow` split the tier lists use, and two doors map onto each.
+
### ⚡ Direct AI step
A flow step that makes one model call and returns: Ask AI, Summarize Text, Classify Text, Extract Structured Data, Generate Image. The counterpart to an **Agent**, which loops — and the distinction decides how each reaches a model, see [decision 000035](../decisions/000035-direct-ai-steps-reuse-the-agents-suspend-and-resume-path.md).
- *Avoid:* "simple AI action" and "AI action" — both name the piece rather than the behaviour, and would wrongly include the Agent step, which also lives in the AI piece.
diff --git a/brain/knowledge/decisions/000041-ai-model-tiers-are-published-to-the-cdn-from-a-second-console.md b/brain/knowledge/decisions/000041-ai-model-tiers-are-published-to-the-cdn-from-a-second-console.md
new file mode 100644
index 00000000000..21210624a7e
--- /dev/null
+++ b/brain/knowledge/decisions/000041-ai-model-tiers-are-published-to-the-cdn-from-a-second-console.md
@@ -0,0 +1,85 @@
+---
+icon: 🪙
+status: accepted
+---
+
+# AI model tiers are published to the CDN from a second console
+
+## Decision
+
+The chat model tiers — `id`, `label`, `modelId`, `nativeModelId`, `thinkingBudget` — and
+`defaultTierId` move out of the code and into `cdn.activepieces.com/ai/pricing.json`. A **new repo**, `activepieces/ap-analytics`, is where
+marketing edits them and presses Publish. Activepieces fetches that file (15-minute TTL), keeps the last
+good copy, and falls back to the constants shipped with the release. The existing billing console
+is not touched.
+
+There is **no database table for the tiers**. The CDN file is the source of truth. Every publish
+also writes `ai/pricing/history/<timestamp>-<email>.json`, which gives history and one-click undo
+with no table.
+
+## Context
+
+Every tier was a constant in the monorepo, so moving Expert to a newer model meant a code change,
+a release and a self-host upgrade. Marketing needed to do it themselves. Two problems fell out of that:
+where the UI lives, and how the values travel.
+
+The billing console already holds license keys, Autumn customers and money. Its own rule is
+"Architecture A+: one codebase, separate Supabase project per sensitive module" — but that
+separates only the **database**. It does not stop a config feature from breaking a deploy that
+also serves billing, and it does not stop anyone (or any agent) editing files next to that code.
+
+## Why
+
+A second repo separates the code and the deploy, not just the data. Config work can move fast
+without touching the repo that holds the master billing key.
+
+Publishing to the CDN rather than serving a live console endpoint keeps **billing correctness off
+the console's uptime**. The fetch/cache/backoff/stale-fallback code already existed and was proven
+(`model-catalog.ts`), so the reader is a copy of a working thing rather than new machinery.
+Rejected: AP calling a console API on every read, which would make a config tool an availability
+dependency of charging customers.
+
+No table because the CDN object already gives durable storage, and archive copies give history for
+one extra upload call. Rejected: a versioned Postgres table, which is a migration, a schema and a
+second copy of the truth for no gain.
+
+The cost is propagation delay (about 20 minutes, from `max-age=300` plus a 15-minute in-process TTL) and
+that publishing needs CDN write credentials in the new repo. The current key can write anything in
+the bucket; a key scoped to `ai/pricing*` is the follow-up.
+
+## Consequences
+
+- **The pricing schema now lives in two repos** and they must match. `packages/shared/src/lib/ai-pricing/`
+ in ap-analytics, `packages/server/utils/src/model-tier-catalog.ts` here. Change one without the
+ other and Activepieces rejects the file and silently keeps serving the old tiers. The reader
+ ignores keys it does not declare, which is what kept the console publishable while it still sent
+ the credit fields; ap-analytics dropped those on 2026-09-20 and added `nativeModelId`, so the two
+ schemas name the same five tier fields again.
+- A tier change is no longer visible in `git log` of this repo. The audit trail is the CDN history
+ prefix.
+- The reader **fails closed**: bad schema, no tiers, or a missing default tier all fall back to the
+ last good file, then to the release's own `ACTIVEPIECES_CHAT_TIERS`. CE and self-hosted keep
+ working with zero setup.
+- Publishing is blocked whenever the live file cannot be read, so a CDN outage can never overwrite
+ tiers nobody can see.
+- **This started out as a price file and is not one any more.** It originally carried
+ `MANAGED_MODEL_WEIGHTS`, a per-tier `creditWeight` and `unpricedModelCreditWeight`. Main deleted
+ every weight table in [#15494](https://github.com/activepieces/activepieces/pull/15494) and now
+ bills managed AI on the dollar cost the provider reports per call, so there is no fixed price left
+ to publish. Only the tier table survived. The object is still called `ai/pricing.json` because it
+ is already live and the console writes there; the name is now wrong, and renaming it needs both
+ repos plus the live object to move together. The console page, its nav entry and its docs were
+ renamed to **AI Tiers** instead, because an editor that still showed a credits box let an admin
+ change a number, press Publish and believe they had changed billing.
+- **The two guards on publishing are not equally strict, which is easy to misread.** Reading the live
+ `pricing.json` before a write fails *closed* (above). The separate check that every priced model id
+ exists in `ai/model-catalog.json` fails *open*: when the catalog cannot be loaded,
+ `ai-pricing-service.ts` logs 'The model catalog is unavailable, so model ids were not checked before
+ publishing' and publishes anyway. So a typo in a tier's `modelId` can reach the CDN, and every chat
+ turn and agent run on that tier then asks the provider for a model that does not exist.
+- Config features from now on go in `ap-analytics`, not the billing console.
+- **The repo is named `ap-analytics` on GitHub, but calls itself "config console" inside** — README,
+ `CLAUDE.md` and the package names all say config-console. It was created as `config-console` and
+ renamed on 2026-09-02. A clone made before the rename pushes into a 404; fix it with
+ `git remote set-url origin [email protected]:activepieces/ap-analytics.git`.
+- **Internal tools run on DigitalOcean, but not all the same way.** `activepieces/discover` uses a **droplet** driven by Actions over SSH (`.github/workflows/deploy.yml` — build, rsync, `pm2 reload`), with nginx and certbot in front. `ap-analytics` uses **App Platform** instead: DO builds the Dockerfile, redeploys on push by itself, and issues TLS, so there is no server to log into and the repo carries no deploy workflow at all. Neither repo says which it is, so check the DO dashboard before assuming. Runbook: `DEPLOYMENT.md` in ap-analytics.
diff --git a/brain/knowledge/engineering/ci-pr-review-hygiene.md b/brain/knowledge/engineering/ci-pr-review-hygiene.md
index e3b0f4e279a..b3c72cb7ff6 100644
--- a/brain/knowledge/engineering/ci-pr-review-hygiene.md
+++ b/brain/knowledge/engineering/ci-pr-review-hygiene.md
@@ -69,7 +69,8 @@ Enforcement is the **`Codeowners review` repository ruleset** (active on the def
- **Reopening a bot-closed external PR is futile until a core member adds `keep-open` first.** `close-external-prs.yml` triggers on `pull_request_target` `[opened, reopened]`, so every reopen re-runs the same comment-then-close step; its `if` exempts OWNER/MEMBER/COLLABORATOR, bots, and the `keep-open` label, and nothing else. A docs PR from an outside contributor ([#15031](https://github.com/activepieces/activepieces/pull/15031)) was reopened 13 times over two days and closed 13 times within seconds of each, until a member labelled it `keep-open` and reopened it once. The same job also runs a nightly `actions/stale` pass that closes any PR idle 60 days. The lasting fix for a change worth keeping is to re-open it from a branch owned by someone with write access — author association, not the diff, is what the gate reads.
- **`license/cla` keys off the commit author email, so re-opening someone else's branch under your own name does not clear it.** CLA-assistant walks every commit in the PR rather than the PR author, and an author email that matches no GitHub account can never be matched to a signature — the 47 commits carried over onto [#15092](https://github.com/activepieces/activepieces/pull/15092) were authored as `[email protected]`, a local hostname, so the check sat at `not_signed` on a PR opened by a member. It is not in the `main` ruleset's required-checks list, but it is red on the page and a reviewer reads that as unmergeable. Either the original author signs through the PR link, or the commits get re-authored to an email tied to their GitHub account before you open it.
- **A branch that predates the `brain/` → `brain/knowledge/` move cannot edit a brain page in place — GitHub will call the PR conflicting even when `git merge` is clean locally.** Git follows the rename and merges the modification into the new path; GitHub's mergeability check does not, so it reports `modify/delete` on the old path and the PR goes `dirty`. Local `git merge-tree --write-tree` exits 0 and hides the problem; reproduce what GitHub sees with `git merge -X no-renames origin/main`. Fix: merge `origin/main` into the branch first, which lands the edit at the new path, then push.
-- **`breaking-change-check` couples the docs entry to the label in BOTH directions, so back-documenting an already-shipped change drags the label onto a docs-only PR.** R3 in `tools/scripts/breaking-change-check.ts` fails a PR that adds a `####` entry to `docs/install/reference/breaking-changes.mdx` without `⛓️‍💥 breaking-change`, exactly as it fails the label without an entry — and the template answer has to agree too, so "yes" must be ticked on a PR that changes no code. It reads the *added lines of that one file* from `git diff origin/<base>...HEAD`, and `hasBreakingEntry` wants a `####` heading **plus** a non-heading body line, so a heading alone, a `---`, or a version bump does not count. Two consequences: the label then collides with `skip-changelog` in release-drafter (pick one deliberately — the feature's own PR usually already carried the changelog entry), and an entry appended to a *released* section still trips it, since the check never looks at which heading the lines landed under.
+- **Merging `main` into your branch makes Greptile review `main`'s shipped code as yours, and the score drops for files you never touched.** It appears to review the commits in the PR's range rather than the diff against the base, so a merge commit drags the commits it brought in along with it — [#15550](https://github.com/activepieces/activepieces/pull/15550) went 4/5 → 3/5 on a finding in `agent-conversation-service.ts` and `agent-run-controller.ts`, both arriving from #15548 in a merge done minutes earlier, neither in the PR's own diff. The check is one command: `git diff --name-only origin/main HEAD` — if a "Files Needing Attention" entry is not in that list, it is not this PR's. (Three-dot `origin/main...HEAD` works too; after merging `main` the merge base *is* `main`, so the two agree.) Do not stop at "not mine", though: that finding was real, a lookup by id with no `projectId` filter, and it is live on `main` where nobody is reviewing it any more — report it against the owning PR rather than letting the misattribution bury it. Rebasing instead of merging avoids the whole effect, but this repo merges, so expect it after every catch-up.
+- **`breaking-change-check` couples the docs entry to the label in BOTH directions, so back-documenting an already-shipped change drags the label onto a docs-only PR.** R3 in `tools/scripts/breaking-change-check.ts` fails a PR that adds a `####` entry to `docs/install/reference/breaking-changes.mdx` without `⛓️‍💥 breaking-change`, exactly as it fails the label without an entry — and the template answer has to agree too, so "yes" must be ticked on a PR that changes no code. It reads the *added lines of that one file* from `git diff origin/<base>...HEAD`, and `hasBreakingEntry` wants a `####` heading **plus** a non-heading body line, so a heading alone, a `---`, or a version bump does not count. Two consequences: the label then collides with `skip-changelog` in release-drafter (pick one deliberately — the feature's own PR usually already carried the changelog entry), and an entry appended to a *released* section still trips it, since the check never looks at which heading the lines landed under. **When the check fails, removing the label is sometimes the right fix, not writing an entry.** A long-lived branch can stop being breaking underneath you — merging `main` can delete the very thing that was breaking, and then the label and the template answer are both stale while the code is fine. Re-read what the branch still does against the template's own list before reaching for `breaking-changes.mdx`. Handy either way: the job re-runs on a **label change**, so flipping the label clears it with no empty commit and no push.
- **A release cut empties `## Unreleased` into a version section, so a long-lived branch's entry conflicts in a way that is wrong to resolve by hand.** The entries do not move to the bottom of the file — the whole Unreleased block is relabelled as the new version and a fresh Unreleased is opened above it. A branch that added its entry weeks ago then conflicts against a section that has been relocated wholesale, and git presents it as "your entire block versus one stray line", which invites resolving the hunk in place. Doing that leaves the entry sitting inside an already-released section, where it is both wrong for readers and invisible to `breaking-change-check` (see the bullet above: the check never looks at which heading the added lines landed under, so CI stays green). Take main's copy of the file whole and re-insert the entry at the end of the *current* Unreleased section instead, then check that the entries you unioned on an earlier merge each appear exactly once — the previous resolution's placement is usually now a duplicate. Seen on GIT-1764 / #14899, which conflicted twice in one day for this reason.
- **Nothing rolls `## Unreleased` over at release time, and the docs site is unversioned — so a breaking-changes entry has to name its own version.** No workflow or script writes to `docs/install/reference/breaking-changes.mdx` (`breaking-change-check.ts` only reads it), and `git log -S"## 0.88"` on the file comes back empty: the heading has not moved since 0.87.0, so entries for work that shipped months ago still sit under "Unreleased" (PM2 removal in 0.88.2, cache pre-warm gate and workspace naming in 0.89.0, …). `docs/docs.json` has no versioning either, so there is one live page for every self-hoster whatever version they run, published on merge rather than on release — the version heading is the *only* thing telling a reader whether a change is already in their build. So before adding an entry, run `git tag --contains <commit>` on the change it describes and file it under the release that actually shipped it; only genuinely unshipped work belongs under "Unreleased". What points self-hosters at the page in the first place is `release-drafter.yml`, which appends a "review the Breaking Changes page" line to every release body and groups `⛓️‍💥 breaking-change` PRs under their own heading — which also means a docs-only PR back-documenting an old change shows up in the *next* release's breaking-change list.
- **Greptile enforces the file-order rule on *private* constants too, which CLAUDE.md only states for exported ones.** CLAUDE.md says "Exported types and constants must be placed at the end of the file" and gives the order as imports → exports → helpers → types; Greptile reads that as covering module-private constants as well, and flags a `const` sitting above the file's exported symbol (P2 on [#15226](https://github.com/activepieces/activepieces/pull/15226), for two constants only read inside the service they sat above). It has that as a stored custom-context memory, so it will keep raising it. Put private constants in the helpers section below the export — hoisting is a non-issue when they are only read at call time.
diff --git a/brain/knowledge/engineering/engineering-handbook-playbooks.md b/brain/knowledge/engineering/engineering-handbook-playbooks.md
index 649ee54a630..e6add8a47e7 100644
--- a/brain/knowledge/engineering/engineering-handbook-playbooks.md
+++ b/brain/knowledge/engineering/engineering-handbook-playbooks.md
@@ -21,6 +21,7 @@ Run EE, building for self-hosting, setup BetterStack, releases, canary deploymen
Postmortems (Redis/queue overload, infra upgrade — March 2026) and product interface-design notes.
## Gotchas
+- **Put a scratch worktree *inside* the repo root, or it cannot lint or typecheck at all.** Node resolves `node_modules` by walking up the directory tree, so a worktree at `/tmp/...` finds nothing and eslint dies on `couldn't find the plugin "@typescript-eslint/eslint-plugin"` before it reads a single rule — no install, no symlink, no checks. The same worktree created at `.claude/worktrees/<name>` walks up to the repo root's `node_modules` and runs lint, `tsc` and vitest with zero setup. This is cheaper than both workarounds in the next bullet and has none of the cross-branch skew, because the resolved packages belong to the same checkout. It matters most during a long conflict resolution: files you edit while resolving are easy to treat as "already reviewed" and never check again, and in an unusable worktree you *cannot* check them. A merge resolved in `/tmp` shipped a `sort-imports` error and a `TS2783` to CI this way — both in files touched only during conflict resolution, both caught by the first `turbo run lint` / `turbo run typecheck` that could actually run. After a merge, run the task CI runs (`turbo run lint --filter=<pkg>`), not a list of the files you remember editing.
- **Running EE locally (outside the dev container) to preview a chat/agents-gated view hits four macOS-specific walls the [Run EE](https://www.activepieces.com/docs/handbook/engineering/playbooks/run-ee) playbook doesn't cover.** (1) The default dev DB, PGlite (`.env.dev`'s `AP_DB_TYPE=PGLITE`), hard-refuses `AP_EDITION=ee`/`cloud` with `Error: Edition ee not supported in pglite mode in dev environment` — point at a real local Postgres instead (`AP_DB_TYPE=POSTGRES` + a throwaway DB via `createdb`). (2) In a fresh git worktree, symlinking `node_modules` from another worktree/checkout works for lint/typecheck but not for actually running the server: workspace packages resolve through the symlink to whatever commit *that* checkout is on, so a genuine cross-branch source/type skew appears (e.g. `AIProviderName.VERTEX does not exist`) purely from the mismatch — do a real `bun install` scoped to the worktree instead. (3) `bun install` aborts the *entire* install (not just its own package) if `isolated-vm`'s native build fails, which it does on Darwin 25 (`node-gyp` / `undici` `webidl.util.markAsUncloneable is not a function`) — even though `isolated-vm` is only needed by the engine/worker sandbox, not by `api`+`web`. Fix: `bun install --ignore-scripts`, then `cd` into `node_modules/.bun/sqlite3@*/node_modules/sqlite3` and run `npx prebuild-install -r napi` directly to fetch its prebuilt native binding (something in the queue/api dependency tree requires it to *load* even when the configured DB isn't sqlite). (4) The repo requires Node 22.15+/24 (`bootstrap.ts` uses `zlib.zstdDecompress`, added in Node 22.15); a system default of Node 20 (common via `nvm`) crashes API boot with `ERR_INVALID_ARG_TYPE` in `file-compressor.ts` — put a `nvm`-installed v24 first on `PATH` before starting `serve`. Once booted: `AP_EDITION=ee` alone (no license key) is enough to preview chat/agents, since the unlicensed `AUTUMN_FREE_PLAN` already sets `chatEnabled`/`agentsEnabled: true` — but that plan's `aiProvidersEnabled: false` hides the "Connect" button on every provider card, so there is no UI path to satisfy chat's "Set up an AI provider" gate; insert a throwaway row into `ai_provider` directly via SQL (`enabledForChat: true`, `config: '{}'`, any `auth` JSON — it's only decrypted when a message is actually sent) to get past it for pure layout/UI verification.
- **`DISCORD_ON_CALL_WEBHOOK` is the single repo secret behind every on-call Discord notification** — cloud production deploys (`continuous-delivery-cloud.yml`), self-hosted releases (`release-self-hosted.yml`), and release-pieces failure alerts all post through it. Rotating it repoints all of them at once; there is no per-workflow webhook. Self-hosted release notifications skip `-rc` tags unless `publish_rc_release` is set, mirroring the release-drafter condition so the message never links a release page that doesn't exist.
- **Docs media lives on the CDN, never in the repo — and videos and images sit on two different paths.** A video embeds as `<video src="https://cdn.activepieces.com/videos/docs/<Exact-File-Name>.mp4" controls />`, an image as `![Alt](https://cdn.activepieces.com/assets/<exact-file-name>.png)`. Videos are namespaced under `videos/docs/`; images are **flat** under `assets/` with no `docs/` segment, so don't infer one path from the other — check the URL you actually mean. Both mirror the filename verbatim, so an upload is fetchable with no config change. Committing the binary instead bloats every clone forever (`docs/videos/` reached 63 MB and `docs/images/` 1.6 MB before both were removed in Sept 2026) since git history keeps the blob even after a delete. Curl each URL for a 200 before deleting a local copy: `docs/` also carries stale `.mdx` references to images that never existed in git history at all, and rewriting one of those to a CDN URL turns a visibly-missing asset into a confident 404.
diff --git a/brain/knowledge/engineering/server-module-anatomy.md b/brain/knowledge/engineering/server-module-anatomy.md
index 47bc8b45e58..558bb3f8a6b 100644
--- a/brain/knowledge/engineering/server-module-anatomy.md
+++ b/brain/knowledge/engineering/server-module-anatomy.md
@@ -160,6 +160,8 @@ Verify with `npm run lint-dev` and `npm run test-api`.
- **Reverting a merged migration PR needs a hand-resolved conflict, and it does not unrun the migration.** GitHub's revert button fails ("couldn't be reverted automatically") as soon as another migration has been registered since yours: both the import block and the `getMigrations()` array put the new entry on the line next to the old one, so both hunks conflict. This is the one case where the usual union resolution is wrong — drop yours, keep the later one. The slot then becomes a hole in the sequence, which TypeORM does not mind, and the number stays safely reusable because migrations are matched by class name. The data is the real question: TypeORM records the migration as run and never revisits it, so the revert leaves every database that already executed `up()` in the new state, and deleting the class removes the only `down()`, putting it out of reach of `rollback-migrations.ts` too — copy that SQL out before you delete the file. To find out who has run it: `git tag --contains <sha>` empty means no release has it, `git merge-base --is-ancestor <sha> release-candidate` failing means cloud production has not, and staging has it either way, because `continuous-delivery-stg.yml` deploys every push to `main` (GIT-1778 / #14982, reverted 2026-09-16).
- **A new `AppSystemProp` needs three edits, not one.** Add the enum entry in `system-props.ts`, a default in `systemPropDefaultValues` (`system.ts`), *and* a validator in `systemPropValidators` (`system-validator.ts`). Miss the validator and `validateEnvPropsOnStartup` throws `systemPropValidators[prop] is not a function` at boot — every API test fails on setup, not just the new one. Document the var in `docs/install/reference/environment-variables.mdx` too.
- **`permission: undefined` on `securityAccess.project(...)` silently allows any project member.** The argument is required in practice even though the type tolerates omitting it.
+- **Anything that does network I/O inside a module's `setup()` adds its own timeout to boot.** `app.ts` awaits every `setup()` and every `register()` in one sequential chain before the server listens, so a single `await someClient.load()` in a `setup()` means a slow or unreachable host delays startup by that client's full timeout — on every boot, for every self-hoster, including the ones with no outbound internet who will never get a useful answer. An unbounded `await` of the model-tier warm-up in `aiProviderService.setup()` put up to 10 seconds on the boot path this way; `modelTierCatalog.warmUp()` now races a 2 s timer for exactly that reason. The repo already has the right idiom a few lines above, and it is worth copying rather than reinventing: `rejectedPromiseHandler(toolSearchReindexJob(app.log).backfillIfNeeded(), app.log)` fires the work off and lets boot continue, with a comment saying it must never block or fail boot. If you genuinely need the value before the first request, give that one call its own short timeout instead of inheriting the client's.
+- **`security` goes under `config`, never under `schema`, and putting it in the wrong half fails silently.** Fastify reads the security config off `config`; a `security` key inside `schema` is just an unknown property on the schema object, so nothing validates it, nothing warns, and the route ships with no security config at all. It reads as correct at a glance because the two keys sit next to each other in the same literal and every route in the file has both. Caught on `GET /v1/ai-providers/tiers` before merge only because the diff was being read line by line. When you add a route, compare its literal against the one above it: `config: { security }` then `schema: { body, response }`, in that order.
- **Every query filters by `projectId` or `platformId`.** For connections with multi-project access, use `ArrayContains([projectId])` on the `projectIds` array column.
- **A mutation test against a `packages/core/*` package proves nothing until you rebuild its dist.** The api package resolves `@activepieces/core-utils` and friends through `node_modules` to `dist/`, not through the tsconfig path to `src/`, so breaking the source and re-running an api test reports a pass while the test is still executing the old build. Measured: removing the connection-template unwrap from `core-utils/src` left `agent-tool-pinning.test.ts` fully green, and the same mutation failed it once `turbo run build --filter=@activepieces/core-utils` had run. Web tests do not share the trap — vitest aliases the core packages to `src` in `packages/web/vitest.config.ts` — so a web suite catching a core mutation while the api suite ignores it is the signature of a stale dist rather than of missing coverage. Same cause as the phantom "has no exported member" errors after merging a branch that adds a core export.
- **`npx vitest` must be run from `packages/server/api`, never the repo root.** The config's `setupFiles` is what loads `.env.tests`, and from the root that setup never runs, so every suite dies in `beforeAll` with `SYSTEM_PROP_NOT_DEFINED: AP_POSTGRES_DATABASE` (thrown from `createPostgresDataSource`) and vitest reports the file as a failed *suite* with all its tests skipped. It reads exactly like a real breakage in whatever you just changed — the tell is that the stack bottoms out in `test-setup.ts`/`database-connection.ts` and never reaches your code, and that the run's stdout is missing the `Configuring vitest …/.env.tests` line a healthy run prints first. `npm run test-api` sets the cwd for you; a hand-written `npx vitest run test/…` does not.
diff --git a/brain/knowledge/flows-execution/flows.md b/brain/knowledge/flows-execution/flows.md
index 22020f07470..42f41642aba 100644
--- a/brain/knowledge/flows-execution/flows.md
+++ b/brain/knowledge/flows-execution/flows.md
@@ -32,6 +32,7 @@ Flows are the core automation primitive: a versioned directed graph of trigger +
- List filtering: `folderId` uses the string sentinel `"NULL"` for uncategorized; `folderIds` (array) loads all foldered flows in one request.
- Builder is Zustand-sliced (flow/run/canvas/step-form/piece-selector state). Canvas supports vertical (default) and horizontal orientations, and PNG export via a hand-rolled clone-and-rasterize pipeline.
- **`Popover.Trigger asChild` always composes its own open-toggle onto the child's click, even when `open`/`onOpenChange` is externally controlled — a `preventDefault()`-shaped guard is the only thing that stops it.** Radix wires `onClick={composeEventHandlers(props.onClick, context.onOpenToggle)}` on the trigger, and `composeEventHandlers` skips the second handler only if `event.defaultPrevented`. `ApStepCanvasNode` wraps *every* step (trigger and action) in `<PieceSelector openSelectorOnClick={false}>` (`flow-canvas/nodes/step-node/index.tsx`), but that prop only guards the app's own `onClick` — it was `handleStepClick`'s incidental `e.preventDefault()` that actually suppressed Radix's toggle for ordinary steps. PR #14405 ("close trigger piece selector on outside/repeat click") removed that `preventDefault()` and made `pieces-selector/index.tsx`'s `onOpenChange` unconditionally honor `open` for any step id — fixing a real empty-trigger close/repeat-click race, but with nothing scoping the new open-branch to the empty trigger specifically. Regression window: 2026-07-28 (#14405) to 2026-08-11 — any plain click on a *configured* step's body reopened its own piece selector, not just the empty trigger (case 1) or an explicit Replace (case 2, which sets the state directly from the context menu and never touches this trigger). Fix: gate the `onOpenChange` open-branch on `isForEmptyTrigger || openSelectorOnClick` instead of honoring every toggle — Radix's own attempt to open is simply ignored (state doesn't change, so the controlled `open` prop stays false) when neither condition holds. Confirmed both the break and the fix by reproducing the exact `Popover.Root`/`Trigger asChild` wiring against the real installed `radix-ui` package in a throwaway vitest — not just static reading. The general lesson (Radix always attempts the toggle; controlled mode only means *you* decide whether to honor it) applies to every controlled Radix `Trigger` in this codebase, not just this one.
+- **Rolling a release back past a `LATEST_FLOW_SCHEMA_VERSION` bump fails silently, not loudly.** `flowMigrations.apply` matches a row on exact equality (`flowVersion.schemaVersion === migration.targetSchemaVersion`), so a row stamped `'27'` running on code that only knows up to `'26'` matches no migration, is returned unchanged, and is not even rewritten — no error, no page, nothing in the log. The row survives; what does not survive is whatever the new migration wrote into it, because the old code has no idea how to read it. So a release that bumps the schema version is a one-way door for every flow read while it was live, and the only way back is `backupFiles[<old version>]`, which nothing reads on its own (`flowVersionBackupService.get()` has no callers). Ship a schema-version bump in a release of its own, with nothing in it you might want to revert for another reason. **And when the migration depends on a server-side change, put the two in different releases, server code first.** A rollback then lands on a server that still understands what the migration wrote: ship both together and undoing that release leaves every rewritten row unreadable, ship the migration one release later and the same rollback is safe.
- **Anything drawn in canvas coordinates must measure the canvas element, never infer its offset from app chrome.** The note and step drag previews are `position: absolute` inside the canvas and used to subtract `#project-sidebar`'s width plus a hardcoded 60px header; when the chat-first rail (#15005) replaced that sidebar the id vanished, the width read 0, and Add note silently stopped working — the preview drew a sidebar-width right of the cursor, so the placing click always missed it. Take the origin from xyflow's `useStore((s) => s.domNode)?.getBoundingClientRect()`. `position: fixed` is no way out: an ancestor carries `will-change: transform`, which makes it the containing block.
- **A stray DRAFT row makes a published flow look blank.** "Latest version" is resolved by `getFlowVersionOrThrow({ versionId: undefined })`, which is just `ORDER BY created DESC` with no state filter — so any DRAFT created after the LOCKED version *is* what the builder opens. This is why a half-created draft is a user-visible outage, not DB litter: recovering needs the row deleted or a `USE_AS_DRAFT`. Editing a published flow used to commit the empty DRAFT and import the locked content into it as two separate writes, so an import failure (field case: `RangeError: Maximum call stack size exceeded` on deeply nested flows — the recursive `sanitizeObjectForPostgresql` before the save is the prime suspect) left the flow rendering empty forever. GIT-1590 / Pylon #5225; the `RangeError` itself is still open as GIT-1593.
- **Draft creation is now atomic, in two different ways — know which one you're in.** `createNewDraftIfVersionIsPublished` runs `createEmptyVersion` + the IMPORT_FLOW loop in one `transaction()`, threading the `entityManager` down through `applyOperation` to the `updateLastModified` side effect. The *user's* operation deliberately stays outside that transaction (it would hold Postgres open across `prepareRequest` piece-metadata fetches and non-rollbackable file/webhook side effects) and is instead undone by a compensating `delete` of the freshly created draft. `flowService.create` wraps the flow row + first empty version the same way, so a failure can't leave a zero-version, unopenable flow.
diff --git a/brain/knowledge/memory.md b/brain/knowledge/memory.md
index 62309b2f627..fd035296001 100644
--- a/brain/knowledge/memory.md
+++ b/brain/knowledge/memory.md
@@ -1,4 +1,6 @@
- 2026-09-24 — `test-unit` (api unit tests) only joined the PR pipeline on 2026-09-20 (#15653). A branch whose last CI run predates that has never had its unit tests run in CI; expect first-time failures when it merges `main`, as #15550 did (a test mock disagreeing with the real code, not a merge problem).
+- 2026-09-20 — Found while planning the AI tier work: managed AI piece steps under-billed for about 23 days, between #14942 (2026-08-24) and #15494 (2026-09-16). #14942 changed the AI piece's `provider` prop to store an object (`{ provider, configId }`), but `flow-run-ai-usage-extractor` read that field with a string-only helper, so it resolved to `'unknown'`, failed the `provider !== ACTIVEPIECES` check in `resolveAiCreditWeight`, and charged **1 credit** per step instead of the model's table weight. It hit the five non-agent AI steps only, and only those configured or re-saved inside that window — a step saved earlier still held a plain string and billed correctly. `run_agent` was never affected, because it stores `aiProviderModel` instead. Nothing logged an error, and every test in the file passed a string provider, so the suite was green the whole time. The code is gone (#15494 deleted the extractor and bills on real provider cost now), so there is nothing left to fix — but the cloud credit events for that window are still wrong, and nobody has reconciled them.
+- 2026-09-20 — The live `ai/pricing.json` (version 1, published 2026-09-14) carried a leftover test tier `tier-4` / "New tier" on `anthropic/claude-opus-4.8`, created by clicking "add tier" in the pricing console and publishing. It was removed on 2026-09-24 by deleting the whole object, so the key is 404 until someone publishes again from the console; every server falls back to the bundled tiers and warns every five minutes until then. Next time, edit the row and publish; do not delete the object.
- 2026-09-06 — Follow-up (Option B, "stub-writer cascade"): fix `engine-run-callback-service.ts` `ensureLogsFileExists` (line 84-86) so a fresh log-file stub isn't written with `{ steps: {}, tags: [] }` when the underlying file is missing — that stub is what the next BullMQ retry downloads and trips `EmptyResumeStateError` on. Options: (a) store `internalError` on `flow_run` itself so no stub is needed; (b) use a distinguishable stub shape (`executionState: null`) that the engine reader rejects fast; (c) `UnrecoverableError` in worker on state-loss errors so BullMQ doesn't retry the stub. Handles manual-admin-ops case (case #5 in the retention-hunt discussion) and any non-retention internal-error that would otherwise loop. Ping user once C.2/W.1/#2/#4 have landed.
- 2026-09-10 — `bun.lock` on main is out of sync with four workspaces (three piece version bumps, plus `packages/pieces/community/sage-accounting` missing entirely), so `bun install --frozen-lockfile` — and therefore the Dockerfile — fails on main until someone runs `bun install` and commits the lockfile.
- 2026-09-10 — Measured embed analytics cost inside the embedded builder (headless Chromium, M-series Mac, 12-step flow, scripted zoom/pan/4 step-panel opens over ~16 s, medians of 3, baseline noise ±7%): Clarity → main-thread +100 ms (+6%, consistent every round), heap +4 to +22 MB depending on GC timing, ~6k extra DOM nodes and ~1.9k extra listeners (its DOM mirror), 76 KB download once, ~120 KB uploaded per 30 s active (~4 KB/s); GTM (container `GTM-5KZNZGMN`, no firing tags) → indistinguishable from baseline at runtime, 331 KB download once; both together → additive. Time-to-canvas unchanged in every scenario. Bench script lives in the session scratchpad `bench/bench.js`; drives `/embed` top-level by answering `CLIENT_INIT` with a synthetic `VENDOR_INIT` from an init script, measures via CDP `Performance.getMetrics`. Worst case (155-step flow with 5 loops, Clarity+GTM with a published GA4 tag, heavy scripted use, medians of 3): normal CPU → main-thread +0.2%, 45 fps both, p95 input latency 1288→1296 ms, heap +40 MB (Clarity mirror takes DOM-tracked nodes 9k→33k), 0.9 MB download once (mostly gtm.js+gtag.js), ~280 KB uploaded per ~50 s; 4× CPU throttle → main-thread +4%, 25 fps both, p95 input 4.47→4.45 s, heap +17 MB. Analytics never changed frame rate or input latency; the builder itself is the bottleneck on huge flows (1.3 s to open a step panel at normal CPU, ~4.5 s throttled, with or without tracking).
diff --git a/brain/knowledge/platform-editions-ee/console.md b/brain/knowledge/platform-editions-ee/console.md
new file mode 100644
index 00000000000..c60b4aa18ec
--- /dev/null
+++ b/brain/knowledge/platform-editions-ee/console.md
@@ -0,0 +1,86 @@
+---
+title: Console
+icon: 🎛️
+---
+
+# Console
+
+The internal admin dashboard, in its **own repo** (`activepieces/console`, private). Not
+customer-facing except for one corner, the Portal. It holds the Autumn master key, mints license
+keys, and is what support and sales actually look at. Activepieces talks to it over
+`AUTUMN_CONSOLE_URL` — see [EE Platform (Plans & Billing)](./ee-platform-plans-billing.md) for
+that contract.
+
+Small: Nx monorepo, bun, three packages, about 8.6k lines of server and 12.4k of web.
+
+**Main DB** — the Supabase project holding `license_keys`, `key_history`, `admin_access`,
+`usage_snapshots`, `usage_limits`, `billing_periods`, `invoices`, read through `supabaseAdmin()`.
+**Chat-analytics DB** — a *second, separate* Supabase project holding `conversations`,
+`conversation_scores`, `audit_log`, read through `chatAnalyticsSupabaseAdmin()`.
+**Architecture A+** — the repo's own name for that split: one codebase, a separate Supabase
+project per sensitive module. DB-level isolation without microservices.
+**Portal** — the customer-facing half at `/portal`. Sign in with email + license key, get a
+self-signed JWT, see your own usage read-only. Easy to forget this repo is not purely internal.
+
+## Stack
+
+| Layer | What |
+|---|---|
+| Server | Fastify 5 + `fastify-type-provider-zod` + `@supabase/supabase-js`. Runs `.ts` under `tsx`, **no bundler** — so its `build` target is `tsc --noEmit`, a typecheck. |
+| Web | React 19, react-router 7 (`BrowserRouter`, not framework mode), Vite 6, Tailwind 4, TanStack Query 5, shadcn/ui on Radix. One flat routes file, no lazy loading. |
+| Shared | Plain TS + zod, no build step, imported as source. |
+| Ports | web **5757**, API **5858**. |
+
+One container serves both: the server registers `@fastify/static` on `packages/web/dist` when it
+exists, with a not-found handler returning `index.html`.
+
+A feature is three files — `<name>-module.ts` (owns the prefix), `<name>-controller.ts` (routes,
+with the route option consts *below* the controller), `<name>-service.ts` (all Supabase access).
+
+## Auth — four kinds, not one
+
+| Hook | Caller | Credential |
+|---|---|---|
+| `supabaseAuthHook` | a person in the admin UI | Google OAuth via Supabase, then an `admin_access` row lookup |
+| `apiKeyAuthHook` | machines | shared secret `AP_API_SECRET_KEY`, constant-time compare |
+| `licenseKeyAuthHook` | AP instances pushing usage | the license key itself as Bearer |
+| `portalAuthHook` | customers | self-signed JWT from `AP_PORTAL_JWT_SECRET` |
+
+Login is **Google only** — there is no password path. `assertAdmin` is a separate role check on
+top. `AP_DEV_AUTH_BYPASS` + `VITE_DEV_AUTH_BYPASS` disables all admin auth for local work.
+
+## Gotchas
+
+- **`core/migrations.ts` does not run migrations.** It probes each declared table/column with a
+ `head: true` select and, when one is missing, **logs the SQL for a human to paste into the
+ Supabase SQL Editor**. Nothing is ever executed. Repeated "Migration pending" lines in the logs
+ are the app asking you to go run DDL by hand. The chat-analytics DB has no detector at all —
+ its schema is a checked-in `chat-analytics-schema.sql` applied manually.
+- **There is no ORM and no Postgres connection.** Every query is HTTP to PostgREST with the
+ `service_role` key; the DB password is unused. So no transactions, no hand-written joins, and
+ `ilike` values must be escaped yourself via `supabase-utils.ts`. There is also no generated
+ `Database` type — the client is untyped and zod at the route boundary is the only enforcement.
+- **`supabase-js` needs Node 22 at runtime, and a Node 20 image fails only after login, never at boot.** `@supabase/realtime-js` (2.112+) asks for a global `WebSocket`, which Node ships unflagged from 22. `SupabaseClient`'s constructor builds a `RealtimeClient` whether or not you use realtime, so on `node:20-alpine` `createClient()` throws `Node.js detected but native WebSocket not found`. Because `supabaseAdmin()` is called lazily inside the request hook rather than at startup, the container boots, passes its health check and looks deployed — then every authenticated request 500s. The generic `INTERNAL_ERROR` body hides it; the stack is only in the Runtime Logs. Pin the runner stage to `node:22-alpine`.
+- **"Access restricted to authorized admin accounts" does not mean your row is missing.** `supabase-auth-hook.ts` reads the `admin_access` row as `const { data: access } = await ...single()` and throws the `error` away, so a missing row, a missing *table*, and an RLS or PostgREST failure all end as the same 401. Before chasing the row, run `select * from admin_access;` in that project's SQL Editor — `relation does not exist` means the schema was never applied (nothing applies it for you; see the migrations gotcha above). If the row is there, compare the email exactly: the lookup is `.eq('user_email', email)` and Postgres text compare is case-sensitive, so `Louai@` never matches `louai@`. `ap-analytics` has the same hook and the same trap.
+- **Never mix the two Supabase clients.** Customer chat data must never reach the main project.
+ A wrong `supabaseAdmin()` in a chat module is a data-isolation break, not a bug.
+- **Production config is a `.env` file on the box, not anything a cloud panel shows you.** There is no secret manager anywhere in the repo — no Doppler, Vault, 1Password or SOPS. The server just reads `process.env[prefix + prop]` (`AP_` for everything, `VITE_` for the two shared ones), and `docker/docker-compose.yml` feeds it with `env_file: ../.env`. So if the app runs on a droplet, DigitalOcean has no environment-variable UI to look in and never will — that is a DO App Platform feature, and a droplet is just a Linux box. To find the values, `docker exec <container> env | grep -E 'AP_|VITE_'`, which works whatever put them there. Check `ls -l .env` is `600` while you are in there: it holds `AP_SUPABASE_SERVICE_ROLE_KEY`, which is full read-write on the billing database.
+- **`VITE_SUPABASE_URL` and `VITE_SUPABASE_ANON_KEY` are not secrets and are not runtime config.** They are `ARG`s in the Dockerfile, so Vite substitutes them at *build* time and they ship inside the JavaScript the browser downloads — open any `assets/index-*.js` and search for `supabase.co` to read them without any server access. That is intended: the anon key is public by design, and RLS plus the `admin_access` lookup are the real protection. The consequence for CI is that both must be available as build-time secrets, not only on the server. Fastest way to identify which Supabase project an environment points at: open devtools and read the `*.supabase.co` subdomain off any request.
+- **The deploy is not in the repo.** Only a `Dockerfile`, a compose file, and a CI job that lints,
+ typechecks and tests. Where it runs is configured elsewhere — the org's pattern for internal
+ tools is a DigitalOcean droplet driven by Actions over SSH, which you have to read out of
+ `activepieces/discover`'s `deploy.yml`.
+- **The server reads `AP_PORT` and ignores `PORT`, which breaks it on any PaaS.** Its Dockerfile even sets `ENV PORT=3000`, a line that does nothing. This is harmless on a droplet, where you choose the port, and fatal on DigitalOcean App Platform, Railway or Render: they inject `PORT` and health-check it, the app listens somewhere else, and the deploy fails with nothing but 'health check failed'. On App Platform the injected `PORT` is exactly the component's **HTTP Port** setting, so a port pinned in the image is only fatal when the two disagree — and because a boot crash from any missing required env var reports as the same 'health check failed', do not diagnose it as a port problem until the Runtime Logs say so. `ap-analytics` hit exactly this and fixed it by defaulting `PORT` into the prop (`AP_PORT` -> `PORT` -> a local default) and pinning nothing in the image. Do the same here before moving the console off a droplet.
+ That line is dead unless the platform injects `AP_PORT` separately.
+- **App Platform autodetect makes one component per `package.json`, so an Nx monorepo lands as three.** With no `.do/app.yaml` in the repo, DigitalOcean scans and creates a component for `packages/server`, `packages/web` and `packages/shared` — `ap-analytics` came out as two Web Services and a Function for what is a single container. Only one is right: the root `Dockerfile` already serves the API and the built web assets together (`@fastify/static` on `packages/web/dist` with an `index.html` fallback), so keep the component whose Source Directory is `/` and whose build is the Dockerfile, and destroy the rest. The auto-generated names (`<repo>2`, `<repo>3`) say nothing about which is which — check the Source tab, not the name. Committing a `.do/app.yaml` stops the guessing for good.
+- **Config features belong in `ap-analytics` (the repo that calls itself "config console"), not here** — see decision
+ [000039](../decisions/000041-ai-model-tiers-are-published-to-the-cdn-from-a-second-console.md).
+
+## Key files
+
+- `packages/server/api/src/app/app.ts` — every route prefix in one place
+- `packages/server/api/src/app/core/auth/` — the four hooks
+- `packages/server/api/src/app/core/migrations.ts` — the detector, not a runner
+- `packages/server/api/src/app/modules/license-keys/` — the clearest three-file feature
+- `packages/web/src/features/license-keys/` — the list + detail + dialog shape
+- `packages/web/src/styles.css` — the whole design system; there is no `tailwind.config.js`
diff --git a/brain/knowledge/platform-editions-ee/index.md b/brain/knowledge/platform-editions-ee/index.md
index 987cede997b..04251d553c0 100644
--- a/brain/knowledge/platform-editions-ee/index.md
+++ b/brain/knowledge/platform-editions-ee/index.md
@@ -47,3 +47,4 @@ Activation/recovery handle for a self-hosted platform's Autumn billing identity
- **License Keys** — activating self-hosted EE
- **Embed** — signing keys, external tokens, the Cloudflare subdomain, and the frame-ancestors CSP
- **Platform Copilot** — retired; kept for the migration trail
+- **Console** — the internal admin dashboard in its own repo: two Supabase projects, four auth hooks, and migrations that only print SQL
diff --git a/docs/install/reference/environment-variables.mdx b/docs/install/reference/environment-variables.mdx
index 1ed3106f421..d224dab053a 100644
--- a/docs/install/reference/environment-variables.mdx
+++ b/docs/install/reference/environment-variables.mdx
@@ -155,6 +155,7 @@ run timeouts, and the network egress posture for user code. Read
| `AP_NETWORK_MODE` | Egress posture for user code. `STRICT` installs the engine's in-process SSRF guard, blocking outbound connections to private, loopback, link-local, and cloud-metadata IPs across every Node egress path (`axios`, `fetch`, `undici`, raw `http`/`net`). This is best-effort, in-process protection — enforce the real boundary in infrastructure (see [Network Security](/install/architecture/network-security)). `UNRESTRICTED` disables the guard. | `UNRESTRICTED` |
| `AP_SSRF_ALLOW_LIST` | Comma-separated IPs or CIDR ranges that bypass `AP_NETWORK_MODE=STRICT`, e.g. `10.0.0.5,10.10.0.0/24`. Only applies when `AP_NETWORK_MODE=STRICT`. | `None` |
| `AP_MODEL_CATALOG_URL` | Source for AI model metadata (context window, pricing, capabilities), shown beside each model when picking one. Fetched once and cached for 24 hours. An install with no egress to the default CDN simply shows models without that metadata; point this at a self-hosted mirror of the same JSON to restore it. | `https://cdn.activepieces.com/ai/model-catalog.json` |
+| `AP_MODEL_TIERS_URL` | Source for the published AI model tiers file (Fast / Expert / Heavy and the model behind each). Read at boot and refreshed every 15 minutes. An install with no egress to the default CDN keeps the tiers shipped with the release and logs a warning at boot. | `https://cdn.activepieces.com/ai/pricing.json` |
---
diff --git a/packages/server/api/src/app/ai/ai-provider-service.ts b/packages/server/api/src/app/ai/ai-provider-service.ts
index bbde89f949a..940eac9eed6 100644
--- a/packages/server/api/src/app/ai/ai-provider-service.ts
+++ b/packages/server/api/src/app/ai/ai-provider-service.ts
@@ -1,5 +1,5 @@
import { ActivepiecesError, AiProviderKeyStatus, AIProviderName, apId, classifyProviderOutcome, ErrorCode, isNil, PlatformId, ProviderOutcomeSignal, spreadIfDefined, spreadIfNotUndefined, toProviderOutcomeSignal, tryCatch, unique } from '@activepieces/core-utils'
-import { modelCatalog } from '@activepieces/server-utils'
+import { modelCatalog, modelTierCatalog } from '@activepieces/server-utils'
import { ActivePiecesProviderAuthConfig, AI_PROVIDER_ENTITY_TYPES, AIProviderAuthConfig, AIProviderConfig, aiProviderCredentials, AIProviderModel, AiProviderProjectScope, AIProviderWithoutSensitiveData, CreateAIProviderRequest, GetProviderConfigResponse, ProjectAIProvider, UpdateAIProviderRequest } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import cron from 'node-cron'
@@ -28,6 +28,7 @@ const CONFIRM_MIN_INTERVAL_SECONDS = 10
export const aiProviderService = (log: FastifyBaseLogger) => ({
async setup(): Promise<void> {
+ await modelTierCatalog.warmUp()
cron.schedule('0 0 * * *', () => {
log.info('Clearing AI provider models cache')
modelsCache.clear()
diff --git a/packages/server/utils/src/index.ts b/packages/server/utils/src/index.ts
index 28c6b370884..461d31e558d 100644
--- a/packages/server/utils/src/index.ts
+++ b/packages/server/utils/src/index.ts
@@ -22,6 +22,8 @@ export type { RedactConfig } from './logger-redact'
export { memoryLock } from './memory-lock'
export type { ApLock } from './memory-lock'
export { modelCatalog } from './model-catalog'
+export { modelTierCatalog } from './model-tier-catalog'
+export type { ModelTier, ModelTierReader, ModelTierSurface } from './model-tier-catalog'
export { RedisType } from './redis-type'
export { safeHttp } from './safe-http'
export type { SsrfAgents } from './safe-http'
diff --git a/packages/server/utils/src/model-tier-catalog.ts b/packages/server/utils/src/model-tier-catalog.ts
new file mode 100644
index 00000000000..73728c3fa2b
--- /dev/null
+++ b/packages/server/utils/src/model-tier-catalog.ts
@@ -0,0 +1,185 @@
+import { isNil, tryCatch } from '@activepieces/core-utils'
+import { ACTIVEPIECES_CHAT_TIERS, DEFAULT_CHAT_TIER_ID } from '@activepieces/shared'
+import { z } from 'zod'
+import { apLogger } from './ap-logger'
+import { safeHttp } from './safe-http'
+
+const logger = apLogger.create()
+
+export const modelTierCatalog = {
+ async warmUp(): Promise<void> {
+ await Promise.race([
+ loadTiers(),
+ new Promise<void>((resolve) => setTimeout(resolve, WARM_UP_TIMEOUT_MS).unref()),
+ ])
+ },
+
+ current(surface: ModelTierSurface): ModelTierReader {
+ if (isNil(cached) || Date.now() - cached.fetchedAt >= TIERS_TTL_MS) {
+ loadTiers().catch(() => undefined)
+ }
+ return (cached?.readers ?? bundledReaders())[surface]
+ },
+}
+
+async function loadTiers(): Promise<void> {
+ if (!isNil(cached) && Date.now() - cached.fetchedAt < TIERS_TTL_MS) {
+ return
+ }
+ if (!isNil(lastFailureAt) && Date.now() - lastFailureAt < FAILURE_BACKOFF_MS) {
+ return
+ }
+ await tryCatch(() => inFlight ?? startFetch())
+}
+
+function startFetch(): Promise<void> {
+ inFlight = fetchTiers()
+ .then((published) => {
+ cached = { fetchedAt: Date.now(), readers: buildReaders(published) }
+ lastFailureAt = undefined
+ })
+ .catch((error: unknown) => {
+ lastFailureAt = Date.now()
+ logger.warn({ error, tiers: { url: tiersUrl() } }, isNil(cached)
+ ? 'Failed to load the AI model tiers file; serving the tiers shipped with the release'
+ : 'Failed to refresh the AI model tiers file; keeping the last published copy')
+ throw error
+ })
+ .finally(() => {
+ inFlight = undefined
+ })
+ return inFlight
+}
+
+async function fetchTiers(): Promise<PublishedTiers> {
+ const response = await safeHttp.retryingAxios.get(tiersUrl(), {
+ timeout: REQUEST_TIMEOUT_MS,
+ })
+ return PublishedTiers.parse(response.data)
+}
+
+function tiersUrl(): string {
+ return process.env['AP_MODEL_TIERS_URL'] ?? DEFAULT_TIERS_URL
+}
+
+function buildReaders(published: PublishedTiers): Record<ModelTierSurface, ModelTierReader> {
+ const flow = buildReader(flowListOf(published))
+ const chatList = chatListOf(published)
+ return {
+ flow,
+ chat: isNil(chatList) ? flow : buildReader(chatList),
+ }
+}
+
+function buildReader({ tiers, defaultTierId, fastTierId }: TierList): ModelTierReader {
+ const tiersById = new Map(tiers.map((tier) => [tier.id, tier]))
+ const defaultTier = tiersById.get(defaultTierId) ?? tiers[0]
+ return {
+ tiers,
+ defaultTierId: defaultTier.id,
+ fastTierId: fastTierId ?? DEFAULT_FAST_TIER_ID,
+ findTier({ tierId }) {
+ return tiersById.get(tierId)
+ },
+ resolveTier({ tierId }) {
+ return (isNil(tierId) ? undefined : tiersById.get(tierId)) ?? defaultTier
+ },
+ }
+}
+
+function flowListOf({ tiers, defaultTierId, fastTierId }: PublishedTiers): TierList {
+ return { tiers, defaultTierId, fastTierId }
+}
+
+function chatListOf({ chatTiers, chatDefaultTierId, chatFastTierId }: PublishedTiers): TierList | undefined {
+ if (isNil(chatTiers) || isNil(chatDefaultTierId)) {
+ return undefined
+ }
+ return { tiers: chatTiers, defaultTierId: chatDefaultTierId, fastTierId: chatFastTierId }
+}
+
+function tierListProblems({ tiers, defaultTierId, fastTierId }: TierList): string[] {
+ const ids = tiers.map((tier) => tier.id)
+ return [
+ ...(new Set(ids).size === ids.length ? [] : ['tier ids must be unique within a list']),
+ ...(ids.includes(defaultTierId) ? [] : ['the default tier must be one of the tiers']),
+ ...(ids.includes(fastTierId ?? DEFAULT_FAST_TIER_ID) ? [] : ['the fast tier must be one of the tiers']),
+ ]
+}
+
+function bundledReaders(): Record<ModelTierSurface, ModelTierReader> {
+ bundled ??= buildReaders({
+ version: 0,
+ publishedAt: BUNDLED_PUBLISHED_AT,
+ publishedBy: 'bundled-with-release',
+ tiers: ACTIVEPIECES_CHAT_TIERS.map((tier) => ({ ...tier })),
+ defaultTierId: DEFAULT_CHAT_TIER_ID,
+ })
+ return bundled
+}
+
+let cached: { fetchedAt: number, readers: Record<ModelTierSurface, ModelTierReader> } | undefined
+let bundled: Record<ModelTierSurface, ModelTierReader> | undefined
+let inFlight: Promise<void> | undefined
+let lastFailureAt: number | undefined
+
+const DEFAULT_TIERS_URL = 'https://cdn.activepieces.com/ai/pricing.json'
+const DEFAULT_FAST_TIER_ID = 'fast'
+const TIERS_TTL_MS = 15 * 60 * 1000
+const FAILURE_BACKOFF_MS = 5 * 60 * 1000
+const REQUEST_TIMEOUT_MS = 10_000
+const WARM_UP_TIMEOUT_MS = 2_000
+const BUNDLED_PUBLISHED_AT = '1970-01-01T00:00:00.000Z'
+
+const PublishedTier = z.object({
+ id: z.string().min(1),
+ label: z.string().min(1),
+ modelId: z.string().min(1),
+ nativeModelId: z.string().min(1).optional(),
+ thinkingBudget: z.int().positive(),
+})
+
+const PublishedTiers = z
+ .object({
+ version: z.int().min(0),
+ publishedAt: z.string().min(1),
+ publishedBy: z.string().min(1),
+ tiers: z.array(PublishedTier).min(1),
+ defaultTierId: z.string().min(1),
+ fastTierId: z.string().min(1).optional(),
+ chatTiers: z.array(PublishedTier).min(1).optional(),
+ chatDefaultTierId: z.string().min(1).optional(),
+ chatFastTierId: z.string().min(1).optional(),
+ })
+ .superRefine((value, ctx) => {
+ for (const message of tierListProblems(flowListOf(value))) {
+ ctx.addIssue({ code: 'custom', message, path: ['tiers'] })
+ }
+ if (isNil(value.chatTiers) !== isNil(value.chatDefaultTierId)) {
+ ctx.addIssue({ code: 'custom', message: 'chatTiers and chatDefaultTierId must be published together', path: ['chatTiers'] })
+ }
+ const chatList = chatListOf(value)
+ for (const message of isNil(chatList) ? [] : tierListProblems(chatList)) {
+ ctx.addIssue({ code: 'custom', message, path: ['chatTiers'] })
+ }
+ })
+
+type PublishedTiers = z.infer<typeof PublishedTiers>
+
+type TierList = {
+ tiers: ModelTier[]
+ defaultTierId: string
+ fastTierId?: string
+}
+
+export type ModelTierSurface = 'chat' | 'flow'
+
+export type ModelTier = z.infer<typeof PublishedTier>
+
+export type ModelTierReader = {
+ tiers: ModelTier[]
+ defaultTierId: string
+ fastTierId: string
+ findTier(params: { tierId: string }): ModelTier | undefined
+ resolveTier(params: { tierId: string | null | undefined }): ModelTier
+}
diff --git a/packages/server/utils/test/model-tier-catalog.test.ts b/packages/server/utils/test/model-tier-catalog.test.ts
new file mode 100644
index 00000000000..cca06b4a40e
--- /dev/null
+++ b/packages/server/utils/test/model-tier-catalog.test.ts
@@ -0,0 +1,195 @@
+import { ACTIVEPIECES_CHAT_TIERS, DEFAULT_CHAT_TIER_ID } from '@activepieces/shared'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const get = vi.fn()
+
+vi.mock('../src/safe-http', () => ({
+ safeHttp: {
+ get retryingAxios() {
+ return { get }
+ },
+ },
+}))
+
+const FAST = { id: 'fast', label: 'Fast', modelId: 'anthropic/claude-haiku-4.5', thinkingBudget: 5_000 }
+const SMART = { id: 'smart', label: 'Expert', modelId: 'anthropic/claude-sonnet-4.6', thinkingBudget: 10_000 }
+const CHAT_SMART = { id: 'smart', label: 'Expert', modelId: 'openai/gpt-5.5', thinkingBudget: 10_000 }
+const DEEP = { id: 'deep', label: 'Deep', modelId: 'anthropic/claude-opus-4.8', thinkingBudget: 20_000 }
+
+const FLOW_ONLY = {
+ version: 3,
+ publishedAt: '2026-09-26T00:00:00.000Z',
+ publishedBy: '[email protected]',
+ tiers: [FAST, SMART],
+ defaultTierId: 'smart',
+}
+
+const BOTH_LISTS = {
+ ...FLOW_ONLY,
+ chatTiers: [FAST, CHAT_SMART, DEEP],
+ chatDefaultTierId: 'deep',
+}
+
+const BUNDLED_IDS = ACTIVEPIECES_CHAT_TIERS.map((tier) => tier.id)
+
+async function freshCatalog(): Promise<typeof import('../src/model-tier-catalog').modelTierCatalog> {
+ vi.resetModules()
+ const { modelTierCatalog } = await import('../src/model-tier-catalog')
+ return modelTierCatalog
+}
+
+async function warmedCatalog(file: unknown): Promise<typeof import('../src/model-tier-catalog').modelTierCatalog> {
+ get.mockResolvedValue({ data: file })
+ const catalog = await freshCatalog()
+ await catalog.warmUp()
+ return catalog
+}
+
+function ids(tiers: { id: string }[]): string[] {
+ return tiers.map((tier) => tier.id)
+}
+
+describe('modelTierCatalog', () => {
+ beforeEach(() => {
+ get.mockReset()
+ process.env['AP_MODEL_TIERS_URL'] = 'https://tiers.test/pricing.json'
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ delete process.env['AP_MODEL_TIERS_URL']
+ })
+
+ it('serves the flow list and the chat list from one file, each with its own default', async () => {
+ const catalog = await warmedCatalog(BOTH_LISTS)
+
+ expect(ids(catalog.current('flow').tiers)).toEqual(['fast', 'smart'])
+ expect(catalog.current('flow').defaultTierId).toBe('smart')
+ expect(ids(catalog.current('chat').tiers)).toEqual(['fast', 'smart', 'deep'])
+ expect(catalog.current('chat').defaultTierId).toBe('deep')
+ expect(get).toHaveBeenCalledWith('https://tiers.test/pricing.json', expect.anything())
+ })
+
+ it('lets the same tier id point at different models on the two lists', async () => {
+ const catalog = await warmedCatalog(BOTH_LISTS)
+
+ expect(catalog.current('flow').resolveTier({ tierId: 'smart' }).modelId).toBe('anthropic/claude-sonnet-4.6')
+ expect(catalog.current('chat').resolveTier({ tierId: 'smart' }).modelId).toBe('openai/gpt-5.5')
+ })
+
+ it('reads the flow list for chat when the file has no chat keys', async () => {
+ const catalog = await warmedCatalog(FLOW_ONLY)
+
+ expect(catalog.current('chat')).toBe(catalog.current('flow'))
+ })
+
+ it('points the fast tier at "fast" unless the file says otherwise', async () => {
+ const catalog = await warmedCatalog({ ...BOTH_LISTS, fastTierId: 'smart' })
+
+ expect(catalog.current('flow').fastTierId).toBe('smart')
+ expect(catalog.current('chat').fastTierId).toBe('fast')
+ })
+
+ it('resolves an unknown or missing tier id to the default of that surface', async () => {
+ const catalog = await warmedCatalog(BOTH_LISTS)
+
+ expect(catalog.current('chat').resolveTier({ tierId: 'does-not-exist' }).id).toBe('deep')
+ expect(catalog.current('chat').resolveTier({ tierId: undefined }).id).toBe('deep')
+ expect(catalog.current('flow').resolveTier({ tierId: null }).id).toBe('smart')
+ expect(catalog.current('flow').findTier({ tierId: 'does-not-exist' })).toBeUndefined()
+ })
+
+ it('serves the tiers shipped with the release when the fetch fails, and still finishes warm-up', async () => {
+ get.mockRejectedValue(new Error('network is down'))
+ const catalog = await freshCatalog()
+
+ await expect(catalog.warmUp()).resolves.toBeUndefined()
+ expect(ids(catalog.current('flow').tiers)).toEqual(BUNDLED_IDS)
+ expect(catalog.current('flow').defaultTierId).toBe(DEFAULT_CHAT_TIER_ID)
+ expect(catalog.current('chat')).toBe(catalog.current('flow'))
+ })
+
+ it('finishes warm-up within two seconds when the CDN hangs', async () => {
+ vi.useFakeTimers()
+ get.mockReturnValue(new Promise(() => undefined))
+ const catalog = await freshCatalog()
+
+ const warmUp = catalog.warmUp()
+ await vi.advanceTimersByTimeAsync(2_000)
+
+ await expect(warmUp).resolves.toBeUndefined()
+ expect(ids(catalog.current('flow').tiers)).toEqual(BUNDLED_IDS)
+ })
+
+ it.each([
+ ['default tier missing from its list', { ...FLOW_ONLY, defaultTierId: 'nope' }],
+ ['no tiers at all', { ...FLOW_ONLY, tiers: [] }],
+ ['duplicate id within one list', { ...FLOW_ONLY, tiers: [FAST, { ...SMART, id: 'fast' }] }],
+ ['fast pointer missing from its list', { ...FLOW_ONLY, fastTierId: 'nope' }],
+ ['no "fast" tier and no fast pointer', { ...FLOW_ONLY, tiers: [SMART] }],
+ ['chat list without a chat default', { ...FLOW_ONLY, chatTiers: [FAST, DEEP] }],
+ ['chat default without a chat list', { ...FLOW_ONLY, chatDefaultTierId: 'smart' }],
+ ['chat default missing from the chat list', { ...BOTH_LISTS, chatDefaultTierId: 'smart-er' }],
+ ['chat fast pointer missing from the chat list', { ...BOTH_LISTS, chatFastTierId: 'nope' }],
+ ])('rejects a file whole when it has a %s', async (_, file) => {
+ const catalog = await warmedCatalog(file)
+
+ expect(ids(catalog.current('flow').tiers)).toEqual(BUNDLED_IDS)
+ expect(ids(catalog.current('chat').tiers)).toEqual(BUNDLED_IDS)
+ })
+
+ it('ignores the keys an older console still publishes', async () => {
+ const catalog = await warmedCatalog({ ...BOTH_LISTS, modelWeights: { 'openai/gpt-4': 999 }, unpricedModelCreditWeight: 250 })
+
+ expect(catalog.current('flow').resolveTier({ tierId: 'fast' }).modelId).toBe('anthropic/claude-haiku-4.5')
+ expect(Object.keys(catalog.current('flow').tiers[0])).toEqual(['id', 'label', 'modelId', 'thinkingBudget'])
+ })
+
+ it('answers synchronously with the bundled tiers before the first fetch lands, then switches to the file', async () => {
+ let release: (value: { data: unknown }) => void = () => undefined
+ get.mockReturnValue(new Promise<{ data: unknown }>((resolve) => {
+ release = resolve
+ }))
+ const catalog = await freshCatalog()
+
+ const beforeFetch = catalog.current('flow')
+ expect(ids(beforeFetch.tiers)).toEqual(BUNDLED_IDS)
+ expect(catalog.current('flow')).toBe(beforeFetch)
+ expect(get).toHaveBeenCalledTimes(1)
+
+ release({ data: BOTH_LISTS })
+ await vi.waitFor(() => expect(ids(catalog.current('flow').tiers)).toEqual(['fast', 'smart']))
+ expect(catalog.current('flow')).toBe(catalog.current('flow'))
+ expect(catalog.current('flow')).not.toBe(beforeFetch)
+ })
+
+ it('refreshes in the background after 15 minutes and backs off for 5 minutes after a failure', async () => {
+ const catalog = await warmedCatalog(BOTH_LISTS)
+ vi.useFakeTimers()
+ expect(get).toHaveBeenCalledTimes(1)
+
+ catalog.current('flow')
+ expect(get).toHaveBeenCalledTimes(1)
+
+ vi.setSystemTime(Date.now() + 16 * 60_000)
+ catalog.current('flow')
+ catalog.current('chat')
+ expect(get).toHaveBeenCalledTimes(2)
+ await vi.advanceTimersByTimeAsync(0)
+
+ get.mockRejectedValue(new Error('network is down'))
+ vi.setSystemTime(Date.now() + 16 * 60_000)
+ catalog.current('flow')
+ await vi.advanceTimersByTimeAsync(0)
+ expect(get).toHaveBeenCalledTimes(3)
+ expect(ids(catalog.current('flow').tiers)).toEqual(['fast', 'smart'])
+
+ vi.setSystemTime(Date.now() + 60_000)
+ catalog.current('flow')
+ expect(get).toHaveBeenCalledTimes(3)
+
+ vi.setSystemTime(Date.now() + 5 * 60_000)
+ catalog.current('flow')
+ expect(get).toHaveBeenCalledTimes(4)
+ })
+})