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): platform model tiers data and api (#15995)

Louai Boumediene3f6f2b49b942
diff --git a/brain/knowledge/ai-intelligence/ai-providers.md b/brain/knowledge/ai-intelligence/ai-providers.md
index 5eabcb51f81..2668dcc553a 100644
--- a/brain/knowledge/ai-intelligence/ai-providers.md
+++ b/brain/knowledge/ai-intelligence/ai-providers.md
@@ -4,7 +4,7 @@ icon: 🧠
# AI Providers
-Lets platform admins configure one or more LLM backends for AI pieces in flows. Also auto-provisions an "Activepieces" provider (backed by OpenRouter) whose credit balance and auto-top-up are metered by Autumn billing. EE/Cloud only (not registered in CE).
+Lets platform admins configure one or more LLM backends for AI pieces in flows. Also auto-provisions an "Activepieces" provider (backed by OpenRouter) whose credit balance and auto-top-up are metered by Autumn billing. Registered in every edition (`aiProviderModule` sits outside the edition switch in `app.ts`).
### Entities & services
- **AIProvider** — platform-scoped: `displayName`, `platformId` (indexed with `provider`, NOT unique — a platform can hold multiple keys per provider since the 2026-08 providers redesign), `provider` (AIProviderName enum), `auth` (EncryptedObject, AES-256 at rest), `config` (JSON), `enabledForChat`, plus per-key scoping: `modelScope` (`all|selected`) + `modelIds[]`, and `projectScope` (`all|selected|except`) + `projectIds[]` (GIN-indexed).
@@ -68,7 +68,16 @@ derives `namesItsOwnModel` from it. The AI piece's text steps resolve through `a
enqueued. `AP_MODEL_TIERS_URL` overrides the URL. The file is published from the console in `ap-analytics`; see
decision 000041. The console publishes both lists and both fast pointers on every Publish, and on its first load
after a file without chat keys it seeds the chat list from the live flow list.
+### Platform tiers
+
+**Platform tier** — an admin-built, platform-owned list of up to 5 `{configId, modelId}` entries (main + ranked fallbacks, any keys), table `platform_model_tier`, API `/v1/platform-model-tiers`. A tier grants its entries to every project; see decision [000044](../decisions/000044-platform-tiers-are-platform-owned-and-grant-key-access.md). _Avoid_: "model tier" alone — that is the console **credits tier** (`ModelTier`, above).
+
### Gotchas
+- **A key a live platform tier uses cannot be deleted, and its `modelScope` cannot drop a tier's model.** `aiProviderService.delete` and `update` call `platformModelTierService.assertKeyCanBeDeleted` / `assertKeyScopeKeepsTiers` under a `platform` row `FOR NO KEY UPDATE` lock and answer 409 with the tier names. The same lock serialises every tier write, so a tier save can't race a key delete into a dangling entry.
+- **Deleting a platform tier needs a replacement, except the last live tier, and there is no usage count.** Refs to a deleted tier are never rewritten; they reach a live tier through `replacedBy` (flattened to one hop on delete). The last tier may always go with no replacement: without that exit, a platform's last tier and the key it uses could never be removed, because the key guard refuses keys a live tier uses. Tier delete is also deliberately **not** plan-gated (writes are), so a platform that downgrades can still clear its tiers and then remove its key. Its refs then point at a tier with `replacedBy: null`, and the resolver must fail them with a clear "tier removed" error. An exact "used by N flows" count needs a `LIKE` scan over every flow version's `trigger` text, plus agent jsonb and conversations, on the whole platform. We dropped it rather than pay that. If counts come back, add a denormalized `flow_version.modelTierIds` array + GIN index (the `connectionIds` pattern) instead of scanning.
+- **The live-name unique index is `lower("name")`, which `EntitySchema` cannot express.** The entity declares it `synchronize: false` (so `check-migrations` skips it), which means test DBs built by `synchronize` don't have it. The case-insensitive check that tests rely on is the service's `assertNameIsFree`, which is race-free because it runs under the `platform` row lock; the index is the backstop.
+- **`lockPlatform` takes `FOR NO KEY UPDATE`, not `FOR UPDATE`.** Every FK insert that references `platform` (projects, users, …) takes `FOR KEY SHARE` on the platform row, which `FOR UPDATE` blocks until commit. `FOR NO KEY UPDATE` serialises tier writes just the same without stalling those inserts.
+- **Builders read the slim tier list (`GET /v1/platform-model-tiers`) with no `configId` or key names; the full entries are `GET /admin` only.** Don't widen the builder view: it would show project users the ids of keys scoped away from them.
- **The managed key only runs models the tiers or the chat allow-list permit, enforced in `aiUtils.createModel`.** The managed provider is OpenRouter underneath, so before this guard a crafted step naming any OpenRouter model ran on our key; the picker hid it but nothing denied it. `assertManagedModelAllowed` (`server/utils/src/ai-utils.ts`) checks `managedChatModelIds()` plus both surfaces' published tier `modelId`s and throws a `VALIDATION` error. Image models are checked too, in `createModel` (`imageGeneration: true`) and `createModelForImages`: only `ACTIVEPIECES_IMAGE_TIERS` model ids, plus the id the chat path passes as `adminChosenImageModelId` (the server-chosen Capabilities model). The worker now calls `modelTierCatalog.warmUp()` at start so a cold worker does not judge a newly published tier against the bundled list.
- **A catalog change takes up to ~2 days to reach a dropdown, through three caches in series.** CDN edge (`--cache-control max-age=3600`, 1h) → the server's in-memory catalog (`CATALOG_TTL_MS`, 24h) → `modelsCache` (flushed by the 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.
diff --git a/brain/knowledge/decisions/000044-platform-tiers-are-platform-owned-and-grant-key-access.md b/brain/knowledge/decisions/000044-platform-tiers-are-platform-owned-and-grant-key-access.md
new file mode 100644
index 00000000000..f5df4c7fd19
--- /dev/null
+++ b/brain/knowledge/decisions/000044-platform-tiers-are-platform-owned-and-grant-key-access.md
@@ -0,0 +1,20 @@
+---
+status: proposed
+---
+
+# Platform tiers are platform-owned and grant key access
+
+## Decision
+A **platform tier** (`platform_model_tier`) belongs to the platform, not to a key. It is an ordered list of `{configId, modelId}` entries: entry 0 is the main model, the rest are ranked fallbacks, and the entries may come from different keys. A project that uses a tier may run every entry in it, even when an entry's key is scoped away from that project. Picking one specific model still obeys the key's scope.
+
+## Context
+Admins want builders to pick "Fast" or "Expert" instead of hunting for model ids, and to move models between tiers without breaking flows. An earlier plan put a tier map inside each provider key. That couldn't express fallbacks across providers, and it tied a tier's meaning to a single key's scope.
+
+## Why
+If a tier were limited by each key's project scope, the same tier would run different models in different projects, and a fallback on a restricted key would silently vanish. Letting the tier grant access keeps its meaning the same on every surface. We rejected the per-key tier map, because moving a model would mean rewriting every key that listed it.
+
+## Consequences
+- The grant is security-sensitive. The runtime must only honour a `configId` that a live tier on the same platform contains, and never a client-sent `configId`.
+- A key a live tier uses cannot be deleted, and its `modelScope` cannot drop a tier's model. `aiProviderService` refuses both.
+- A deleted tier stays as a soft-deleted row with a `replacedBy` pointer, so stored refs keep resolving without rewriting any flow.
+- Platform tiers are unrelated to the console **credits tiers** (`ModelTier`, `pricing.json`). They share only the word "tier".
diff --git a/brain/knowledge/engineering/ci-pr-review-hygiene.md b/brain/knowledge/engineering/ci-pr-review-hygiene.md
index c89783fbb7e..dae907053d3 100644
--- a/brain/knowledge/engineering/ci-pr-review-hygiene.md
+++ b/brain/knowledge/engineering/ci-pr-review-hygiene.md
@@ -22,6 +22,7 @@ Which team gets asked to review comes entirely from `.github/CODEOWNERS` — the
Enforcement is the **`Codeowners review` repository ruleset** (active on the default branch), not classic branch protection: `require_code_owner_review: true` plus `required_approving_review_count: 1` and `required_review_thread_resolution: true`. Eight bypass actors are configured, which is why an owner-team request can look non-blocking on some PRs.
## Gotchas
+- **When merging main, `rerere` can replay a stale `bun.lock` resolution.** "Staged 'bun.lock' using previous resolution" means git reused an old answer, which can carry workspace versions that no longer match any `package.json` (seen: core-utils `0.8.6` in the lockfile against `0.8.5` in the manifest). If the branch adds no dependencies, take main's `bun.lock` and edit only the branch's own workspace `version` lines.
- **The tests bucket keys off a path *segment*, so a feature folder named `test-step` is not mistaken for tests.** `packages/web/src/app/builder/test-step/` and `latest-test.ts` stay in `packages/web`; the regex requires `test/` as a whole segment or a `.test.`/`.spec.` suffix. The one deliberate overlap is `packages/pieces/framework/src/lib/test/index.ts` — shipped `createMockActionContext` helpers, counted as tests, and exempt either way because pieces are exempt.
- **A job-level `env:` in `ci.yml` does not reach anything turbo runs.** Turbo 2.x defaults to `--env-mode=strict`: a task's process only receives variables named in `globalPassThroughEnv` / `passThroughEnv` / `env`, plus turbo's own system list. Everything else is dropped silently, so the task falls back to whatever `packages/server/api/.env.tests` set (dotenv there runs without `override`, so a real env var would otherwise win). Symptom: the workflow clearly sets the variable and the test still uses the old value. Add the name to `globalPassThroughEnv` in `turbo.json` — that is why `AP_DB_TYPE` and `AP_POSTGRES_*` are already listed. Jobs that call `npx vitest` directly, like `tool-search-postgres`, are unaffected, which is what makes the difference easy to miss. Verify with a throwaway test that `console.log`s the variable through `npx turbo run <task> --filter=<pkg>`.
- **A GitHub service container is not reachable by its name from a non-container job.** `services:` attaches the container to a docker network with a `--network-alias`, but the runner itself is on the host, so the alias does not resolve (`getaddrinfo EAI_AGAIN redis`) and only the published `ports:` mapping on `localhost` works. `.env.tests` pins `AP_REDIS_HOST=redis` for `docker-compose`, so any test that opens a real connection needs `localhost` forced past it.
diff --git a/brain/knowledge/engineering/server-module-anatomy.md b/brain/knowledge/engineering/server-module-anatomy.md
index 558bb3f8a6b..b31cdc18aaa 100644
--- a/brain/knowledge/engineering/server-module-anatomy.md
+++ b/brain/knowledge/engineering/server-module-anatomy.md
@@ -132,6 +132,8 @@ Verify with `npm run lint-dev` and `npm run test-api`.
**`packages/server/api/test/unit/**` runs in CI since 2026-09 (the `api (ee, unit, migrations)` job, whenever api or worker is affected).** It ran in no pipeline before that and rotted: in Aug 2026, 18 tests across 4 files failed on a clean `main`. The root `npm run test-unit` still skips api; run `npx turbo run test-unit --filter=api`. When a `test/unit` run goes red locally, check `main` before assuming your branch caused it.
## Gotchas
+- **CI `check-migrations` matches foreign keys by name, so an inline `REFERENCES` fails it as drift.** `migration:generate --check` compares FKs by name + `onDelete` (indexes by name + unique + columns; `where` is not compared). An inline FK gets Postgres's auto name. Use a named `ADD CONSTRAINT "fk_<table>_<col>"` in the migration and the same `joinColumn.foreignKeyConstraintName` on the entity relation (copy `1797000000000-AddAiToolConfigTable`).
+- **A plan-gate test can't live in `test/integration/ce/`.** On CE, `platformService.getPlan` returns `OPEN_SOURCE_PLAN` without reading the DB, so `createTestContext(app, { plan: { flag: false } })` has no effect there. Put 402 tests under `ee/` or `cloud/`, where `createMockPlatformPlan` defaults many flags (e.g. `aiProvidersEnabled`) to `false`.
- **A date-range query filter typed `z.string()` turns bad input into a 500, not a 400.** `createdAfter`/`createdBefore` bind straight into a `created >= :createdAfter` comparison against a `timestamp with time zone` column, so `?createdAfter=invalid` reaches PostgreSQL and surfaces as `invalid input syntax for type timestamp with time zone: "invalid"` — an internal error for ordinary malformed input. Type them `z.iso.datetime({ offset: true }).optional()` instead: that accepts everything a caller actually sends (`.toISOString()` and `+02:00` offsets alike) and rejects the garbage at the edge, where `fastify-type-provider-zod` already turns a querystring rejection into a 400. Note `z.string().datetime()` is deprecated in zod v4 — `z.iso.datetime()` is the replacement, and its default is Z-only, so omitting `{ offset: true }` also rejects legitimate offset timestamps. **The loose shape is still on `flow-run`, `audit-events` and health metrics**, so copying a date filter from any of them carries the hole along.
- **`z.iso.datetime()` alone is still a 500: it accepts year `0000`, which PostgreSQL cannot represent.** The ISO grammar's year is `\d{4}`, so `?createdAfter=0000-01-01T00:00:00Z` parses, then `created >= :createdAfter` fails with `date/time field value out of range`. Use `OptionalIsoDateTimeQuery` from `@activepieces/core-utils`, which adds a `val.slice(0, 4) !== '0000'` bound — years `0001`-`9999` are all representable, so that one check closes the whole gap the 4-digit grammar leaves. **Check the literal year, not `new Date(val).getUTCFullYear()`.** The service binds the raw string, so the guard has to judge the string the driver sends; normalising to UTC first pushes a legitimate `0001-01-01T00:00:00+01:00` back into year `0000` and 400s a timestamp PostgreSQL accepts. A test using `0001-01-01T00:00:00Z` passes either way and will not catch it — cover a positive offset. **Binding a JS `Date` instead of the string looks like the better fix and is not one.** `node-postgres` serialises a year-zero `Date` to `0001-01-01 ... BC`, which PostgreSQL accepts, and both a bare `pg` query and an entity-less TypeORM query builder do behave that way — so a scratch reproduction says the bug is gone. Through the real entity-bound query builder the value is ISO-stringified again before it reaches the driver and PostgreSQL rejects it exactly as before. Reject the range at the edge; do not try to fix it at the binding.
- **`z.record()` over an enum key is exhaustive in zod v4 — a sparse map needs `z.partialRecord()`.** `z.record(z.enum(SomeEnum), value)` demands *every* member of the enum and fails with `expected record, received undefined` for each missing key, which is the opposite of the `Partial<Record<Enum, T>>` shape this codebase uses everywhere (provider maps, capability tables, per-edition config). It bit the AI model catalog: the schema wanted all 16 `AIProviderName` members while the real payload carries 13, so validation added to protect production would instead have rejected it on the first fetch. The unit-test fixture passed either way, because fixtures are written to match the schema. **Validate a schema against the real generated artefact, not only against a fixture** — that is the only step that catches this class of bug.
diff --git a/brain/knowledge/platform-editions-ee/platform-configuration.md b/brain/knowledge/platform-editions-ee/platform-configuration.md
index da60246107e..7a73c346733 100644
--- a/brain/knowledge/platform-editions-ee/platform-configuration.md
+++ b/brain/knowledge/platform-editions-ee/platform-configuration.md
@@ -17,6 +17,7 @@ A **Platform** is the top-level tenant namespace in Activepieces. Every install
- `GET /v1/platforms/assets/:id` — public asset download.
### Gotchas
+- **A new platform column breaks the cloud `platform.test.ts` key list.** "Always Returns non-sensitive information for platform" pins `Object.keys(response).sort()` with `toStrictEqual`, so adding a field to `PlatformWithoutSensitiveData` fails `api (cloud)` until the key is added there, in sorted order. It only runs in the cloud suite, so a CE run won't catch it.
- **The platform name is editable on every edition, even though it lives inside the Appearance section.** `appearance-section.tsx` computes `brandingLocked = !platform.plan.customAppearanceEnabled` and passes `disabled={brandingLocked}` to the logo, icon, favicon and theme-colour inputs, but **not** to the `Platform Name` input, and `formdata.append('name', name)` sits outside the `if (!brandingLocked)` block. So a Community or unlicensed platform can rename itself at Settings > Platform > Account > General while every other field on that form is locked. Reading the file top-down makes the whole section look gated; it is per-field. `UpdatePlatformRequestBody.name` is likewise ungated on the API and only validated against `SAFE_STRING_PATTERN` (no `.` or `/`).
- Per-project piece/action/trigger visibility is done via **piece sets**, NOT the platform.
- On GET for USER principals, `plan.chatEnabled` is rewritten to effective per-user chat visibility, and `licenseKey` is nulled for embedded users.
diff --git a/bun.lock b/bun.lock
index ab0e3cb8583..a57116784e6 100644
--- a/bun.lock
+++ b/bun.lock
@@ -165,7 +165,7 @@
},
"packages/core/shared": {
"name": "@activepieces/shared",
- "version": "0.188.0",
+ "version": "0.189.0",
"dependencies": {
"@activepieces/core-execution": "workspace:*",
"@activepieces/core-formula": "workspace:*",
@@ -188,7 +188,7 @@
},
"packages/core/utils": {
"name": "@activepieces/core-utils",
- "version": "0.8.3",
+ "version": "0.8.5",
"dependencies": {
"deepmerge-ts": "8.0.2",
"ipaddr.js": "2.3.0",
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.json
index d6d48e205a8..cbecabd952d 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.188.0",
+ "version": "0.189.0",
"type": "commonjs",
"sideEffects": false,
"main": "./dist/src/index.js",
diff --git a/packages/core/shared/src/lib/management/ai-providers/index.ts b/packages/core/shared/src/lib/management/ai-providers/index.ts
index 8b26f81d0a2..31aba3cb417 100644
--- a/packages/core/shared/src/lib/management/ai-providers/index.ts
+++ b/packages/core/shared/src/lib/management/ai-providers/index.ts
@@ -331,3 +331,5 @@ export {
export type { ActivepiecesChatTier, ActivepiecesImageTier, AIProviderCapabilities, AIWebSearchMode, OpenAiCompatibleVendor } from '@activepieces/core-piece-types'
export const AI_PIECE_COST_BILLING_VERSION = '0.11.0'
+
+export * from './platform-model-tier'
diff --git a/packages/core/shared/src/lib/management/ai-providers/platform-model-tier.ts b/packages/core/shared/src/lib/management/ai-providers/platform-model-tier.ts
new file mode 100644
index 00000000000..f3ae8caf5c5
--- /dev/null
+++ b/packages/core/shared/src/lib/management/ai-providers/platform-model-tier.ts
@@ -0,0 +1,96 @@
+import { AIProviderName, ApId, BaseModelSchema, DateOrString, formErrors, Nullable } from '@activepieces/core-utils'
+import { z } from 'zod'
+
+const LIMITS = {
+ maxEntries: 5,
+ nameMaxLength: 40,
+ descriptionMaxLength: 120,
+ emojiMaxLength: 16,
+ minThinkingBudget: 1024,
+ maxThinkingBudget: 64000,
+} as const
+
+function isOffOrEnoughToThink(budget: number): boolean {
+ return budget === 0 || budget >= LIMITS.minThinkingBudget
+}
+
+function hasNoDuplicateEntries(entries: { configId: string, modelId: string }[]): boolean {
+ return new Set(entries.map((entry) => `${entry.configId}:${entry.modelId}`)).size === entries.length
+}
+
+const TierName = z.string().trim().min(1, formErrors.required).max(LIMITS.nameMaxLength, formErrors.tierNameTooLong)
+const TierEmoji = z.string().min(1, formErrors.required).max(LIMITS.emojiMaxLength, formErrors.invalidEmoji).regex(/^(\p{Extended_Pictographic}|\p{Regional_Indicator})/u, formErrors.invalidEmoji)
+const TierDescription = z.string().trim().max(LIMITS.descriptionMaxLength, formErrors.tierDescriptionTooLong)
+const TierThinkingBudget = z.number().int(formErrors.wholeNumber).max(LIMITS.maxThinkingBudget, formErrors.tierThinkingBudgetInvalid)
+ .refine(isOffOrEnoughToThink, formErrors.tierThinkingBudgetInvalid)
+
+export const PlatformModelTierEntry = z.object({
+ configId: ApId,
+ modelId: z.string().min(1, formErrors.required).max(256),
+})
+
+const TierEntries = z.array(PlatformModelTierEntry)
+ .min(1, formErrors.atLeastOne)
+ .max(LIMITS.maxEntries, formErrors.tierTooManyModels)
+ .refine(hasNoDuplicateEntries, formErrors.tierDuplicateModel)
+
+export const PlatformModelTier = z.object({
+ ...BaseModelSchema,
+ platformId: ApId,
+ name: z.string(),
+ emoji: z.string(),
+ description: Nullable(z.string()),
+ position: z.number().int(),
+ entries: z.array(PlatformModelTierEntry),
+ isDefault: z.boolean(),
+ thinkingBudget: Nullable(z.number().int()),
+ deleted: Nullable(DateOrString),
+ replacedBy: Nullable(ApId),
+})
+
+export const PlatformModelTierSummary = z.object({
+ id: ApId,
+ name: z.string(),
+ emoji: z.string(),
+ description: Nullable(z.string()),
+ position: z.number().int(),
+ isDefault: z.boolean(),
+ mainModel: Nullable(z.object({
+ provider: z.enum(AIProviderName),
+ modelId: z.string(),
+ })),
+ fallbackCount: z.number().int(),
+})
+
+export const CreatePlatformModelTierRequest = z.object({
+ name: TierName,
+ emoji: TierEmoji,
+ description: Nullable(TierDescription),
+ entries: TierEntries,
+ thinkingBudget: Nullable(TierThinkingBudget),
+})
+
+export const UpdatePlatformModelTierRequest = z.object({
+ name: TierName.optional(),
+ emoji: TierEmoji.optional(),
+ description: Nullable(TierDescription),
+ entries: TierEntries.optional(),
+ thinkingBudget: Nullable(TierThinkingBudget),
+ isDefault: z.literal(true).optional(),
+})
+
+export const ReorderPlatformModelTiersRequest = z.object({
+ tierIds: z.array(ApId).min(1, formErrors.atLeastOne),
+})
+
+export const DeletePlatformModelTierRequest = z.object({
+ replacedBy: z.optional(ApId),
+})
+
+export type PlatformModelTierEntry = z.infer<typeof PlatformModelTierEntry>
+export type PlatformModelTier = z.infer<typeof PlatformModelTier>
+export type PlatformModelTierSummary = z.infer<typeof PlatformModelTierSummary>
+export type CreatePlatformModelTierRequest = z.infer<typeof CreatePlatformModelTierRequest>
+export type UpdatePlatformModelTierRequest = z.infer<typeof UpdatePlatformModelTierRequest>
+export type ReorderPlatformModelTiersRequest = z.infer<typeof ReorderPlatformModelTiersRequest>
+export type DeletePlatformModelTierRequest = z.infer<typeof DeletePlatformModelTierRequest>
diff --git a/packages/core/utils/package.json b/packages/core/utils/package.json
index 20638a9b878..6165ede95c7 100644
--- a/packages/core/utils/package.json
+++ b/packages/core/utils/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/core-utils",
- "version": "0.8.3",
+ "version": "0.8.5",
"type": "commonjs",
"main": "./dist/src/index.js",
"scripts": {
diff --git a/packages/core/utils/src/lib/form-errors.ts b/packages/core/utils/src/lib/form-errors.ts
index ab25cb23770..0494e2d4d14 100644
--- a/packages/core/utils/src/lib/form-errors.ts
+++ b/packages/core/utils/src/lib/form-errors.ts
@@ -12,6 +12,12 @@ export const formErrors = {
atLeastOne: 'atLeastOne',
wholeNumber: 'wholeNumber',
atMostTenThousand: 'atMostTenThousand',
+ tierNameTooLong: 'tierNameTooLong',
+ tierDescriptionTooLong: 'tierDescriptionTooLong',
+ invalidEmoji: 'invalidEmoji',
+ tierTooManyModels: 'tierTooManyModels',
+ tierDuplicateModel: 'tierDuplicateModel',
+ tierThinkingBudgetInvalid: 'tierThinkingBudgetInvalid',
} as const
export const SAFE_EXTERNAL_ID_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,128}$/
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 52482bdfcd8..60dbb58242e 100644
--- a/packages/server/api/src/app/ai/ai-provider-service.ts
+++ b/packages/server/api/src/app/ai/ai-provider-service.ts
@@ -4,6 +4,7 @@ import { ActivePiecesProviderAuthConfig, AI_PROVIDER_ENTITY_TYPES, AIProviderAut
import { FastifyBaseLogger } from 'fastify'
import cron from 'node-cron'
import { repoFactory } from '../core/db/repo-factory'
+import { transaction } from '../core/db/transaction'
import { getAiProviderConfirmKey } from '../database/redis/keys'
import { distributedStore } from '../database/redis-connections'
import { openRouterApi } from '../ee/platform/platform-plan/openrouter/openrouter-api'
@@ -12,6 +13,7 @@ import { encryptUtils } from '../helper/encryption'
import { platformService } from '../platform/platform.service'
import { AIProviderEntity, AIProviderSchema } from './ai-provider-entity'
import { aiProviderHealth } from './ai-provider-health'
+import { platformModelTierService } from './platform-model-tier-service'
import { aiProviders } from './providers'
const aiProviderRepo = repoFactory<AIProviderSchema>(AIProviderEntity)
@@ -143,15 +145,22 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({
displayName: request.displayName,
}
- if (request.enabledForChat === true) {
- await aiProviderRepo().manager.transaction(async (manager) => {
+ const changesModelScope = !isNil(request.modelScope) || !isNil(request.modelIds)
+ await transaction(async (manager) => {
+ if (changesModelScope) {
+ await platformModelTierService.assertKeyScopeKeepsTiers({
+ manager,
+ platformId,
+ configId: providerId,
+ modelScope: request.modelScope,
+ modelIds: request.modelIds,
+ })
+ }
+ if (request.enabledForChat === true) {
await manager.update(AIProviderEntity, { platformId }, { enabledForChat: false })
- await manager.update(AIProviderEntity, providerId, updates)
- })
- }
- else {
- await aiProviderRepo().update(providerId, updates)
- }
+ }
+ await manager.update(AIProviderEntity, providerId, updates)
+ })
},
async getChatProviderName({ platformId, scope }: { platformId: PlatformId, scope: ProviderScope }): Promise<AIProviderName | null> {
@@ -181,9 +190,12 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({
},
async delete(platformId: PlatformId, providerId: string): Promise<void> {
- await aiProviderRepo().delete({
- platformId,
- id: providerId,
+ await transaction(async (manager) => {
+ await platformModelTierService.assertKeyCanBeDeleted({ manager, platformId, configId: providerId })
+ await aiProviderRepo(manager).delete({
+ platformId,
+ id: providerId,
+ })
})
},
async recordKeyObservation({ platformId, providerId, signal }: { platformId: PlatformId, providerId: string, signal: ProviderOutcomeSignal }): Promise<void> {
diff --git a/packages/server/api/src/app/ai/platform-model-tier-controller.ts b/packages/server/api/src/app/ai/platform-model-tier-controller.ts
new file mode 100644
index 00000000000..548c0919275
--- /dev/null
+++ b/packages/server/api/src/app/ai/platform-model-tier-controller.ts
@@ -0,0 +1,121 @@
+import { ActivepiecesError, ApId, ErrorCode } from '@activepieces/core-utils'
+import { CreatePlatformModelTierRequest, DeletePlatformModelTierRequest, PlatformModelTier, PlatformModelTierSummary, PrincipalType, ReorderPlatformModelTiersRequest, UpdatePlatformModelTierRequest } from '@activepieces/shared'
+import { FastifyRequest } from 'fastify'
+import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
+import { StatusCodes } from 'http-status-codes'
+import { z } from 'zod'
+import { ProjectResourceType } from '../core/security/authorization/common'
+import { securityAccess } from '../core/security/authorization/fastify-security'
+import { platformService } from '../platform/platform.service'
+import { platformModelTierService } from './platform-model-tier-service'
+
+export const platformModelTierController: FastifyPluginAsyncZod = async (app) => {
+ app.get('/', ListPlatformModelTiers, async (request) => {
+ return platformModelTierService.listSummaries({ platformId: request.principal.platform.id })
+ })
+ app.get('/admin', ListPlatformModelTiersForAdmin, async (request) => {
+ return platformModelTierService.list({ platformId: request.principal.platform.id })
+ })
+ app.post('/', CreatePlatformModelTier, async (request) => {
+ return platformModelTierService.create({ platformId: request.principal.platform.id, request: request.body })
+ })
+ app.post('/reorder', ReorderPlatformModelTiers, async (request) => {
+ return platformModelTierService.reorder({ platformId: request.principal.platform.id, tierIds: request.body.tierIds })
+ })
+ app.post('/:id', UpdatePlatformModelTier, async (request) => {
+ return platformModelTierService.update({ platformId: request.principal.platform.id, id: request.params.id, request: request.body })
+ })
+ app.delete('/:id', DeletePlatformModelTier, async (request, reply) => {
+ await platformModelTierService.delete({ platformId: request.principal.platform.id, id: request.params.id, replacedBy: request.query.replacedBy })
+ return reply.status(StatusCodes.NO_CONTENT).send()
+ })
+}
+
+async function requireAiProvidersPlan(request: FastifyRequest): Promise<void> {
+ const platform = await platformService(request.log).getOneWithPlanOrThrow(request.principal.platform.id)
+ if (!platform.plan.aiProvidersEnabled) {
+ throw new ActivepiecesError({
+ code: ErrorCode.FEATURE_DISABLED,
+ params: { message: 'AI providers are not included in your plan' },
+ })
+ }
+}
+
+const TierIdParams = z.object({
+ id: ApId,
+})
+
+const ListPlatformModelTiers = {
+ config: {
+ security: securityAccess.project([PrincipalType.USER, PrincipalType.ENGINE], undefined, { type: ProjectResourceType.QUERY }),
+ },
+ schema: {
+ querystring: z.object({
+ projectId: z.string().optional(),
+ }),
+ response: {
+ [StatusCodes.OK]: z.array(PlatformModelTierSummary),
+ },
+ },
+}
+
+const ListPlatformModelTiersForAdmin = {
+ config: {
+ security: securityAccess.platformAdminOnly([PrincipalType.USER]),
+ },
+ schema: {
+ response: {
+ [StatusCodes.OK]: z.array(PlatformModelTier),
+ },
+ },
+}
+
+const CreatePlatformModelTier = {
+ config: {
+ security: securityAccess.platformAdminOnly([PrincipalType.USER]),
+ },
+ preHandler: requireAiProvidersPlan,
+ schema: {
+ body: CreatePlatformModelTierRequest,
+ response: {
+ [StatusCodes.OK]: PlatformModelTier,
+ },
+ },
+}
+
+const ReorderPlatformModelTiers = {
+ config: {
+ security: securityAccess.platformAdminOnly([PrincipalType.USER]),
+ },
+ preHandler: requireAiProvidersPlan,
+ schema: {
+ body: ReorderPlatformModelTiersRequest,
+ response: {
+ [StatusCodes.OK]: z.array(PlatformModelTier),
+ },
+ },
+}
+
+const UpdatePlatformModelTier = {
+ config: {
+ security: securityAccess.platformAdminOnly([PrincipalType.USER]),
+ },
+ preHandler: requireAiProvidersPlan,
+ schema: {
+ params: TierIdParams,
+ body: UpdatePlatformModelTierRequest,
+ response: {
+ [StatusCodes.OK]: PlatformModelTier,
+ },
+ },
+}
+
+const DeletePlatformModelTier = {
+ config: {
+ security: securityAccess.platformAdminOnly([PrincipalType.USER]),
+ },
+ schema: {
+ params: TierIdParams,
+ querystring: DeletePlatformModelTierRequest,
+ },
+}
diff --git a/packages/server/api/src/app/ai/platform-model-tier-entity.ts b/packages/server/api/src/app/ai/platform-model-tier-entity.ts
new file mode 100644
index 00000000000..7b032035167
--- /dev/null
+++ b/packages/server/api/src/app/ai/platform-model-tier-entity.ts
@@ -0,0 +1,87 @@
+import { Platform, PlatformModelTier } from '@activepieces/shared'
+import { EntitySchema } from 'typeorm'
+import { ApIdSchema, BaseColumnSchemaPart } from '../database/database-common'
+
+export type PlatformModelTierSchema = PlatformModelTier & {
+ platform: Platform
+}
+
+export const PlatformModelTierEntity = new EntitySchema<PlatformModelTierSchema>({
+ name: 'platform_model_tier',
+ columns: {
+ ...BaseColumnSchemaPart,
+ platformId: {
+ ...ApIdSchema,
+ nullable: false,
+ },
+ name: {
+ type: String,
+ nullable: false,
+ },
+ emoji: {
+ type: String,
+ nullable: false,
+ },
+ description: {
+ type: String,
+ nullable: true,
+ },
+ position: {
+ type: Number,
+ nullable: false,
+ default: 0,
+ },
+ entries: {
+ type: 'jsonb',
+ nullable: false,
+ },
+ isDefault: {
+ type: Boolean,
+ nullable: false,
+ default: false,
+ },
+ thinkingBudget: {
+ type: Number,
+ nullable: true,
+ },
+ deleted: {
+ type: 'timestamp with time zone',
+ deleteDate: true,
+ nullable: true,
+ },
+ replacedBy: {
+ ...ApIdSchema,
+ nullable: true,
+ },
+ },
+ indices: [
+ {
+ name: 'idx_platform_model_tier_platform_id',
+ columns: ['platformId'],
+ },
+ {
+ name: 'idx_platform_model_tier_platform_name_live',
+ columns: ['platformId', 'name'],
+ unique: true,
+ synchronize: false,
+ },
+ {
+ name: 'idx_platform_model_tier_platform_default',
+ columns: ['platformId'],
+ unique: true,
+ where: '"isDefault" = true AND "deleted" IS NULL',
+ },
+ ],
+ relations: {
+ platform: {
+ type: 'many-to-one',
+ target: 'platform',
+ cascade: true,
+ onDelete: 'CASCADE',
+ joinColumn: {
+ name: 'platformId',
+ foreignKeyConstraintName: 'fk_platform_model_tier_platform_id',
+ },
+ },
+ },
+})
diff --git a/packages/server/api/src/app/ai/platform-model-tier-service.ts b/packages/server/api/src/app/ai/platform-model-tier-service.ts
new file mode 100644
index 00000000000..1ef9c905a1f
--- /dev/null
+++ b/packages/server/api/src/app/ai/platform-model-tier-service.ts
@@ -0,0 +1,260 @@
+import { ActivepiecesError, AIProviderName, apId, ErrorCode, isNil, PlatformId, spreadIfDefined, spreadIfNotUndefined, unique } from '@activepieces/core-utils'
+import { AiProviderModelScope, CreatePlatformModelTierRequest, PlatformModelTier, PlatformModelTierEntry, PlatformModelTierSummary, UpdatePlatformModelTierRequest } from '@activepieces/shared'
+import { EntityManager, In } from 'typeorm'
+import { repoFactory } from '../core/db/repo-factory'
+import { transaction } from '../core/db/transaction'
+import { isUniqueViolation } from '../core/db/unique-violation'
+import { AIProviderEntity, AIProviderSchema } from './ai-provider-entity'
+import { PlatformModelTierEntity, PlatformModelTierSchema } from './platform-model-tier-entity'
+
+const tierRepo = repoFactory<PlatformModelTierSchema>(PlatformModelTierEntity)
+const aiProviderRepo = repoFactory<AIProviderSchema>(AIProviderEntity)
+
+const MAX_LIVE_TIERS = 50
+
+export const platformModelTierService = {
+ async listSummaries({ platformId }: { platformId: PlatformId }): Promise<PlatformModelTierSummary[]> {
+ const tiers = await listLive({ platformId })
+ const mainConfigIds = unique(tiers.flatMap((tier) => tier.entries.slice(0, 1).map((entry) => entry.configId)))
+ const keys = mainConfigIds.length === 0 ? [] : await aiProviderRepo().findBy({ platformId, id: In(mainConfigIds) })
+ const providerByConfigId = new Map(keys.map((key) => [key.id, key.provider]))
+ return tiers.map((tier) => toSummary({ tier, providerByConfigId }))
+ },
+
+ async list({ platformId }: { platformId: PlatformId }): Promise<PlatformModelTier[]> {
+ return listLive({ platformId })
+ },
+
+ async create({ platformId, request }: { platformId: PlatformId, request: CreatePlatformModelTierRequest }): Promise<PlatformModelTier> {
+ return withNameConflictAsValidation(() => transaction(async (manager) => {
+ await lockPlatform({ manager, platformId })
+ await assertEntriesValid({ manager, platformId, entries: request.entries })
+ const live = await listLive({ platformId, manager })
+ if (live.length >= MAX_LIVE_TIERS) {
+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: `A platform can have at most ${MAX_LIVE_TIERS} tiers` } })
+ }
+ assertNameIsFree({ live, name: request.name })
+ const isFirstTier = live.length === 0
+ const position = live.reduce((max, tier) => Math.max(max, tier.position + 1), 0)
+ return tierRepo(manager).save({
+ id: apId(),
+ platformId,
+ name: request.name,
+ emoji: request.emoji,
+ description: request.description ?? null,
+ position,
+ entries: request.entries,
+ thinkingBudget: request.thinkingBudget ?? null,
+ isDefault: isFirstTier,
+ deleted: null,
+ replacedBy: null,
+ })
+ }))
+ },
+
+ async update({ platformId, id, request }: { platformId: PlatformId, id: string, request: UpdatePlatformModelTierRequest }): Promise<PlatformModelTier> {
+ return withNameConflictAsValidation(() => transaction(async (manager) => {
+ await lockPlatform({ manager, platformId })
+ const tier = await getLiveOrThrow({ manager, platformId, id })
+ if (!isNil(request.name)) {
+ assertNameIsFree({ live: await listLive({ platformId, manager }), name: request.name, exceptId: id })
+ }
+ if (!isNil(request.entries)) {
+ await assertEntriesValid({ manager, platformId, entries: request.entries })
+ }
+ if (request.isDefault === true && !tier.isDefault) {
+ await tierRepo(manager).update({ platformId, isDefault: true }, { isDefault: false })
+ }
+ await tierRepo(manager).update({ platformId, id }, {
+ ...spreadIfDefined('name', request.name),
+ ...spreadIfDefined('emoji', request.emoji),
+ ...spreadIfNotUndefined('description', request.description),
+ ...spreadIfDefined('entries', request.entries),
+ ...spreadIfNotUndefined('thinkingBudget', request.thinkingBudget),
+ ...spreadIfDefined('isDefault', request.isDefault),
+ })
+ return getLiveOrThrow({ manager, platformId, id })
+ }))
+ },
+
+ async reorder({ platformId, tierIds }: { platformId: PlatformId, tierIds: string[] }): Promise<PlatformModelTier[]> {
+ return transaction(async (manager) => {
+ await lockPlatform({ manager, platformId })
+ const live = await listLive({ platformId, manager })
+ const liveIds = new Set(live.map((tier) => tier.id))
+ const sameSet = tierIds.length === liveIds.size && new Set(tierIds).size === tierIds.length && tierIds.every((id) => liveIds.has(id))
+ if (!sameSet) {
+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: 'Reorder must list every tier exactly once' } })
+ }
+ await manager.query(
+ `
+ UPDATE "platform_model_tier" AS t
+ SET "position" = ordering.ord - 1
+ FROM unnest($1::text[]) WITH ORDINALITY AS ordering(id, ord)
+ WHERE t."id" = ordering.id
+ AND t."platformId" = $2
+ AND t."deleted" IS NULL
+ AND t."position" IS DISTINCT FROM ordering.ord - 1
+ `,
+ [tierIds, platformId],
+ )
+ return listLive({ platformId, manager })
+ })
+ },
+
+ async delete({ platformId, id, replacedBy }: { platformId: PlatformId, id: string, replacedBy: string | undefined }): Promise<void> {
+ if (replacedBy === id) {
+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: 'A tier cannot replace itself' } })
+ }
+ await transaction(async (manager) => {
+ await lockPlatform({ manager, platformId })
+ const tier = await getLiveOrThrow({ manager, platformId, id })
+ if (isNil(replacedBy)) {
+ await assertLastTierCanGo({ manager, platformId })
+ await tierRepo(manager).update({ platformId, id }, { isDefault: false })
+ await tierRepo(manager).softDelete({ platformId, id })
+ return
+ }
+ await getLiveOrThrow({ manager, platformId, id: replacedBy })
+ await manager.query(
+ 'UPDATE "platform_model_tier" SET "replacedBy" = $1 WHERE "platformId" = $2 AND ("id" = $3 OR "replacedBy" = $3)',
+ [replacedBy, platformId, id],
+ )
+ await tierRepo(manager).update({ platformId, id }, { isDefault: false })
+ await tierRepo(manager).softDelete({ platformId, id })
+ if (tier.isDefault) {
+ await tierRepo(manager).update({ platformId, id: replacedBy }, { isDefault: true })
+ }
+ })
+ },
+
+ async assertKeyCanBeDeleted({ manager, platformId, configId }: { manager: EntityManager, platformId: PlatformId, configId: string }): Promise<void> {
+ await lockPlatform({ manager, platformId })
+ const tiers = await findLiveTiersUsingKey({ manager, platformId, configId })
+ if (tiers.length > 0) {
+ throw keyInUseError({ tierNames: tiers.map((tier) => tier.name) })
+ }
+ },
+
+ async assertKeyScopeKeepsTiers({ manager, platformId, configId, modelScope, modelIds }: AssertKeyScopeParams): Promise<void> {
+ await lockPlatform({ manager, platformId })
+ const key = await aiProviderRepo(manager).findOneBy({ platformId, id: configId })
+ if (isNil(key)) {
+ throw new ActivepiecesError({ code: ErrorCode.ENTITY_NOT_FOUND, params: { entityId: configId, entityType: 'ai_provider' } })
+ }
+ const nextScope = { modelScope: modelScope ?? key.modelScope, modelIds: modelIds ?? key.modelIds }
+ const tiers = await findLiveTiersUsingKey({ manager, platformId, configId })
+ const broken = tiers.filter((tier) => tier.entries.some((entry) => entry.configId === configId && !scopeAllows({ ...nextScope, modelId: entry.modelId })))
+ if (broken.length > 0) {
+ throw keyInUseError({ tierNames: broken.map((tier) => tier.name) })
+ }
+ },
+}
+
+async function lockPlatform({ manager, platformId }: { manager: EntityManager, platformId: PlatformId }): Promise<void> {
+ const rows: unknown[] = await manager.query(
+ 'SELECT 1 FROM "platform" WHERE "id" = $1 FOR NO KEY UPDATE',
+ [platformId],
+ )
+ if (rows.length === 0) {
+ throw new ActivepiecesError({ code: ErrorCode.ENTITY_NOT_FOUND, params: { entityId: platformId, entityType: 'platform' } })
+ }
+}
+
+async function listLive({ platformId, manager }: { platformId: PlatformId, manager?: EntityManager }): Promise<PlatformModelTier[]> {
+ return tierRepo(manager).find({ where: { platformId }, order: { position: 'ASC', created: 'ASC' }, take: MAX_LIVE_TIERS })
+}
+
+async function getLiveOrThrow({ platformId, id, manager }: { platformId: PlatformId, id: string, manager?: EntityManager }): Promise<PlatformModelTier> {
+ const tier = await tierRepo(manager).findOneBy({ platformId, id })
+ if (isNil(tier)) {
+ throw new ActivepiecesError({ code: ErrorCode.ENTITY_NOT_FOUND, params: { entityId: id, entityType: 'platform_model_tier' } })
+ }
+ return tier
+}
+
+async function assertLastTierCanGo({ manager, platformId }: { manager: EntityManager, platformId: PlatformId }): Promise<void> {
+ const live = await listLive({ platformId, manager })
+ if (live.length > 1) {
+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: 'Pick a tier to move this tier\'s users to' } })
+ }
+}
+
+function assertNameIsFree({ live, name, exceptId }: { live: PlatformModelTier[], name: string, exceptId?: string }): void {
+ const taken = live.some((tier) => tier.id !== exceptId && tier.name.toLowerCase() === name.toLowerCase())
+ if (taken) {
+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: 'A tier with this name already exists' } })
+ }
+}
+
+async function assertEntriesValid({ manager, platformId, entries }: { manager: EntityManager, platformId: PlatformId, entries: PlatformModelTierEntry[] }): Promise<void> {
+ const configIds = unique(entries.map((entry) => entry.configId))
+ const keys = await aiProviderRepo(manager).findBy({ platformId, id: In(configIds) })
+ const keyById = new Map(keys.map((key) => [key.id, key]))
+ for (const entry of entries) {
+ const key = keyById.get(entry.configId)
+ if (isNil(key)) {
+ throw new ActivepiecesError({ code: ErrorCode.ENTITY_NOT_FOUND, params: { entityId: entry.configId, entityType: 'ai_provider' } })
+ }
+ if (key.provider === AIProviderName.ACTIVEPIECES) {
+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: 'Tiers cannot use the Activepieces credits key' } })
+ }
+ if (!scopeAllows({ modelScope: key.modelScope, modelIds: key.modelIds, modelId: entry.modelId })) {
+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: `Key "${key.displayName}" does not allow model ${entry.modelId}` } })
+ }
+ }
+}
+
+async function findLiveTiersUsingKey({ manager, platformId, configId }: { manager: EntityManager, platformId: PlatformId, configId: string }): Promise<PlatformModelTier[]> {
+ return tierRepo(manager).createQueryBuilder('tier')
+ .where('tier."platformId" = :platformId', { platformId })
+ .andWhere('tier."deleted" IS NULL')
+ .andWhere('tier."entries" @> :needle::jsonb', { needle: JSON.stringify([{ configId }]) })
+ .getMany()
+}
+
+async function withNameConflictAsValidation<T>(operation: () => Promise<T>): Promise<T> {
+ try {
+ return await operation()
+ }
+ catch (error) {
+ if (isUniqueViolation(error)) {
+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: 'A tier with this name already exists' } })
+ }
+ throw error
+ }
+}
+
+function scopeAllows({ modelScope, modelIds, modelId }: { modelScope: AiProviderModelScope, modelIds: string[], modelId: string }): boolean {
+ return modelScope !== 'selected' || modelIds.includes(modelId)
+}
+
+function keyInUseError({ tierNames }: { tierNames: string[] }): ActivepiecesError {
+ return new ActivepiecesError({
+ code: ErrorCode.VALIDATION,
+ params: { message: `This key is used by tiers: ${tierNames.join(', ')}. Remove it from them first.` },
+ })
+}
+
+function toSummary({ tier, providerByConfigId }: { tier: PlatformModelTier, providerByConfigId: Map<string, AIProviderName> }): PlatformModelTierSummary {
+ const main = tier.entries[0]
+ const provider = isNil(main) ? undefined : providerByConfigId.get(main.configId)
+ return {
+ id: tier.id,
+ name: tier.name,
+ emoji: tier.emoji,
+ description: tier.description ?? null,
+ position: tier.position,
+ isDefault: tier.isDefault,
+ mainModel: isNil(main) || isNil(provider) ? null : { provider, modelId: main.modelId },
+ fallbackCount: Math.max(tier.entries.length - 1, 0),
+ }
+}
+
+type AssertKeyScopeParams = {
+ manager: EntityManager
+ platformId: PlatformId
+ configId: string
+ modelScope: AiProviderModelScope | undefined
+ modelIds: string[] | undefined
+}
diff --git a/packages/server/api/src/app/ai/platform-model-tier.module.ts b/packages/server/api/src/app/ai/platform-model-tier.module.ts
new file mode 100644
index 00000000000..5ea32b8d88b
--- /dev/null
+++ b/packages/server/api/src/app/ai/platform-model-tier.module.ts
@@ -0,0 +1,6 @@
+import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
+import { platformModelTierController } from './platform-model-tier-controller'
+
+export const platformModelTierModule: FastifyPluginAsyncZod = async (app) => {
+ await app.register(platformModelTierController, { prefix: '/v1/platform-model-tiers' })
+}
diff --git a/packages/server/api/src/app/app.ts b/packages/server/api/src/app/app.ts
index eb72b56968d..f7cf77e54b8 100644
--- a/packages/server/api/src/app/app.ts
+++ b/packages/server/api/src/app/app.ts
@@ -16,6 +16,7 @@ import { aiProviderModule } from './ai/ai-provider.module'
import { aiToolConfigModule } from './ai/ai-tool-config.module'
import { aiUsageHooks } from './ai/ai-usage-hooks'
import { aiUsageService } from './ai/ai-usage-service'
+import { platformModelTierModule } from './ai/platform-model-tier.module'
import { platformAnalyticsModule } from './analytics/platform-analytics.module'
import { setPlatformOAuthService } from './app-connection/app-connection-service/oauth2'
import { appConnectionModule } from './app-connection/app-connection.module'
@@ -266,6 +267,7 @@ export const setupApp = async (app: FastifyInstance): Promise<FastifyInstance> =
await app.register(oidcModule)
await aiProviderService(app.log).setup()
await app.register(aiProviderModule)
+ await app.register(platformModelTierModule)
await app.register(licenseKeyUsageReportModule)
await app.register(tablesModule)
await app.register(knowledgeBaseModule)
diff --git a/packages/server/api/src/app/database/database-connection.ts b/packages/server/api/src/app/database/database-connection.ts
index ddae7360533..c5aeb156f92 100644
--- a/packages/server/api/src/app/database/database-connection.ts
+++ b/packages/server/api/src/app/database/database-connection.ts
@@ -5,6 +5,7 @@ import {
} from 'typeorm'
import { AIProviderEntity } from '../ai/ai-provider-entity'
import { AiToolConfigEntity } from '../ai/ai-tool-config-entity'
+import { PlatformModelTierEntity } from '../ai/platform-model-tier-entity'
import { PlatformAnalyticsReportEntity } from '../analytics/platform-analytics-report.entity'
import { AppConnectionEntity } from '../app-connection/app-connection.entity'
import { OtpEntity } from '../authentication/otp/otp-entity'
@@ -96,6 +97,7 @@ function getEntities(): EntitySchema<unknown>[] {
UserInvitationEntity,
AIProviderEntity,
AiToolConfigEntity,
+ PlatformModelTierEntity,
ProjectRoleEntity,
TableEntity,
FieldEntity,
diff --git a/packages/server/api/src/app/database/migration/postgres/1859000000000-AddPlatformModelTier.ts b/packages/server/api/src/app/database/migration/postgres/1859000000000-AddPlatformModelTier.ts
new file mode 100644
index 00000000000..15e9e2f985a
--- /dev/null
+++ b/packages/server/api/src/app/database/migration/postgres/1859000000000-AddPlatformModelTier.ts
@@ -0,0 +1,60 @@
+import { QueryRunner } from 'typeorm'
+import { Migration } from '../../migration'
+
+export class AddPlatformModelTier1859000000000 implements Migration {
+ name = 'AddPlatformModelTier1859000000000'
+ breaking = false
+ release = '0.93.0'
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`
+ CREATE TABLE "platform_model_tier" (
+ "id" character varying(21) NOT NULL,
+ "created" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ "updated" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ "platformId" character varying(21) NOT NULL,
+ "name" character varying NOT NULL,
+ "emoji" character varying NOT NULL,
+ "description" character varying,
+ "position" integer NOT NULL DEFAULT 0,
+ "entries" jsonb NOT NULL,
+ "isDefault" boolean NOT NULL DEFAULT false,
+ "thinkingBudget" integer,
+ "deleted" TIMESTAMP WITH TIME ZONE,
+ "replacedBy" character varying(21),
+ CONSTRAINT "PK_platform_model_tier" PRIMARY KEY ("id")
+ )
+ `)
+ await queryRunner.query(`
+ CREATE INDEX "idx_platform_model_tier_platform_id" ON "platform_model_tier" ("platformId")
+ `)
+ await queryRunner.query(`
+ CREATE UNIQUE INDEX "idx_platform_model_tier_platform_name_live" ON "platform_model_tier" ("platformId", lower("name")) WHERE "deleted" IS NULL
+ `)
+ await queryRunner.query(`
+ CREATE UNIQUE INDEX "idx_platform_model_tier_platform_default" ON "platform_model_tier" ("platformId") WHERE "isDefault" = true AND "deleted" IS NULL
+ `)
+ await queryRunner.query(`
+ ALTER TABLE "platform_model_tier"
+ ADD CONSTRAINT "fk_platform_model_tier_platform_id" FOREIGN KEY ("platformId") REFERENCES "platform"("id") ON DELETE CASCADE ON UPDATE NO ACTION
+ `)
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`
+ ALTER TABLE "platform_model_tier" DROP CONSTRAINT "fk_platform_model_tier_platform_id"
+ `)
+ await queryRunner.query(`
+ DROP INDEX "idx_platform_model_tier_platform_default"
+ `)
+ await queryRunner.query(`
+ DROP INDEX "idx_platform_model_tier_platform_name_live"
+ `)
+ await queryRunner.query(`
+ DROP INDEX "idx_platform_model_tier_platform_id"
+ `)
+ await queryRunner.query(`
+ DROP TABLE "platform_model_tier"
+ `)
+ }
+}
diff --git a/packages/server/api/src/app/database/postgres-connection.ts b/packages/server/api/src/app/database/postgres-connection.ts
index 127bcff6cd9..95a4f7ba471 100644
--- a/packages/server/api/src/app/database/postgres-connection.ts
+++ b/packages/server/api/src/app/database/postgres-connection.ts
@@ -447,6 +447,7 @@ import { FlowExternalIdUniqueIgnoresDeleting1855000000000 } from './migration/po
import { AddFlowTombstoneIndex1856000000000 } from './migration/postgres/1856000000000-AddFlowTombstoneIndex'
import { AddWaitpointDeadLetteredAt1857000000000 } from './migration/postgres/1857000000000-AddWaitpointDeadLetteredAt'
import { AddAgentFolderId1858000000000 } from './migration/postgres/1858000000000-AddAgentFolderId'
+import { AddPlatformModelTier1859000000000 } from './migration/postgres/1859000000000-AddPlatformModelTier'
const getSslConfig = (): boolean | TlsOptions => {
const useSsl = system.get(AppSystemProp.POSTGRES_USE_SSL)
@@ -909,6 +910,7 @@ export const getMigrations = (): (new () => Migration)[] => {
AddFlowTombstoneIndex1856000000000,
AddWaitpointDeadLetteredAt1857000000000,
AddAgentFolderId1858000000000,
+ AddPlatformModelTier1859000000000,
]
return migrations
}
diff --git a/packages/server/api/test/integration/ce/ai-provider/platform-model-tier.test.ts b/packages/server/api/test/integration/ce/ai-provider/platform-model-tier.test.ts
new file mode 100644
index 00000000000..77ecdb6883e
--- /dev/null
+++ b/packages/server/api/test/integration/ce/ai-provider/platform-model-tier.test.ts
@@ -0,0 +1,327 @@
+import { AIProviderName, apId } from '@activepieces/core-utils'
+import { DefaultProjectRole, PlatformModelTier, PrincipalType } from '@activepieces/shared'
+import { FastifyInstance } from 'fastify'
+import { StatusCodes } from 'http-status-codes'
+import { databaseConnection } from '../../../../src/app/database/database-connection'
+import { generateMockToken } from '../../../helpers/auth'
+import { db } from '../../../helpers/db'
+import { mockAndSaveAIProvider } from '../../../helpers/mocks'
+import { createMemberContext, createTestContext, TestContext } from '../../../helpers/test-context'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance | null = null
+let ctx: TestContext
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+beforeEach(async () => {
+ ctx = await createTestContext(app!)
+})
+
+describe('Platform model tiers API', () => {
+ describe('create', () => {
+ it('makes the first tier default and appends positions', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ const first = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'Fast' }) })
+ const second = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'Expert' }) })
+
+ expect(first).toMatchObject({ isDefault: true, position: 0, emoji: '⚡' })
+ expect(second).toMatchObject({ isDefault: false, position: 1 })
+ })
+
+ it('rejects bad entry counts and duplicate entries', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ const entry = { configId: key.id, modelId: 'gpt-4o' }
+ const tooMany = Array.from({ length: 6 }, (_, i) => ({ configId: key.id, modelId: `model-${i}` }))
+
+ const empty = await ctx.post(TIERS, tierBody({ configId: key.id, entries: [] }))
+ const overLimit = await ctx.post(TIERS, tierBody({ configId: key.id, entries: tooMany }))
+ const duplicate = await ctx.post(TIERS, tierBody({ configId: key.id, entries: [entry, entry] }))
+
+ expect(empty.statusCode).toBe(StatusCodes.BAD_REQUEST)
+ expect(overLimit.statusCode).toBe(StatusCodes.BAD_REQUEST)
+ expect(duplicate.statusCode).toBe(StatusCodes.BAD_REQUEST)
+ })
+
+ it('rejects a key from another platform', async () => {
+ const otherCtx = await createTestContext(app!)
+ const foreignKey = await seedKey({ testCtx: otherCtx })
+
+ const response = await ctx.post(TIERS, tierBody({ configId: foreignKey.id }))
+
+ expect(response.statusCode).toBe(StatusCodes.NOT_FOUND)
+ })
+
+ it('rejects the Activepieces credits key', async () => {
+ const managed = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.ACTIVEPIECES })
+
+ const response = await ctx.post(TIERS, tierBody({ configId: managed.id }))
+
+ expect(response.statusCode).toBe(StatusCodes.CONFLICT)
+ })
+
+ it('rejects a model the key does not allow', async () => {
+ const key = await seedKey({ testCtx: ctx, modelScope: 'selected', modelIds: ['allowed-model'] })
+
+ const blocked = await ctx.post(TIERS, tierBody({ configId: key.id, entries: [{ configId: key.id, modelId: 'other-model' }] }))
+ const allowed = await ctx.post(TIERS, tierBody({ configId: key.id, entries: [{ configId: key.id, modelId: 'allowed-model' }] }))
+
+ expect(blocked.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(allowed.statusCode).toBe(StatusCodes.OK)
+ })
+
+ it('stores a thinking budget and rejects one too small to think', async () => {
+ const key = await seedKey({ testCtx: ctx })
+
+ const saved = await createTier({ testCtx: ctx, body: { ...tierBody({ configId: key.id }), thinkingBudget: 2048 } })
+ const tooSmall = await ctx.post(TIERS, { ...tierBody({ configId: key.id, name: 'Other' }), thinkingBudget: 500 })
+ const cleared = await ctx.post(`${TIERS}/${saved.id}`, { thinkingBudget: null })
+
+ expect(saved.thinkingBudget).toBe(2048)
+ expect(tooSmall.statusCode).toBe(StatusCodes.BAD_REQUEST)
+ expect(cleared.json().thinkingBudget).toBeNull()
+ })
+
+ it('rejects a duplicate live name and frees it after delete', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ const first = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'Fast' }) })
+ const other = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'Other' }) })
+
+ const duplicate = await ctx.post(TIERS, tierBody({ configId: key.id, name: 'Fast' }))
+ await ctx.delete(`${TIERS}/${first.id}`, { replacedBy: other.id })
+ const reused = await ctx.post(TIERS, tierBody({ configId: key.id, name: 'Fast' }))
+
+ expect(duplicate.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(reused.statusCode).toBe(StatusCodes.OK)
+ })
+
+ it('rejects a name that differs only in case', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ const tier = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'Fast' }) })
+ await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'Other' }) })
+
+ const created = await ctx.post(TIERS, tierBody({ configId: key.id, name: 'fast' }))
+ const renamed = await ctx.post(`${TIERS}/${tier.id}`, { name: 'OTHER' })
+ const sameTier = await ctx.post(`${TIERS}/${tier.id}`, { name: 'FAST' })
+
+ expect(created.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(renamed.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(sameTier.statusCode).toBe(StatusCodes.OK)
+ })
+
+ it('caps a platform at 50 live tiers', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ await db.save('platform_model_tier', Array.from({ length: 50 }, (_, i) => ({
+ id: apId(),
+ platformId: ctx.platform.id,
+ name: `Tier ${i}`,
+ emoji: '⚡',
+ position: i,
+ entries: [{ configId: key.id, modelId: 'gpt-4o' }],
+ isDefault: i === 0,
+ })))
+
+ const response = await ctx.post(TIERS, tierBody({ configId: key.id, name: 'One too many' }))
+
+ expect(response.statusCode).toBe(StatusCodes.CONFLICT)
+ })
+
+ it('keeps exactly one default when two first tiers are created at once', async () => {
+ const key = await seedKey({ testCtx: ctx })
+
+ const responses = await Promise.all([
+ ctx.post(TIERS, tierBody({ configId: key.id, name: 'One' })),
+ ctx.post(TIERS, tierBody({ configId: key.id, name: 'Two' })),
+ ])
+ const tiers = await listAdmin({ testCtx: ctx })
+
+ expect(responses.map((response) => response.statusCode)).toEqual([StatusCodes.OK, StatusCodes.OK])
+ expect(tiers.filter((tier) => tier.isDefault)).toHaveLength(1)
+ })
+ })
+
+ describe('update and reorder', () => {
+ it('moves the default pointer', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ const first = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'A' }) })
+ const second = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'B' }) })
+
+ const response = await ctx.post(`${TIERS}/${second.id}`, { isDefault: true, name: 'B2' })
+ const tiers = await listAdmin({ testCtx: ctx })
+
+ expect(response.statusCode).toBe(StatusCodes.OK)
+ expect(tiers.find((tier) => tier.id === first.id)).toMatchObject({ isDefault: false })
+ expect(tiers.find((tier) => tier.id === second.id)).toMatchObject({ isDefault: true, name: 'B2' })
+ })
+
+ it('reorders only with the exact live set', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ const a = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'A' }) })
+ const b = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'B' }) })
+
+ const partial = await ctx.post(`${TIERS}/reorder`, { tierIds: [b.id] })
+ const full = await ctx.post(`${TIERS}/reorder`, { tierIds: [b.id, a.id] })
+
+ expect(partial.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(full.statusCode).toBe(StatusCodes.OK)
+ expect(full.json().map((tier: PlatformModelTier) => tier.id)).toEqual([b.id, a.id])
+ })
+ })
+
+ describe('isolation and access', () => {
+ it('hides one platform\'s tiers from another platform', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ const tier = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id }) })
+ const otherCtx = await createTestContext(app!)
+
+ const list = await otherCtx.get(`${TIERS}/admin`)
+ const update = await otherCtx.post(`${TIERS}/${tier.id}`, { name: 'Stolen' })
+ const remove = await otherCtx.delete(`${TIERS}/${tier.id}`, { replacedBy: apId() })
+ const reorder = await otherCtx.post(`${TIERS}/reorder`, { tierIds: [tier.id] })
+
+ expect(list.json()).toEqual([])
+ expect(update.statusCode).toBe(StatusCodes.NOT_FOUND)
+ expect(remove.statusCode).toBe(StatusCodes.NOT_FOUND)
+ expect(reorder.statusCode).toBe(StatusCodes.CONFLICT)
+ })
+
+ it('lets project members and the engine read the slim list only', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ await createTier({ testCtx: ctx, body: tierBody({ configId: key.id }) })
+ const member = await createMemberContext(app!, ctx, { projectRole: DefaultProjectRole.EDITOR })
+ const engineToken = await generateMockToken({ type: PrincipalType.ENGINE, id: apId(), projectId: ctx.project.id, platform: { id: ctx.platform.id } })
+
+ const memberList = await member.get(TIERS, { projectId: ctx.project.id })
+ const engineList = await app!.inject({ method: 'GET', url: `/api${TIERS}`, headers: { authorization: `Bearer ${engineToken}` } })
+ const memberAdmin = await member.get(`${TIERS}/admin`)
+ const memberCreate = await member.post(TIERS, tierBody({ configId: key.id, name: 'Member' }))
+
+ expect(memberList.statusCode).toBe(StatusCodes.OK)
+ expect(engineList.statusCode).toBe(StatusCodes.OK)
+ expect(memberList.json()[0]).toMatchObject({ mainModel: { provider: AIProviderName.CUSTOM, modelId: 'gpt-4o' }, fallbackCount: 0 })
+ expect(memberList.body).not.toContain(key.id)
+ expect(memberAdmin.statusCode).toBe(StatusCodes.FORBIDDEN)
+ expect(memberCreate.statusCode).toBe(StatusCodes.FORBIDDEN)
+ })
+ })
+
+ describe('delete', () => {
+ it('flattens the replacement chain and moves the default pointer', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ const a = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'A' }) })
+ const b = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'B' }) })
+ const c = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'C' }) })
+
+ const first = await ctx.delete(`${TIERS}/${a.id}`, { replacedBy: b.id })
+ const second = await ctx.delete(`${TIERS}/${b.id}`, { replacedBy: c.id })
+ const oldA = await findWithDeleted({ id: a.id })
+ const live = await listAdmin({ testCtx: ctx })
+
+ expect(first.statusCode).toBe(StatusCodes.NO_CONTENT)
+ expect(second.statusCode).toBe(StatusCodes.NO_CONTENT)
+ expect(oldA).toMatchObject({ replacedBy: c.id, isDefault: false })
+ expect(live.map((tier) => tier.id)).toEqual([c.id])
+ expect(live[0]).toMatchObject({ isDefault: true })
+ })
+
+ it('refuses a bad replacement', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ const a = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'A' }) })
+ const b = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'B' }) })
+ const c = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'C' }) })
+ await ctx.delete(`${TIERS}/${c.id}`, { replacedBy: b.id })
+ const otherCtx = await createTestContext(app!)
+ const foreign = await createTier({ testCtx: otherCtx, body: tierBody({ configId: (await seedKey({ testCtx: otherCtx })).id }) })
+
+ const self = await ctx.delete(`${TIERS}/${a.id}`, { replacedBy: a.id })
+ const deleted = await ctx.delete(`${TIERS}/${a.id}`, { replacedBy: c.id })
+ const crossPlatform = await ctx.delete(`${TIERS}/${a.id}`, { replacedBy: foreign.id })
+ const missing = await ctx.delete(`${TIERS}/${a.id}`)
+
+ expect(self.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(deleted.statusCode).toBe(StatusCodes.NOT_FOUND)
+ expect(crossPlatform.statusCode).toBe(StatusCodes.NOT_FOUND)
+ expect(missing.statusCode).toBe(StatusCodes.CONFLICT)
+ })
+
+ it('deletes the last tier without a replacement, then frees its key', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ const tier = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id }) })
+
+ const removed = await ctx.delete(`${TIERS}/${tier.id}`)
+ const keyRemoved = await ctx.delete(`/v1/ai-providers/${key.id}`)
+ const gone = await findWithDeleted({ id: tier.id })
+
+ expect(removed.statusCode).toBe(StatusCodes.NO_CONTENT)
+ expect(keyRemoved.statusCode).toBe(StatusCodes.NO_CONTENT)
+ expect(await listAdmin({ testCtx: ctx })).toEqual([])
+ expect(gone).toMatchObject({ replacedBy: null, isDefault: false })
+ })
+ })
+
+ describe('key guard', () => {
+ it('refuses to delete a key a tier uses', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'Expert' }) })
+
+ const response = await ctx.delete(`/v1/ai-providers/${key.id}`)
+
+ expect(response.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(response.body).toContain('Expert')
+ })
+
+ it('refuses a scope change that drops a tier model', async () => {
+ const key = await seedKey({ testCtx: ctx })
+ await createTier({ testCtx: ctx, body: tierBody({ configId: key.id }) })
+
+ const dropping = await ctx.post(`/v1/ai-providers/${key.id}`, { displayName: key.displayName, modelScope: 'selected', modelIds: ['other-model'] })
+ const keeping = await ctx.post(`/v1/ai-providers/${key.id}`, { displayName: key.displayName, modelScope: 'selected', modelIds: ['gpt-4o'] })
+
+ expect(dropping.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(keeping.statusCode).toBe(StatusCodes.OK)
+ })
+ })
+})
+
+async function seedKey({ testCtx, modelScope, modelIds }: { testCtx: TestContext, modelScope?: 'all' | 'selected', modelIds?: string[] }): Promise<{ id: string, displayName: string }> {
+ return mockAndSaveAIProvider({
+ platformId: testCtx.platform.id,
+ provider: AIProviderName.CUSTOM,
+ config: { baseUrl: 'https://api.example.com/v1', apiKeyHeader: 'Authorization', models: [] },
+ ...(modelScope ? { modelScope } : {}),
+ ...(modelIds ? { modelIds } : {}),
+ })
+}
+
+function tierBody({ configId, name, entries }: { configId: string, name?: string, entries?: { configId: string, modelId: string }[] }): Record<string, unknown> {
+ return {
+ name: name ?? 'Fast',
+ emoji: '⚡',
+ description: null,
+ entries: entries ?? [{ configId, modelId: 'gpt-4o' }],
+ }
+}
+
+async function createTier({ testCtx, body }: { testCtx: TestContext, body: Record<string, unknown> }): Promise<PlatformModelTier> {
+ const response = await testCtx.post(TIERS, body)
+ expect(response.statusCode).toBe(StatusCodes.OK)
+ return response.json()
+}
+
+async function listAdmin({ testCtx }: { testCtx: TestContext }): Promise<PlatformModelTier[]> {
+ const response = await testCtx.get(`${TIERS}/admin`)
+ expect(response.statusCode).toBe(StatusCodes.OK)
+ return response.json()
+}
+
+async function findWithDeleted({ id }: { id: string }): Promise<unknown> {
+ return databaseConnection().getRepository('platform_model_tier').findOne({ where: { id }, withDeleted: true })
+}
+
+const TIERS = '/v1/platform-model-tiers'
diff --git a/packages/server/api/test/integration/ee/ai-provider/platform-model-tier-plan.test.ts b/packages/server/api/test/integration/ee/ai-provider/platform-model-tier-plan.test.ts
new file mode 100644
index 00000000000..afb582b248d
--- /dev/null
+++ b/packages/server/api/test/integration/ee/ai-provider/platform-model-tier-plan.test.ts
@@ -0,0 +1,68 @@
+import { AIProviderName } from '@activepieces/core-utils'
+import { FastifyInstance } from 'fastify'
+import { StatusCodes } from 'http-status-codes'
+import { databaseConnection } from '../../../../src/app/database/database-connection'
+import { mockAndSaveAIProvider } from '../../../helpers/mocks'
+import { createTestContext } from '../../../helpers/test-context'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance | null = null
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+describe('Platform model tiers plan gate', () => {
+ it('blocks writes but keeps reads when the plan has no AI providers', async () => {
+ const ctx = await createTestContext(app!, { plan: { aiProvidersEnabled: false } })
+ const key = await mockAndSaveAIProvider({
+ platformId: ctx.platform.id,
+ provider: AIProviderName.CUSTOM,
+ config: { baseUrl: 'https://api.example.com/v1', apiKeyHeader: 'Authorization', models: [] },
+ })
+
+ const create = await ctx.post(TIERS, { name: 'Fast', emoji: '⚡', entries: [{ configId: key.id, modelId: 'gpt-4o' }] })
+ const list = await ctx.get(TIERS, { projectId: ctx.project.id })
+
+ expect(create.statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)
+ expect(list.statusCode).toBe(StatusCodes.OK)
+ })
+
+ it('lets a downgraded platform delete its last tier and then its key', async () => {
+ const ctx = await createTestContext(app!, { plan: { aiProvidersEnabled: true } })
+ const key = await mockAndSaveAIProvider({
+ platformId: ctx.platform.id,
+ provider: AIProviderName.CUSTOM,
+ config: { baseUrl: 'https://api.example.com/v1', apiKeyHeader: 'Authorization', models: [] },
+ })
+ const tier = (await ctx.post(TIERS, { name: 'Fast', emoji: '⚡', entries: [{ configId: key.id, modelId: 'gpt-4o' }] })).json()
+ await databaseConnection().getRepository('platform_plan').update({ platformId: ctx.platform.id }, { aiProvidersEnabled: false })
+
+ const keyWhileUsed = await ctx.delete(`/v1/ai-providers/${key.id}`)
+ const deleteTier = await ctx.delete(`${TIERS}/${tier.id}`)
+ const deleteKey = await ctx.delete(`/v1/ai-providers/${key.id}`)
+
+ expect(keyWhileUsed.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(deleteTier.statusCode).toBe(StatusCodes.NO_CONTENT)
+ expect(deleteKey.statusCode).toBe(StatusCodes.NO_CONTENT)
+ })
+
+ it('allows writes when the plan has AI providers', async () => {
+ const ctx = await createTestContext(app!, { plan: { aiProvidersEnabled: true } })
+ const key = await mockAndSaveAIProvider({
+ platformId: ctx.platform.id,
+ provider: AIProviderName.CUSTOM,
+ config: { baseUrl: 'https://api.example.com/v1', apiKeyHeader: 'Authorization', models: [] },
+ })
+
+ const create = await ctx.post(TIERS, { name: 'Fast', emoji: '⚡', entries: [{ configId: key.id, modelId: 'gpt-4o' }] })
+
+ expect(create.statusCode).toBe(StatusCodes.OK)
+ })
+})
+
+const TIERS = '/v1/platform-model-tiers'
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index 183c3792118..b98209694eb 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -2924,6 +2924,12 @@
"Configurations": "Configurations",
"atLeastOne": "Must be at least 1",
"atMostTenThousand": "Must be at most 10,000",
+ "tierNameTooLong": "Tier name must be 40 characters or fewer",
+ "tierDescriptionTooLong": "Description must be 120 characters or fewer",
+ "invalidEmoji": "Pick an emoji",
+ "tierTooManyModels": "A tier can have at most 5 models",
+ "tierDuplicateModel": "This model is already in the tier",
+ "tierThinkingBudgetInvalid": "Thinking budget must be 0 (off) or between 1,024 and 64,000 tokens",
"wholeNumber": "Must be a whole number",
"Limits": "Limits",
"Guardrails that apply to every project on this platform.": "Guardrails that apply to every project on this platform.",