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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(ai): agents follow their tier when it moves to a newer model (#15871)
Louai Boumediene9eec998dde0a
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.mdindex d4d06442fe8..759e27a8db4 100644--- a/brain/knowledge/ai-intelligence/ai-agents.md+++ b/brain/knowledge/ai-intelligence/ai-agents.md@@ -15,9 +15,9 @@ A flow step type (the `run_agent` action of `@activepieces/piece-ai`) that runs| 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` | `agent.draft.modelName`; no picker is shown while chatting (`ai-chat-box.tsx` hides it when `agentId` is set) | tier id on the managed provider; concrete id on an own key or a row saved before ENG-754 || `AGENT_BUILDER` | `conversation.modelName` | tier id |-| `FLOW_STEP` | `agent.published.modelName`, or the step's own `input.aiProviderModel.model` | concrete id |+| `FLOW_STEP` | `agent.published.modelName`, or the step's own `input.aiProviderModel.model` | same as `AGENT` |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` and `chat-analytics-sync.ts`. **A persisted tier id is not a pin.** `pinnedModelOf` (`rpc/rpc-shared.ts`) ignores `conversation.modelName` for a conversation with an agent: that value is the resolved default, and once the console removes that tier it would reach a catalogue-less own-key provider as a literal model id. A saved agent's run model is the agent's own half (draft for AGENT, published for FLOW_STEP); only an agentless inline step reads `conversation.modelName`, which is the step's configured model.@@ -30,6 +30,9 @@ Three things follow. `run_agent` has two modes: pointed at a saved agent (`agent- **PredefinedInputsStructure** — per-field `AGENT_DECIDE` / `CHOOSE_YOURSELF` / `LEAVE_EMPTY` baked into the tool so the agent knows which inputs it controls.### Gotchas++- **A managed agent row or Run Agent step stores a tier id (`smart`) from ENG-754 on; nothing converts the rows saved before.** `AIModelSelector` (`web/src/features/agents/ai-model/`) lists the published flow tiers by id for the managed provider and never calls `/models` for it; a blank picker pre-fills the published `flow.defaultTierId` once the tiers query settles (it used to take the first tier, Fast), and `withDefaultModel` (`agent-service.ts`) seeds the same default tier id on create. Own-key providers still store concrete ids: `resolveNamedModelId` passes their name through verbatim, so a tier id there would reach the provider as a model name. An older row keeps its concrete id: it runs that model (slash rule), shows the raw id in the picker, and does not follow a re-point until the ENG-753 migration.+- **A flow-surface run takes its thinking budget from the tier it names, not the default tier.** `resolveRunTier` (`agent-model-resolution.ts`) builds `config.tier` for FLOW_STEP and AGENT runs: a managed tier id gives that tier's `thinkingBudget`, `id` and `modelId`; a concrete id, an own-key model, a tier the file dropped, or no model at all gives the flow default, as every flow-surface run did before ENG-754. So a Heavy agent thinks at Heavy's budget and reports `premium` in `chat.tier`, while a Heavy row saved as `anthropic/claude-opus-4.8` still thinks at Expert's until it is migrated.- **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.diff --git a/brain/knowledge/ai-intelligence/ai-providers.md b/brain/knowledge/ai-intelligence/ai-providers.mdindex 3693e563370..2b2468e4d03 100644--- a/brain/knowledge/ai-intelligence/ai-providers.md+++ b/brain/knowledge/ai-intelligence/ai-providers.md@@ -216,3 +216,4 @@ after a file without chat keys it seeds the chat list from the live flow list.Paths verified 2026-07-26.- **`OPENROUTER_PROVISION_KEY` is a management key and cannot make inference calls; only the per-platform keys it mints can.** OpenRouter states it outright: management keys are for creating, listing, updating and deleting other keys and are rejected by every completion or decisions endpoint. So "we already have an OpenRouter key" is true for provisioning and false for anything that needs to call a model at the instance level (the AI Router's Jev call, for example): that needs an ordinary inference key from the same account, created in the dashboard or via the same `POST /keys` the instance already uses, with a credit `limit`. The AI Router does exactly that since 2026-09-23: it runs on the platform's managed key where credits are on, else the admin's own OpenRouter row, as a worker `EXECUTE_AI` job billed like any AI step.- **`z.enum(SomeTsEnum).exclude([SomeTsEnum.MEMBER])` compiles and excludes nothing at the type level; pass the key string, `.exclude(['MEMBER'])`.** zod's `exclude` is typed over `keyof T` and returns `ZodEnum<Omit<T, U[number]>>`. A TS enum member is its own literal type, not the string `'MEMBER'`, so `Omit` finds no key to drop and the inferred value type keeps every member, while the runtime check does exclude it. The symptom is one step removed from the cause: a switch over the parsed field is suddenly non-exhaustive (`switch-exhaustiveness-check` in lint, `TS2366` in the build) even though the branch you removed can never arrive. `/v1/ai/execute` hit this when `ROUTE` was carved out of `AiStepAction` for #15707. Neither vitest nor a package-local eslint run without type information reports it; only the build does.+- **The managed Activepieces row can never restrict its models, so a finding that the managed picker offers a model the key forbids is not reachable.** The row is inserted with `modelScope: 'all', modelIds: []`, `create()` refuses `provider === ACTIVEPIECES` (`aiProvider.activepiecesIsManaged`), and `update()` handles only `enabledForChat` for it and returns before any scope field is read (`ai-provider-service.ts`). Every published tier therefore runs on it, and any `modelScope` filtering on the managed path is inert. Reviewers (Greptile on #15871) raise this as a P1; answer with these three facts rather than adding a filter.diff --git a/brain/knowledge/engineering/ci-pr-review-hygiene.md b/brain/knowledge/engineering/ci-pr-review-hygiene.mdindex 44c1c6ddc11..c89783fbb7e 100644--- a/brain/knowledge/engineering/ci-pr-review-hygiene.md+++ b/brain/knowledge/engineering/ci-pr-review-hygiene.md@@ -85,7 +85,8 @@ Enforcement is the **`Codeowners review` repository ruleset** (active on the def- **Docs videos belong on `cdn.activepieces.com/videos/docs/`, never in the repo — and `docs/resources/` is the legacy path that suggests otherwise.** Every `<video>` already in the wiki points at that CDN prefix, but `docs/resources/` still holds ~43 MB of in-repo gifs from before the convention, so the tree itself gives mixed signals and a contributor reasonably copies the wrong one. [#15399](https://github.com/activepieces/activepieces/pull/15399) added a fresh `docs/videos/` folder with 155 MB of `.mp4` against an 880 MB `.git`, including one byte-identical duplicate. Nothing in CI catches it: `PR size` exempts unmatched areas and counts lines, not bytes, and a binary blob contributes zero lines. Review the *file list* of a docs PR, not just its diff. Once such a branch is pushed the blobs are already on the remote — dropping them at the tip only keeps them out of `main` if the PR is **squash**-merged and the branch deleted, so a merge commit ships them permanently. Because the blobs stay reachable until the branch is deleted, nobody has to re-request the assets from whoever recorded them — pull them straight back out of history with `git archive <commit> docs/videos | tar -x --strip-components=2 -C <dir>`, picking the commit *before* the removal, which is also how you get them under the post-rename filenames the pages already reference.- **Mintlify-editor PRs arrive with `untitled-page*.mdx` at the docs root and `(1)`/`(2)`-suffixed media, wired into `docs.json` under those names.** The bot commits whatever the web editor autosaved, so pages land as `docs/untitled-page-5.mdx` rather than in the folder their nav group implies, and re-uploaded assets keep the browser's download-collision suffix (`data-flow-(1).mp4`, `01---insert-panel-(1.2x).mp4`). Mintlify's own link check passes — the names are internally consistent — so nothing flags it. Rename the files, fix the `docs.json` entries, then diff the *flattened nav tree* against `main` rather than reading the raw JSON diff: the editor also reindents, which buried a real change (the Enterprise Control `Security` group demoted to a child of `Guides`) inside 242 lines of whitespace churn on that PR.- **After rewriting a lower branch of a stack, the `--onto` upstream you need is that branch's *old* tip, and `<branch>@{1}` is where to read it.** Every commit above a rewritten branch has to be replayed with `git rebase --onto <new lower tip> <old lower tip> <upper>`, and the old tip stops being reachable by name the moment the rebase finishes. Guessing a SHA from an earlier terminal scroll either fails outright with `invalid upstream` or, worse, succeeds against the wrong base and replays a handful of commits instead of all of them, which surfaces as a pile of conflicts the branch has with itself. `git rev-parse <branch>@{1}` reads it from the reflog every time. Re-run the whole `--onto` chain top-down after any lower-branch amend, and confirm afterwards that `git log --format=%s main..<top>` has no duplicate subjects.-- **When a stacked PR's parent is squash-merged, merge `main` into the child and retarget; do not rebase.** The parent's commits are on `main` by content but not by SHA, so `git merge origin/main` on the child sees both sides make the same change and auto-merges it; only the lines the child *rewrote* from the parent conflict, plus anything `main` changed in the same functions since (PR 2 of the model tiers work, #15825: three brain and docs pages where PR 2 had rewritten PR 1's sentences, and `agent-helpers.ts` where main's `resolveImageModelId` landed next to the surface-threaded fast-model helper). No history rewrite, a normal push, and the PR above it keeps its base untouched; a `--onto` rebase would replay every commit up the stack and force-push each. After the retarget, the PR's Commits tab still lists the parent's original SHAs (they reached `main` only as a squash) while Files changed shows only the child's files; the second view is the one that matters, so do not "fix" the first. Two traps in the resolution. `git checkout --ours <file>` on a conflicted file takes the *whole* file from your side and silently discards main's auto-merged hunks in it, so resolve hunk by hunk and check `git diff origin/main -- <file>` afterwards shows only your lines. And `tsc` against the merged tree resolves `@activepieces/shared` through the built dist, which still holds the pre-merge exports: three phantom "has no exported member" errors vanished after `npx turbo run build --filter=@activepieces/server-utils`. Rebuild the core libs before believing a typecheck, then run the child's own tests. A child branched off an *older* head of its parent (the parent took review fixes after the child was cut) also conflicts in files the child never touched: those are the parent's early copy against its final one on `main`. If `git log <old parent head>..HEAD -- <file>` lists none of the child's commits, `git checkout --theirs <file>` is the right answer there, because the whole file is main's (PR 4 of the model tiers work, #15866: `use-chat.ts`, `core/execution/package.json` and an agent test).+- **When a stacked PR's parent is squash-merged, merge `main` into the child and retarget; do not rebase.** The parent's commits are on `main` by content but not by SHA, so `git merge origin/main` on the child sees both sides make the same change and auto-merges it; only the lines the child *rewrote* from the parent conflict, plus anything `main` changed in the same functions since (PR 2 of the model tiers work, #15825: three brain and docs pages where PR 2 had rewritten PR 1's sentences, and `agent-helpers.ts` where main's `resolveImageModelId` landed next to the surface-threaded fast-model helper). No history rewrite, a normal push, and the PR above it keeps its base untouched; a `--onto` rebase would replay every commit up the stack and force-push each. After the retarget, the PR's Commits tab still lists the parent's original SHAs (they reached `main` only as a squash) while Files changed shows only the child's files; the second view is the one that matters, so do not "fix" the first. Two traps in the resolution. `git checkout --ours <file>` on a conflicted file takes the *whole* file from your side and silently discards main's auto-merged hunks in it, so resolve hunk by hunk and check `git diff origin/main -- <file>` afterwards shows only your lines. And `tsc` against the merged tree resolves `@activepieces/shared` through the built dist, which still holds the pre-merge exports: three phantom "has no exported member" errors vanished after `npx turbo run build --filter=@activepieces/server-utils`. Rebuild the core libs before believing a typecheck, then run the child's own tests. A child branched off an *older* head of its parent (the parent took review fixes after the child was cut) also conflicts in files the child never touched: those are the parent's early copy against its final one on `main`. If `git log <old parent head>..HEAD -- <file>` lists none of the child's commits, `git checkout --theirs <file>` is the right answer there, because the whole file is main's (PR 4 of the model tiers work, #15866: `use-chat.ts`, `core/execution/package.json` and an agent test). For a file the child *did* change, take main's copy and replay only the child's own commit on top: `git checkout --theirs <files> && git add <files> && git show <child commit> -- <files> | git apply --3way` (it needs the files staged, and in zsh pass the list as an array, since a plain variable is not word-split); only hunks where main moved the child's own lines are left to resolve by hand (PR 5, #15871: six files, one hunk).+- **Retargeting a PR's base never starts CI, and a push made while the old base conflicts may not start it either.** `ci.yml` listens only to `pull_request` opened, synchronize and reopened; `gh pr edit --base` fires `edited`, which starts nothing. On #15866 the catch-up merge was pushed while the PR still targeted its squash-merged parent's branch, the main CI never ran on that head, and the retarget did not trigger it, so the PR showed only the small checks (title, breaking change, Greptile) and looked green. After a retarget, check `gh pr checks <n>` lists `build-test` and the `api` jobs; if not, push again (an empty `ci:` commit is enough). Never `gh run rerun`: it replays the old event.- **Never commit a shared file onto a lower branch of a stack by copying it in from the stack top — you drag the upper branches' edits down with it.** Adding one gotcha bullet to a brain page while sitting on the top branch, then `git checkout <stash-or-top> -- <file>` after switching to the base branch, brings the *whole* file across, so every bullet the upper branches added to that page is silently duplicated onto the base. The commit stat is the tell: a one-line edit that reports six insertions is not a one-line edit. Switch branches first, re-apply the edit against **that branch's own copy** of the file, and re-check the stat before committing.- **Cherry-picking a merged PR onto a release branch: the commit-msg hook rejects it, and `breaking-changes.mdx` conflicts pull in other people's entries.** GitHub writes the squash header server-side, so `fix(flows): … instead of reverting them (#14899)` never faced commitlint — replaying it locally trips the 100-character header limit and `git cherry-pick --continue` dies in husky with the working tree half-applied. Finish it with `git commit --no-verify -C <original-sha>` rather than rewording, so the release branch keeps the same subject as `main`. The `Unreleased` section of `docs/install/reference/breaking-changes.mdx` conflicts on almost every pick because it accumulates entries from unrelated `main` work: take only the section your own commit added. **Take it by its own heading, not by "everything after the marker" — the incoming side of that hunk usually runs on into `main`'s copy of an already-published `## X.Y.Z` section, and pasting the tail duplicates ~200 lines of published notes that no test, lint or typecheck will ever notice.** The reliable move is to rebuild the file: `git checkout origin/release/<version> -- docs/install/reference/breaking-changes.mdx`, then insert your entry under its own `## <new version>` heading above the previous release's, and confirm with `git diff --stat` that only your lines are added and `grep -c '^## '` that no version heading appears twice. Then run `bun install` before pushing — the release branch's `bun.lock` is usually stale against its own `package.json`s, and the pick drags those stale piece versions along until install corrects them; `git diff --stat origin/release/<version> -- bun.lock` should come back as just the packages your pick actually bumped. Expect the **PR size** gate to block it too: the picked commits drag their own upstream tests along (769/600 in `server/api` for two picks), and splitting a replay of already-reviewed work is the wrong answer — add `large-pr-ok`.- **`api#test-ce` can exit 1 with every test passing — read the `Errors` line, not just `Tests`.** Vitest fails the run on *unhandled* errors too, so the summary reads `Test Files 92 passed`, `Tests 1076 passed`, `Errors 3 errors` and turbo reports `Failed: api#test-ce`. The recurring one is `TypeError: socket.destroySoon is not a function` at `Timeout.forceClose` in `@hono/node-server`, attributed to `test/integration/ce/mcp/mcp-platform-project-selection.test.ts` — a teardown race after the test already finished, not a failure of whatever you changed. Before chasing it, scroll to the `Unhandled Errors` block and check whether any test actually failed; if none did and the stack is in `forceClose`, re-run the job (`gh run rerun <id> --failed`) rather than editing code. Note the log section only has the whole `main` job, so `gh run view --job <id> --log-failed` buries it under thousands of lines of passing-test stderr — grep for `Unhandled Errors` or `Test Files`.diff --git a/brain/knowledge/memory.md b/brain/knowledge/memory.mdindex 3b7c5930233..0befdb61ec6 100644--- a/brain/knowledge/memory.md+++ b/brain/knowledge/memory.md@@ -2,6 +2,7 @@- 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-27 — PR 3 of the configurable tiers work (`feat/tier-endpoint`, ENG-768): `GET /v1/ai-providers/tiers` serves both lists and both web pickers read it; a new chat no longer hardcodes `smart`. Found on the way: the live `ai/pricing.json` republished on 2026-09-26 carried `defaultTierId: fast`, which never reached web chats only because the web sent `smart` explicitly; it is being republished as `smart`.- 2026-09-28 — PR 4 of the configurable tiers work (`feat/tier-ai-piece`, ENG-752): the AI piece's managed text dropdown (piece 0.12.0, `minimumSupportedRelease` 0.93.0) offers the published flow tiers and stores the tier id, falling back to the bundled tier ids, never `/models`. `aiModelResolution.resolveTierModelId` (`src/app/ai/`, CE) turns the id into today's flow model in `ai-execute-controller` before enqueue, skips image steps, and logs `model.id` and `tier.id` on both branches. Merge gate: `origin/main`'s root version must be below 0.93.0 when it merges.+- 2026-09-28 — PR 5 of the configurable tiers work (`feat/tier-agent-step`, ENG-754): managed agents and Run Agent steps store the flow tier id, a blank picker pre-fills the published default, and a named tier supplies its own thinking budget (Heavy 10k → 20k). Chosen that day: older rows show their raw model id and keep Expert's budget until ENG-753, with no display or budget mapping; own-key agents get no server-side guard, PR 6's tier map will cover them.- 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.diff --git a/packages/server/api/src/app/ee/agent/agent-model-resolution.ts b/packages/server/api/src/app/ee/agent/agent-model-resolution.tsindex f9980906911..28bd415f476 100644--- a/packages/server/api/src/app/ee/agent/agent-model-resolution.ts+++ b/packages/server/api/src/app/ee/agent/agent-model-resolution.ts@@ -15,6 +15,16 @@ function resolveTier({ tierId, surface }: { tierId: string | null, surface: Modereturn modelTierCatalog.current(surface).resolveTier({ tierId })}+function resolveRunTier({ provider, modelName, selectedModel, surface }: { provider: AIProviderName, modelName: string | null, selectedModel: string | null, surface: ModelTierSurface }): ModelTier {+ if (surface === 'chat') {+ return resolveTier({ tierId: selectedModel, surface })+ }+ const namedTier = provider === AIProviderName.ACTIVEPIECES && !isNil(modelName) && isTierId({ modelName })+ ? findTier({ tierId: modelName, surface })+ : undefined+ return namedTier ?? resolveTier({ tierId: null, surface })+}+function nativeModelIdFor({ tier }: { tier: ModelTier }): string | null {return tier.nativeModelId ?? ACTIVEPIECES_CHAT_TIERS.find((shipped) => shipped.id === tier.id)?.nativeModelId ?? null}@@ -117,6 +127,7 @@ export const agentModelResolution = {surfaceOf,findTier,resolveTier,+ resolveRunTier,nativeModelIdFor,resolveNamedModelId,resolveModelIdForProvider,diff --git a/packages/server/api/src/app/ee/agent/agent-service.ts b/packages/server/api/src/app/ee/agent/agent-service.tsindex 073b3285b23..5845ef9bbb3 100644--- a/packages/server/api/src/app/ee/agent/agent-service.ts+++ b/packages/server/api/src/app/ee/agent/agent-service.ts@@ -1,6 +1,6 @@import { createHash } from 'node:crypto'import { AgentToolType, McpAuthType } from '@activepieces/core-piece-types'-import { ActivepiecesError, apId, ApId, connectionTemplate, Cursor, ErrorCode, isNil, omit, Permission, PlatformId, ProjectId, sanitizeObjectForPostgresql, SeekPage, unique, UserId } from '@activepieces/core-utils'+import { ActivepiecesError, AIProviderName, apId, ApId, connectionTemplate, Cursor, ErrorCode, isNil, omit, Permission, PlatformId, ProjectId, sanitizeObjectForPostgresql, SeekPage, unique, UserId } from '@activepieces/core-utils'import { Agent, AgentConfig, AgentFlowTool, AgentKnowledgeBaseTool, AgentListSort, AgentMoveLoss, AgentMoveLossKind, AgentMovePreview, AgentRunSource, AgentSummary, agentUtils, AgentVisibility, CreateAgentRequest, DefaultProjectRole, Project, ProjectType, UpdateAgentRequest } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { Brackets, EntityManager, In, SelectQueryBuilder } from 'typeorm'@@ -431,7 +431,9 @@ async function withDefaultModel({ draft, platformId, projectId, log }: {if (isNil(provider)) {return draft}- const modelName = agentHelpers.defaultModelIdForProvider({ provider, surface: 'flow' })+ const modelName = provider === AIProviderName.ACTIVEPIECES+ ? agentHelpers.resolveTier({ tierId: null, surface: 'flow' }).id+ : agentHelpers.defaultModelIdForProvider({ provider, surface: 'flow' })if (isNil(modelName)) {return { ...draft, provider }}diff --git a/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts b/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.tsindex 9ab01d02267..5e7680671f7 100644--- a/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts+++ b/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts@@ -131,10 +131,8 @@ export const agentConfigRpc = (log: FastifyBaseLogger) => ({}const selectedModel = modelName ?? conversation.modelName ?? null- // The tier resolver finds no tier for a concrete model id and silently returns the default,- // so a source that names its own model must never be routed through it.const namesItsOwnModel = surface === 'flow'- const tier = agentHelpers.resolveTier({ tierId: namesItsOwnModel ? null : selectedModel, surface })+ const tier = agentHelpers.resolveRunTier({ provider: providerConfig.provider, modelName: modelName ?? null, selectedModel, surface })const resolvedModelId = namesItsOwnModel && !isNil(modelName)? agentHelpers.resolveNamedModelId({ provider: providerConfig.provider, modelName, surface, modelScope: providerConfig.modelScope, modelIds: providerConfig.modelIds, log }): await agentHelpers.resolveModelId({ platformId, providerConfig, selectedModel, surface, scope: runScope, log })diff --git a/packages/server/api/test/integration/ee/agent/agent-controller.test.ts b/packages/server/api/test/integration/ee/agent/agent-controller.test.tsindex 1d1ff6547f2..2033c56d76a 100644--- a/packages/server/api/test/integration/ee/agent/agent-controller.test.ts+++ b/packages/server/api/test/integration/ee/agent/agent-controller.test.ts@@ -71,6 +71,22 @@ describe('agent crud', () => {expect(agent.draft.provider).toBe(AIProviderName.OPENROUTER)})+ it('fills in the default tier id, not the model behind it, when the platform runs on Activepieces credits', async () => {+ process.env.AP_OPENROUTER_PROVISION_KEY = 'test-provision-key'+ try {+ const ctx = await context()+ await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.ACTIVEPIECES, enabledForChat: true })++ const agent = await createAgent(ctx)++ expect(agent.draft.modelName).toBe('smart')+ expect(agent.draft.provider).toBe(AIProviderName.ACTIVEPIECES)+ }+ finally {+ delete process.env.AP_OPENROUTER_PROVISION_KEY+ }+ })+it('keeps a model the request did name, even where a default was available', async () => {const ctx = await context()await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.OPENROUTER, enabledForChat: true })diff --git a/packages/server/api/test/unit/app/ee/agent/agent-model-resolution.test.ts b/packages/server/api/test/unit/app/ee/agent/agent-model-resolution.test.tsindex 88a4b08961c..cd1af713e69 100644--- a/packages/server/api/test/unit/app/ee/agent/agent-model-resolution.test.ts+++ b/packages/server/api/test/unit/app/ee/agent/agent-model-resolution.test.ts@@ -226,6 +226,31 @@ describe('defaultModelIdForProvider', () => {})})+describe('resolveRunTier', () => {+ const runTier = ({ provider = AIProviderName.ACTIVEPIECES, modelName, surface = 'flow' }: { provider?: AIProviderName, modelName: string | null, surface?: ModelTierSurface }) =>+ agentModelResolution.resolveRunTier({ provider, modelName, selectedModel: modelName, surface })++ it('gives a run that names a managed tier that tier, so Heavy thinks on its own budget rather than the default one', () => {+ expect(runTier({ modelName: 'premium' })).toMatchObject({ id: 'premium', thinkingBudget: 20_000 })+ expect(runTier({ modelName: 'deep' })).toMatchObject({ id: 'deep', modelId: 'anthropic/claude-fable-5.1' })+ })++ it('keeps the default tier for a concrete model id, a tier the file no longer carries, or no model at all', () => {+ expect(runTier({ modelName: 'anthropic/claude-opus-4.8' }).id).toBe('smart')+ expect(runTier({ modelName: 'tier-9' }).id).toBe('smart')+ expect(runTier({ modelName: null }).id).toBe('smart')+ })++ it('never reads an own-key deployment named like a tier as that tier', () => {+ expect(runTier({ provider: AIProviderName.AZURE, modelName: 'premium' }).id).toBe('smart')+ })++ it('resolves the chat pick on the chat list', () => {+ expect(runTier({ modelName: 'smart', surface: 'chat' }).modelId).toBe('google/gemini-3.7-flash')+ expect(runTier({ modelName: 'turbo', surface: 'chat' }).id).toBe('turbo')+ })+})+describe('resolveNamedModelId', () => {beforeEach(() => {warn.mockClear()diff --git a/packages/web/src/app/builder/step-settings/agent-settings/agent-link.tsx b/packages/web/src/app/builder/step-settings/agent-settings/agent-link.tsxindex 7708fb6f92a..7abbeffd456 100644--- a/packages/web/src/app/builder/step-settings/agent-settings/agent-link.tsx+++ b/packages/web/src/app/builder/step-settings/agent-settings/agent-link.tsx@@ -1,4 +1,8 @@-import { isNil, spreadIfDefined } from '@activepieces/core-utils';+import {+ AIProviderName,+ isNil,+ spreadIfDefined,+} from '@activepieces/core-utils';import {AgentPieceProps,AgentSummary,@@ -31,6 +35,7 @@ import {agentsQueries,useAgentsAvailable,} from '@/features/agents/hooks/agents-hooks';+import { aiProviderQueries } from '@/features/platform-admin/hooks/ai-provider-hooks';import { useAuthorization } from '@/hooks/authorization-hooks';import { authenticationSession } from '@/lib/authentication-session';import { cn } from '@/lib/utils';@@ -77,7 +82,13 @@ export const AgentLink = ({ disabled }: AgentLinkProps) => {: !linked.isPublished? t('Not published yet. Publish it before this flow can run.'): undefined;- const modelLabel = linkedConfig?.modelName ?? undefined;+ const { tiers: flowTiers } = aiProviderQueries.useModelTiers('flow');+ const modelLabel =+ (linkedConfig?.provider === AIProviderName.ACTIVEPIECES+ ? flowTiers.find((tier) => tier.id === linkedConfig.modelName)?.label+ : undefined) ??+ linkedConfig?.modelName ??+ undefined;const toolPieces = new Set((linked?.toolPieceNames ?? []).map((pieceName) =>pieceName.replace('@activepieces/piece-', ''),diff --git a/packages/web/src/features/agents/ai-model/hooks.ts b/packages/web/src/features/agents/ai-model/hooks.tsindex 6b5887571b5..fd6c43dca1a 100644--- a/packages/web/src/features/agents/ai-model/hooks.ts+++ b/packages/web/src/features/agents/ai-model/hooks.ts@@ -1,6 +1,7 @@import { AIProviderName, isNil } from '@activepieces/core-utils';import {AIProviderModel,+ AIProviderModelType,ALLOWED_CHAT_MODELS_BY_PROVIDER,} from '@activepieces/shared';import { useQuery } from '@tanstack/react-query';@@ -26,10 +27,14 @@ function getAllowedModelsForProvider({modelType: AIModelType;flowTiers: ModelTier[];}): AIProviderModel[] {- const allowedIds =- provider === AIProviderName.ACTIVEPIECES- ? flowTiers.map((tier) => tier.modelId)- : ALLOWED_CHAT_MODELS_BY_PROVIDER[provider];+ if (provider === AIProviderName.ACTIVEPIECES) {+ return flowTiers.map((tier) => ({+ id: tier.id,+ name: tier.label,+ type: AIProviderModelType.TEXT,+ }));+ }+ const allowedIds = ALLOWED_CHAT_MODELS_BY_PROVIDER[provider];return allModels.filter((model) => model.type === modelType)@@ -47,26 +52,7 @@ function getAllowedModelsForProvider({const aIndex = allowedIds.indexOf(a.id);const bIndex = allowedIds.indexOf(b.id);return aIndex - bIndex;- })- .map((model) =>- provider === AIProviderName.ACTIVEPIECES- ? {- ...model,- name:- managedTierLabel({ modelId: model.id, flowTiers }) ?? model.name,- }- : model,- );-}--function managedTierLabel({- modelId,- flowTiers,-}: {- modelId: string;- flowTiers: ModelTier[];-}): string | undefined {- return flowTiers.find((tier) => tier.modelId === modelId)?.label;+ });}export const aiModelHooks = {@@ -99,7 +85,9 @@ export const aiModelHooks = {queryKey: ['ai-models', provider, configId, projectId],enabled: !isNil(provider) && !isNil(projectId),queryFn: () =>- isNil(provider) || isNil(projectId)+ isNil(provider) ||+ isNil(projectId) ||+ provider === AIProviderName.ACTIVEPIECES? []: aiProviderApi.listModelsForProvider(provider, projectId, configId),select,diff --git a/packages/web/src/features/agents/ai-model/index.tsx b/packages/web/src/features/agents/ai-model/index.tsxindex 11528447a5a..91f1eba2180 100644--- a/packages/web/src/features/agents/ai-model/index.tsx+++ b/packages/web/src/features/agents/ai-model/index.tsx@@ -1,4 +1,6 @@import { AIProviderName } from '@activepieces/core-utils';+import { AIProviderModel } from '@activepieces/shared';+import { useQuery } from '@tanstack/react-query';import { t } from 'i18next';import { Check, ChevronsUpDown, Loader2 } from 'lucide-react';import * as React from 'react';@@ -17,6 +19,7 @@ import {PopoverTrigger,} from '@/components/ui/popover';import { SUPPORTED_AI_PROVIDERS } from '@/features/agents/ai-providers';+import { aiProviderQueries } from '@/features/platform-admin/hooks/ai-provider-hooks';import { cn } from '@/lib/utils';import { aiModelHooks } from './hooks';@@ -80,6 +83,16 @@ export function AIModelSelector({aiModelHooks.useListProviders();const { data: models = [], isLoading: modelsLoading } =aiModelHooks.useGetModelsForProvider(selectedProvider, selectedConfigId);+ const { status: modelTiersStatus } = useQuery(+ aiProviderQueries.modelTiersOptions(),+ );+ const { defaultTierId } = aiProviderQueries.useModelTiers('flow');+ const managed = selectedProvider === AIProviderName.ACTIVEPIECES;+ const waitingForTiers = managed && modelTiersStatus === 'pending';+ const defaultModelId = defaultPick({+ models,+ preferredId: managed ? defaultTierId : undefined,+ });const getProviderLogo = React.useCallback((providerName: string) => {return ALL_PROVIDERS.find((p) => p.provider === providerName)?.logoUrl;@@ -126,13 +139,13 @@ export function AIModelSelector({selectedProvider &&models.length > 0 &&!selectedModel &&- !modelsLoading+ !modelsLoading &&+ !waitingForTiers) {- const firstModel = models[0].id;- setSelectedModel(firstModel);+ setSelectedModel(defaultModelId);onChange({provider: selectedProvider,- model: firstModel,+ model: defaultModelId,configId: selectedConfigId,picked: 'default',});@@ -140,6 +153,8 @@ export function AIModelSelector({}, [models,modelsLoading,+ waitingForTiers,+ defaultModelId,selectedProvider,selectedModel,selectedConfigId,@@ -153,17 +168,17 @@ export function AIModelSelector({models.length > 0 &&!models.some((m) => m.id === selectedModel)) {- const fallback = models[0]?.id;- setSelectedModel(fallback);+ setSelectedModel(defaultModelId);onChange({provider: selectedProvider,- model: fallback,+ model: defaultModelId,configId: selectedConfigId,picked: 'default',});}}, [models,+ defaultModelId,selectedModel,selectedProvider,selectedConfigId,@@ -358,3 +373,15 @@ export function AIModelSelector({</div>);}++function defaultPick({+ models,+ preferredId,+}: {+ models: AIProviderModel[];+ preferredId: string | undefined;+}): string | undefined {+ return models.some((model) => model.id === preferredId)+ ? preferredId+ : models[0]?.id;+}diff --git a/packages/web/test/app/builder/step-settings/agent-settings/agent-link.test.tsx b/packages/web/test/app/builder/step-settings/agent-settings/agent-link.test.tsxindex 82feb06dce1..d70290cccb9 100644--- a/packages/web/test/app/builder/step-settings/agent-settings/agent-link.test.tsx+++ b/packages/web/test/app/builder/step-settings/agent-settings/agent-link.test.tsx@@ -10,6 +10,7 @@* branch-settings test, since @testing-library/react is opted into per file.*//* eslint-disable testing-library/no-unnecessary-act */+import { AIProviderName } from '@activepieces/core-utils';import { AgentVisibility } from '@activepieces/shared';import * as React from 'react';import { act } from 'react';@@ -21,6 +22,7 @@ const state = vi.hoisted(() => ({agentsAvailable: true,agents: [] as unknown[],isError: false,+ linkedAgent: undefined as unknown,}));vi.mock('@/features/agents/hooks/agents-hooks', () => ({@@ -32,7 +34,19 @@ vi.mock('@/features/agents/hooks/agents-hooks', () => ({isError: state.isError,refetch: vi.fn(),}),- useAgent: () => ({ data: undefined }),+ useAgent: () => ({ data: state.linkedAgent }),+ },+}));++vi.mock('@/features/platform-admin/hooks/ai-provider-hooks', () => ({+ aiProviderQueries: {+ useModelTiers: () => ({+ tiers: [+ { id: 'fast', label: 'Fast', modelId: 'anthropic/claude-haiku-4.5' },+ { id: 'premium', label: 'Heavy', modelId: 'anthropic/claude-opus-4.8' },+ ],+ defaultTierId: 'fast',+ }),},}));@@ -128,6 +142,7 @@ function render(agentId?: string) {beforeEach(() => {state.agentsAvailable = true;state.isError = false;+ state.linkedAgent = undefined;state.agents = [agent({ displayName: 'Ops', visibility: AgentVisibility.PROJECT }),];@@ -190,4 +205,48 @@ describe('the agent picker on a Run Agent step', () => {container.querySelector('[data-testid="agent-picker-error"]'),).not.toBe(null);});++ it('names a managed agent model by its tier label, not its tier id', () => {+ state.linkedAgent = linkedAgent({+ provider: AIProviderName.ACTIVEPIECES,+ modelName: 'premium',+ });++ render('ext-Ops');++ expect(container.textContent).toContain('Heavy');+ expect(container.textContent).not.toContain('premium');+ });++ it('shows a model id that is not a tier as it is stored', () => {+ state.linkedAgent = linkedAgent({+ provider: AIProviderName.ACTIVEPIECES,+ modelName: 'anthropic/claude-opus-4.8',+ });++ render('ext-Ops');++ expect(container.textContent).toContain('anthropic/claude-opus-4.8');+ });});++function linkedAgent({+ provider,+ modelName,+}: {+ provider: AIProviderName;+ modelName: string;+}) {+ return {+ id: 'id-Ops',+ draft: null,+ published: {+ provider,+ modelName,+ instructions: 'Answer tickets.',+ tools: [],+ structuredOutput: [],+ maxSteps: 10,+ },+ };+}diff --git a/packages/web/test/features/agents/ai-model/ai-model-selector.test.tsx b/packages/web/test/features/agents/ai-model/ai-model-selector.test.tsxnew file mode 100644index 00000000000..e613bf19d6f--- /dev/null+++ b/packages/web/test/features/agents/ai-model/ai-model-selector.test.tsx@@ -0,0 +1,99 @@+// @vitest-environment jsdom+import { AIProviderName } from '@activepieces/core-utils';+import { AIProviderModelType } from '@activepieces/shared';+import { render } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('i18next', () => ({ t: (key: string) => key }));++const state = vi.hoisted(() => ({+ tiersStatus: 'success',+}));++vi.mock('@tanstack/react-query', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useQuery: () => ({ status: state.tiersStatus }),+}));++vi.mock('@/features/platform-admin/hooks/ai-provider-hooks', () => ({+ aiProviderQueries: {+ modelTiersOptions: () => ({ queryKey: ['model-tiers'] }),+ useModelTiers: () => ({ tiers: [], defaultTierId: 'premium' }),+ },+}));++vi.mock('@/features/agents/ai-model/hooks', () => ({+ aiModelHooks: {+ useListProviders: () => ({+ data: [+ {+ provider: AIProviderName.ACTIVEPIECES,+ name: 'Activepieces',+ keys: [{ id: 'managed-key', name: 'Activepieces' }],+ },+ ],+ isLoading: false,+ }),+ useGetModelsForProvider: () => ({+ data: [+ { id: 'fast', name: 'Fast', type: AIProviderModelType.TEXT },+ { id: 'smart', name: 'Expert', type: AIProviderModelType.TEXT },+ { id: 'premium', name: 'Heavy', type: AIProviderModelType.TEXT },+ ],+ isLoading: false,+ }),+ },+}));++import { AIModelSelector } from '@/features/agents/ai-model';++describe('AIModelSelector on the managed provider', () => {+ beforeEach(() => {+ state.tiersStatus = 'success';+ });++ it('pre-fills the published default tier id, not the first tier in the list', () => {+ const onChange = vi.fn();++ render(<AIModelSelector onChange={onChange} />);++ expect(onChange).toHaveBeenCalledWith({+ provider: AIProviderName.ACTIVEPIECES,+ model: 'premium',+ configId: 'managed-key',+ picked: 'default',+ });+ expect(modelTriggerText()).toBe('Heavy');+ });++ it('waits for the published tiers before pre-filling, so the bundled default never lands first', () => {+ state.tiersStatus = 'pending';+ const onChange = vi.fn();++ render(<AIModelSelector onChange={onChange} />);++ expect(onChange).not.toHaveBeenCalled();+ });++ it('leaves a stored concrete model id alone and shows it as stored', () => {+ const onChange = vi.fn();++ render(+ <AIModelSelector+ defaultProvider={AIProviderName.ACTIVEPIECES}+ defaultConfigId="managed-key"+ defaultModel="anthropic/claude-sonnet-4.6"+ onChange={onChange}+ />,+ );++ expect(onChange).not.toHaveBeenCalled();+ expect(modelTriggerText()).toBe('anthropic/claude-sonnet-4.6');+ });+});++function modelTriggerText(): string | undefined {+ return document+ .querySelectorAll('button[role="combobox"]')[1]+ ?.textContent?.trim();+}diff --git a/packages/web/test/features/agents/ai-model/hooks.test.tsx b/packages/web/test/features/agents/ai-model/hooks.test.tsxindex 239c2fd2b67..162e111f1ce 100644--- a/packages/web/test/features/agents/ai-model/hooks.test.tsx+++ b/packages/web/test/features/agents/ai-model/hooks.test.tsx@@ -42,7 +42,7 @@ describe('aiModelHooks.useGetModelsForProvider', () => {queryClient.clear();});- it('offers the published flow tiers, labelled by tier, and never a chat-only model', async () => {+ it('offers the published flow tiers by tier id, never a chat-only tier, and asks for no model list', async () => {listModelTiers.mockResolvedValue(PUBLISHED);listModelsForProvider.mockResolvedValue(MANAGED_MODELS);@@ -50,40 +50,48 @@ describe('aiModelHooks.useGetModelsForProvider', () => {await waitFor(() =>expect(result.current.data?.map((model) => model.id)).toEqual([- 'anthropic/claude-haiku-4.5',- 'anthropic/claude-sonnet-5',+ 'fast',+ 'smart',+ 'premium',]),);expect(result.current.data?.map((model) => model.name)).toEqual(['Fast','Expert',+ 'Heavy',]);+ expect(listModelsForProvider).not.toHaveBeenCalled();});- it('falls back to the bundled tiers when the tiers request fails', async () => {+ it('falls back to the bundled tier ids when the tiers request fails', async () => {listModelTiers.mockRejectedValue(new Error('tiers endpoint down'));- listModelsForProvider.mockResolvedValue(MANAGED_MODELS);const { result } = renderModels(AIProviderName.ACTIVEPIECES);+ await waitFor(() => expect(listModelTiers).toHaveBeenCalled());await waitFor(() =>expect(result.current.data?.map((model) => model.id)).toEqual([- 'anthropic/claude-haiku-4.5',- 'anthropic/claude-sonnet-4.6',+ 'fast',+ 'smart',+ 'premium',]),);expect(result.current.data?.map((model) => model.name)).toEqual(['Fast','Expert',+ 'Heavy',]);});it('keeps the same list object across renders once resolved', async () => {listModelTiers.mockResolvedValue(PUBLISHED);- listModelsForProvider.mockResolvedValue(MANAGED_MODELS);const { result, rerender } = renderModels(AIProviderName.ACTIVEPIECES);- await waitFor(() => expect(result.current.data).toHaveLength(2));+ await waitFor(() =>+ expect(result.current.data?.map((model) => model.name)).toContain(+ 'Heavy',+ ),+ );const resolved = result.current.data;rerender();