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
docs(brain): the plan and gotchas behind running AI steps on the worker (#15485)
Abdulaa7d7d634c2a
diff --git a/brain/knowledge/ai-intelligence/ai-providers.md b/brain/knowledge/ai-intelligence/ai-providers.mdindex 7a899c9b7e4..f1342cf4db2 100644--- a/brain/knowledge/ai-intelligence/ai-providers.md+++ b/brain/knowledge/ai-intelligence/ai-providers.md@@ -54,6 +54,8 @@ renders and preserves every real price; the cheapest in the set is 0.01.- **The catalog object must be published before the code that reads it ships.** There is no bundled copy, so until a `workflow_dispatch` run puts it on the CDN, every install — including local dev — shows no metadata at all.- **A fresh Cloud platform cannot connect any AI provider, and the UI says nothing about why.** The admin page at `/platform/setup/ai` sets `allowWrite = platform.plan.aiProvidersEnabled`, and that column defaults to **false** on the `free` plan (migration `1776…AddDefaultToAiProvidersEnabled`), so the connect button is simply absent rather than disabled-with-a-reason. On Cloud the flag is owned by Autumn (`autumn-utils.ts` lists it among the synced features), so there is nothing to configure locally and no `DEV_ENTERPRISE_PLAN` escape hatch on main. For local Cloud testing, flip it directly: `UPDATE platform_plan SET "aiProvidersEnabled" = true`. Then connect a **BYO key**, not the managed `ACTIVEPIECES` provider — per *Provider visibility* above, the managed row is hidden whenever `OPENROUTER_PROVISION_KEY` is unset, which is the normal local state, and a hidden provider makes `getChatProvider()` return null. Anything gated on a chat provider (chat itself, personalization research) stays silently disabled until a BYO row exists.+- **`aiProviderModule` is registered unconditionally, `agentModule` is not.** In `app.ts`, `aiProviderModule` sits outside the edition switch, while `agentModule` appears only in the `CLOUD` and `ENTERPRISE` arms — so an AI route hung off the provider module is on Community for free, and the same route hung off the agent module 404s there. That asymmetry is the cheapest way to satisfy [000036](../decisions/000036-the-worker-side-ai-path-is-community-edition-core.md): pick the module and there is no edition branch left to get wrong.+- **Multi-key resolution is deterministic, not configurable.** When several keys of one provider are eligible for a project, `resolveEligibleRow` picks by most specific `projectScope` (`selected` > `except` > `all`), newest `created` breaking ties — there is no priority/default field (decision: [providers-redesign-before-routing](../decisions/providers-redesign-before-routing.md)). The ACTIVEPIECES provider stays a singleton — `create()` rejects it (`aiProvider.activepiecesIsManaged`). That ranking is the *fallback*: a step or agent may also pin a key outright (decision: [000030](../decisions/000030-a-step-may-pin-an-ai-provider-key-and-omitting-one-can-only-narrow.md)), in which case `resolveRowForScope` serves that row after checking it is eligible for the caller's project.- **Every resolver takes a required `ProviderScope`; there is no "no project" default** (decision: [000027](../decisions/000027-ai-provider-resolution-takes-a-required-scope-and-splits-reads-by-trust-level.md)). `getConfigOrThrow` / `getChatProvider` / `getChatProviderName` / `listModels` all take `scope: { type: 'project', projectId } | { type: 'platform' }`. This is deliberate and load-bearing: the first cut made `projectId` optional and treated its absence as "every key is eligible", so each new call site that forgot to thread it silently bypassed project scoping — the agent piece/knowledge-base tool handlers, the chat model picker, and the `configId` model lookup each reopened the same hole in turn. Making the argument required turns an omission into a compile error, and `{ type: 'platform' }` at a call site is a reviewable claim rather than an accident. Only three consumers are legitimately platform-wide: the tool-search embedder, chat memory extraction, and the managed-ACTIVEPIECES singleton.- **The last fail-open scope lived in the helper that *builds* the scope, not in the resolvers.** Chat resolves the project a turn runs in (`selectRunProject`) before it resolves a credential, and that project is nullable — a user who can no longer see any project gets `null`. The first cut turned `null` into `{ type: 'platform' }`, which hands the run every key on the platform and is exactly the hole a required `ProviderScope` was meant to close. `agentHelpers.runScopeOrThrow` refuses the run instead; the analytics and billing paths, which want the provider's *name* and not a credential, take the nullable project id themselves (`resolveChatProviderName`) and report no provider for a conversation that has none. Rule of thumb: a nullable id feeding a scope constructor is the shape to look for, not a missing argument.diff --git a/brain/knowledge/ai-intelligence/index.md b/brain/knowledge/ai-intelligence/index.mdindex e0c0b4fb086..23d5b2d64cf 100644--- a/brain/knowledge/ai-intelligence/index.md+++ b/brain/knowledge/ai-intelligence/index.md@@ -16,6 +16,10 @@ The metered currency for AI usage — 1000 credits = $1 — backed by per-key Op### 🤖 AgentA flow step that runs an autonomous LLM loop rather than a single call. Its **AgentTool**s are Piece, Flow, MCP, or Knowledge Base handles.+### ⚡ Direct AI step+A flow step that makes one model call and returns: Ask AI, Summarize Text, Classify Text, Extract Structured Data, Generate Image. The counterpart to an **Agent**, which loops — and the distinction decides how each reaches a model, see [decision 000035](../decisions/000035-direct-ai-steps-reuse-the-agents-suspend-and-resume-path.md).+- *Avoid:* "simple AI action" and "AI action" — both name the piece rather than the behaviour, and would wrongly include the Agent step, which also lives in the AI piece.+### 🔗 MCP ServerThe per-project endpoint that exposes Activepieces tools to an external AI assistant. Distinct from a **piece** that *calls* an MCP server.diff --git a/brain/knowledge/decisions/000035-direct-ai-steps-reuse-the-agents-suspend-and-resume-path.md b/brain/knowledge/decisions/000035-direct-ai-steps-reuse-the-agents-suspend-and-resume-path.mdnew file mode 100644index 00000000000..c986c00a5e3--- /dev/null+++ b/brain/knowledge/decisions/000035-direct-ai-steps-reuse-the-agents-suspend-and-resume-path.md@@ -0,0 +1,61 @@+---+title: Direct AI steps reuse the Agent's suspend-and-resume path+icon: 🔁+status: accepted+---++## Decision++The five **Direct AI steps** — Ask AI, Summarize Text, Classify Text, Extract Structured Data,+Generate Image — execute their model call the same way the Agent step already does: the piece posts to+the API, creates a `WEBHOOK` waitpoint and pauses; a background job runs the model call; the job+releases the flow through the resume path. **One pattern for every AI step**, not two.++## Context++Agreed 2026-09-08. The Agent step is already built this way, in production, and the piece side of it is+notably small — `run-agent.ts` invents no new framework surface at all: `httpClient.sendRequest`,+`context.server.token`, `context.run.createWaitpoint` and `context.resumePayload` all already exist.++The alternative examined at length was an in-band request/response call from the engine to the worker,+exposed as a new `context.ai.execute` on the piece context. It is measurably faster: a pause-and-resume+costs ~150–400 ms on a warm sandbox and ~1.1–1.6 s cold, over roughly 25 sequential I/O hops plus a full+round trip of the run's execution state, and Cloud is likely cold.++## Why++Speed was not the deciding axis; **permanent surface area** was. In-band execution is impossible without+adding a new public API to `@activepieces/pieces-framework` — a piece can only reach what `context` hands+it, and the sandbox↔worker socket belongs to the engine. That API would be callable by every piece,+forever, and could not later be withdrawn. The suspend path needs none of it.++Running one AI execution pattern rather than two also keeps the Agent and the Direct AI steps on a single+route that is already proven, already observable, and already understood by the team.++The cost is accepted knowingly: every Direct AI step pays the resume overhead, and the overhead grows+with the size of the run, because the resume re-reads the whole execution state.++## Consequences++- **Retry can pay for a model call twice.** A background job that completes the model call but fails on+ the way back re-runs it; `flow-run-ai-usage-extractor` derives AI Credits from step outputs, so the+ customer is billed once and we are charged twice. This needs an explicit guard — an idempotency key or+ a dedupe on the job — and it is not optional.+- **Each step needs a backstop timeout**, as `run-agent.ts` does with its 3-hour ceiling. The earlier+ "inherit the flow timeout" answer only made sense for in-band execution and does not apply here.+- Every action's `run()` is invoked twice — once to dispatch, once to read `context.resumePayload` — so+ each carries two distinct branches.+- **No new piece-framework API, and no framework version bump.** This is the property the decision was+ made for.+- `packages/server/sandbox` is untouched: no engine→worker RPC direction, and no handler injected down+ through `createSandboxRuntime` → `createSandboxManager` → `createSandboxForJob` → `createSandbox`.+- **Partial progress becomes available for free.** The Agent already streams into the builder through+ `updateFlowStepProgress`; a slow Extract Structured Data can do the same.+- Provider errors reach the user as strings through the resume payload, losing `ActivepiecesError` codes+ and provider detail. Worth shaping the failure payload deliberately rather than copying+ `throw new Error(result.failure)`.++## See also++- [AI & Intelligence](../ai-intelligence/index.md)+- [000036 — The worker-side AI path is Community-Edition core](./000036-the-worker-side-ai-path-is-community-edition-core.md)diff --git a/brain/knowledge/decisions/000036-the-worker-side-ai-path-is-community-edition-core.md b/brain/knowledge/decisions/000036-the-worker-side-ai-path-is-community-edition-core.mdnew file mode 100644index 00000000000..8bef94d03eb--- /dev/null+++ b/brain/knowledge/decisions/000036-the-worker-side-ai-path-is-community-edition-core.md@@ -0,0 +1,57 @@+---+title: The worker-side AI path is Community-Edition core+icon: 🧱+status: accepted+---++## Decision++The route, job type, resume path and provider-credential resolver that let the worker run AI calls live+in **CE core, outside `src/app/ee/`** — even though every equivalent on the Agent path is Enterprise code.++## Context++Agreed 2026-09-08, alongside+[000035](./000035-direct-ai-steps-reuse-the-agents-suspend-and-resume-path.md), which puts the Direct AI+steps on the same suspend-and-resume route the Agent uses. That makes this decision sharper, not softer:+the pattern is being copied from code that is entirely Enterprise, into a place where it cannot be.++`agentModule`, which owns `POST /v1/agents/runs`, is registered only in the `CLOUD` and `ENTERPRISE`+branches of `app.ts`; on Community it is simply absent and the route 404s. `getAgentConfig`,+`saveAgentFile` and `resumeFlowStep` are likewise EE RPC handlers, each keyed on an agent conversation+row. That placement is correct for the Agent, which is an EE feature.++Ask AI, Summarize Text, Classify Text, Extract Structured Data and Generate Image are not. They ship on+Community today.++## Why++Putting the new path where the Agent's sits would silently remove five shipped Community actions — a+breaking change for self-hosters on the most-used AI steps.++The alternative was to leave Community on the in-sandbox path and move only EE. That was rejected+because it preserves `ai-sdk.ts` and the `ai@6` vs `ai@7` split forever, and removing that duplication is+the primary reason for the work. Shipping two execution paths would also mean maintaining both+indefinitely.++The price is that the Agent's EE helpers cannot be reused as they stand.++## Consequences++- The work is materially larger than "copy what the Agent does" — there are no `ee/` shortcuts, and every+ new surface must be edition-neutral. `getAgentConfig`, `saveAgentFile` and `resumeFlowStep` all key off+ an agent conversation row, so all three are rebuilt rather than reused.+- A new provider-resolution method on `WorkerToApiContract`, distinct from `getAgentConfig` and not tied+ to a conversation.+- The file-save path must be keyed on `projectId`/`runId` rather than `conversationId`, and must re-add+ the `AP_MAX_FILE_SIZE_MB` limit that `saveAgentFile` skips — otherwise Generate Image silently gains+ unbounded file writes.+- Community self-hosters get AI Provider credentials out of the sandbox, which was never previously on+ offer.+- The engine-facing `GET /v1/ai-providers/:provider/config` can only be closed once **every** edition is+ off it, so that deletion is a late layer of the stack, after the migration has promoted.++## See also++- [AI Providers](../ai-intelligence/ai-providers.md)+- [Platform, Editions & EE](../platform-editions-ee/index.md)diff --git a/brain/knowledge/flows-execution/flows.md b/brain/knowledge/flows-execution/flows.mdindex 3cad830c5a0..b8700f2ae25 100644--- a/brain/knowledge/flows-execution/flows.md+++ b/brain/knowledge/flows-execution/flows.md@@ -23,6 +23,7 @@ Flows are the core automation primitive: a versioned directed graph of trigger +- **Step settings autosave from inside the form resolver, on every validating `setValue`.** `step-settings/index.tsx` runs `applyOperation(UPDATE_ACTION/UPDATE_TRIGGER)` in its `resolver` whenever the new values differ from the last saved snapshot — it is *not* gated on `isDirty` or on a submit. Any transient value a component writes with `shouldValidate: true` is therefore persisted immediately, including one it intends to overwrite a moment later from an async response.- **A CODE step's compiled size is its `packageJson`, not its code — bundling *inlines* `node_modules`, it does not exclude it.** This gets assumed backwards a lot: there is no `node_modules` at runtime precisely *because* esbuild inlines every dependency into the step's `index.js`. Measured on cloud, Aug 2026: a step with **1,870 characters** of user source and `{"pdfkit":"0.14.0","aws-sdk":"2.1531.0","uuid":"9.0.1"}` compiles to **24.13 MB**, of which 24.13 MB is `node_modules` — **21.16 MB of it `aws-sdk` alone**. v2 of that SDK resolves its ~200 service clients by dynamic `require`, so esbuild cannot tree-shake it and inlines all of them; `@aws-sdk/client-*` (v3) would be a few hundred KB. Fleet-wide there were 13,918 compiled steps totalling 1.4 GB, **61 of them over 10 MB**, and per *flow* the totals reach **190.7 MB across 40 code steps**. That per-flow number is the one that matters operationally, because `flowBundleStore.publish` holds a flow's entire compiled output in memory at once (three copies — see the OOM gotcha on [[workers]]). To find the offenders: esbuild leaves `// node_modules/<pkg>/…` markers in the output, so you can attribute bytes per package by summing the lines between markers.- **Step output nesting (schema v21+)**: every step output is wrapped as `{ output, error? }`; expressions must use the `['output']` accessor. The v20→v21 migration rewrites existing expressions via `expression-rewriter`.+- **Migrations run on every single-version read, including the worker's own `getFlowVersion`** (`findOne` → `flowVersionMigrationService.migrate`). So no run can execute an unmigrated version, and restoring an old version migrates it forward too. The listing path is the exception: `flowVersionService.list()` paginates the repository directly and hands back whatever schema version the row holds, so a caller reading the version history can see unmigrated rows. The result is persisted, then short-circuits at `LATEST_FLOW_SCHEMA_VERSION`. The old version is saved to `backupFiles[oldSchemaVersion]` first — **that** is what a restore reads, so there's no need to keep an old code path alive "just in case". Nothing restores on its own: `flowVersionBackupService.get()` has no callers, so recovering a version is a deliberate manual step. A migration that throws pages on-call (`FLOW_MIGRATION_FAILED`).- **Continue on Failure**: CODE/PIECE steps with `continueOnFailure.value: true` carry `onSuccess`/`onFailure` sub-trees under `settings.errorHandlingOptions.continueOnFailureBranches`.- **`addActionUtils.clone()` is the single chokepoint for renaming copied steps and rewriting their `{{ }}` references** — paste, duplicate step, and duplicate branch all route through it. It walks the **whole `settings`** deliberately, not just `settings.input`: router conditions live at `settings.branches[].conditions[][].firstValue/.secondValue` and loop expressions at `settings.items`, and an `'input' in settings` guard silently skipped both (GIT-1075). Two things to respect when touching it: `settings.sourceCode` is excluded on purpose (it holds a user program, and a literal `{{ … }}` in a code step was being rewritten), and the remap must stay a **single pass** over the name map — applying one rename at a time rewrites its own output whenever a copied step's new name equals another copied step's old name, which happens on cross-flow paste into a flow that lacks the clipboard's names.- **Paste order follows selection order, not flow order.** `_getActionsForCopy`'s `.sort((a, b) => allSteps.indexOf(a) - ...)` compares deep clones, so `indexOf` is always `-1` and the sort is a no-op. Harmless for a single step; it decides the chaining order for a multi-step paste.diff --git a/brain/knowledge/pieces-engine/pieces.md b/brain/knowledge/pieces-engine/pieces.mdindex 822a042c5fa..88a8f132fca 100644--- a/brain/knowledge/pieces-engine/pieces.md+++ b/brain/knowledge/pieces-engine/pieces.md@@ -40,6 +40,8 @@ The metadata catalog of automation integrations ("pieces") — each a named inte- **Editing `matchPieceName`: the ≥3-character guard is asymmetric on purpose — naming tokens only, never `wholeNameTyped` coverage.** Applying it to both drops every piece with a two-letter name word (`Bland AI`, `Hume AI`, `Microsoft Power BI` — 29 queries regressed in one measured pass), because a two-letter token like `ai` must still count as covering the name word `AI` even though it is too short to *name* a piece on its own. The guard exists only to stop short tokens naming pieces they have nothing to do with. Related, and **not worth fixing**: `tokenizeSearchQuery` splits the query on whitespace while display names split on non-alphanumerics, so a literally-typed `quickbooks online (sandbox) find` leaves the token `(sandbox)`, fails full-name coverage and drops the piece. Only 6 pieces have parentheses (two of them `(Legacy)`/`(Deprecated)`), and every query a human actually types — `quickbooks find`, `quickbooks sandbox find`, `http send`, `approval wait` — finds them at rank 1-3. It surfaces only in generated corpora that build queries by lowercasing display names; do not mistake it for a real defect the way one sweep here did.- **Five frontend surfaces still render the whole ~700-piece catalogue into the DOM, and `usePieces({})` with no `searchQuery` hands them all of it.** The virtualization primitives exist (`VirtualizedScrollArea` in the builder's `pieces-card-list`, `VirtualizedList` in the MCP pieces tab, `virtualizeRows` on `DataTable`) — these just do not use them: the MCP-server `PiecesShowcase` tiles every piece into two masked rows on page load, `NewConnectionDialog` grids every piece that has `auth` as 150x150 cards, project-settings Pieces passes `hidePagination` to a `DataTable` **without** `virtualizeRows` (which defaults to `false`, unlike the platform-admin pieces tables), and both the connections piece filter (`DataTableSelectPopover`) and the piece-selector customization dialog mount every piece as a `CommandItem` — cmdk then rescores all of them per keystroke. Separately, the builder's Explore tab is non-virtualized *and correct in production* (it only ever holds Popular + Highlights), but `getExploreTabContent` has `metadata: environment === ApEnvironment.DEVELOPMENT ? queryResult : []` — so locally Popular **is** the entire catalogue. That is why the Explore tab feels sluggish in dev and fine on cloud; do not chase it as a production regression.+- **`piece-upgrade-register.json` has two consumers, not one.** The upgrade/downgrade dialog is the obvious one; the other is `migrate-v23`, which sits in the flow migration chain — so the register rewrites `pieceVersion` on every flow-version read, not only when someone clicks something. That makes regenerating it a live change to running flows. It also means a migration that pins a version can be undone by a later one in the same `apply()` pass: `migrate-v22` hands off at schemaVersion 23 and `migrate-v23`'s `targetSchemaVersion` is 23, so both run in one pass. Harmless only because the register's highest AI entry is `0.4.4` — add entries and v23 starts upgrading what v22 just pinned. **Pin versions in a migration of your own, appended last; leave the register alone.**+- **`ctx.files.write()` returns a URL served as `application/octet-stream`, so a vendor that sniffs Content-Type will reject it.** The signed read URL (`v1/files/{id}?token=`) carries no file extension, and on S3/R2 storage it 307-redirects to presigned storage where the real filename rides only on `response-content-disposition`. WhatsScale's `/make/prepareFile` refuses it outright — `"URL did not return an image, video, document, or audio file. Got content-type: application/octet-stream" (400)` — unless an explicit `mediaType` is passed alongside the URL. Any piece that hands an AP-hosted file URL to a third party has to tell that API the media type out-of-band; do not assume the URL is self-describing. Verified live 2026-08-24 on the WhatsScale piece: identical URL, 400 without `mediaType`, delivered correctly with it.### Key files