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(engine): run code steps on deno by default and log failed code steps (#16573)
Chaker Atallah9c1998726c53
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex bed2749ba3b..616121ee9eb 100644--- a/docs/install/reference/breaking-changes-unreleased.mdx+++ b/docs/install/reference/breaking-changes-unreleased.mdx@@ -8,6 +8,55 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut## What has changed?+#### Code steps run on Deno by default++A code step without an explicit `useDeno` flag now executes in the Deno runtime instead of the legacy Node sandbox — effectively migrating every existing flow automatically, with no data rewrite. The legacy executors are still shipped: setting `useDeno: false` on a step keeps it on the previous Node/v8-isolate path, and the admin `revert-from-deno` endpoint writes exactly that flag, so individual flows can still be opted out. Failed code steps are now also logged as structured `Code step failed` warnings (flow run, flow version, project, step name, runtime, and the error message) so they can be found and analyzed in centralized logs.++#### What you need to do++Most code steps keep working unchanged: sources are transpiled to CommonJS, so Node-style code (`require`, `exports`, `module.exports`, `__dirname`, even undeclared variable assignments) runs as before, and dependencies from the step's `package.json` install and resolve as before. What actually changes depends on your `AP_EXECUTION_MODE` — the two legacy sandboxes were very different, so the review lists differ.++**If you run `UNSANDBOXED` or `SANDBOX_PROCESS`** — the legacy sandbox here was an unrestricted Node child process, so this is where restrictions are new:++- **Environment variables are no longer inherited.** The legacy sandbox exposed the worker container's entire environment to `process.env`; the Deno sandbox exposes only `PATH`. A code step that reads a custom env var now gets `undefined`. To pass variables through, set `AP_SANDBOX_PROPAGATED_ENV_VARS` (a comma-separated list of names) on the **API** container — it ships the list to workers — and make sure the variables themselves are set in the **worker** container's environment, where their values are read. In a single-container deployment, set both on that container.+- **Filesystem access is confined to the OS temp directory.** Legacy code steps could read and write any path the worker could; Deno grants read/write only under `os.tmpdir()`. Reads or writes elsewhere fail with a `NotCapable` permission error. Write scratch files with `os.tmpdir()` + `path.join` instead of hardcoded absolute paths.+- **Spawning processes is denied.** `child_process` (`spawn`, `exec`, …) worked before; the Deno sandbox has no run permission, so it fails with `NotCapable`.+- Network access and memory stay as they were: outbound requests are allowed, and the step's heap is uncapped.++**If you run `SANDBOX_CODE_ONLY` or `SANDBOX_CODE_AND_PROCESS`** — the legacy sandbox here was a v8 isolate with no Node APIs at all, so little is newly restricted and steps gain capabilities:++- Filesystem, network, environment and process access stay denied, exactly as in the isolate.+- The 128MB heap cap is unchanged, but an over-limit step now dies with a process signal error instead of an isolate memory error — update any alerting that matches on the old message.+- Steps gain working `require` of their installed `package.json` dependencies and of Node built-ins for pure computation (`node:crypto`, `node:path`, …), which the isolate could not do.++**In every mode:**++- **Steps using top-level `await` run as strict ES modules** (they cannot be transpiled to CommonJS). Inside such a step: assigning to an undeclared variable throws `ReferenceError` instead of creating a global, and `exports`, `module`, `__dirname`, `__filename` are unavailable (`require` keeps working — the sandbox provides it as a global). For example, this step ran on the legacy sandbox and now fails — the `await` outside `code` is what forces strict ES module mode, and the first undeclared assignment then throws:++ ```ts+ const settings = await fetch('https://example.com/settings.json').then((res) => res.json())++ export const code = async (inputs) => {+ total = settings.base + inputs.amount // ReferenceError: total is not defined+ const where = __dirname // ReferenceError: __dirname is not defined+ module.exports.extra = total // ReferenceError: module is not defined+ return { total }+ }+ ```++ Moving the awaited call inside `code` lets the step transpile to CommonJS again, where all of the above keep working; declaring the variable is the fix that works in both modes:++ ```ts+ export const code = async (inputs) => {+ const settings = await fetch('https://example.com/settings.json').then((res) => res.json())+ const total = settings.base + inputs.amount+ return { total }+ }+ ```+- **Exotic Node internals may be missing.** Deno's Node compatibility layer covers the standard library that pieces and typical steps use, but low-level APIs (`process.binding`, `node:vm`, `node:cluster`, parts of `node:worker_threads`) and native addons that predate Node-API are not guaranteed. Steps or dependencies relying on them need review.+- **Custom deployments** that do not use the official Docker images must provide a Deno binary and point `AP_DENO_PATH` at it; without it every code step fails at spawn.++To find affected steps after upgrading, search your logs for the structured `Code step failed` warning — it carries the flow run, flow version, project, step name, the runtime that executed the step (`codeRuntime: deno|legacy`), and the error message, so you can group failures by step and error. To pin a misbehaving step to the legacy runtime while you fix it (available on every edition), set `AP_API_KEY` in your environment and call `POST /v1/admin/flows/revert-from-deno` with the `api-key` header and a body of exactly one of `flowIds`, `projectId`, or `platformId`; this sets `useDeno: false` on the affected steps, and `migrate-to-deno` moves them back.#### Each chat keeps the AI model and key it started onA chat used to run on whatever key was the **Default AI key** at the time of each message. Now a chat remembers the key and model it first ran on. Changing the Default AI key affects new chats only. An existing chat moves to the new default only when its key is deleted, or no longer covers the chat's project or model.diff --git a/packages/server/api/src/app/app.ts b/packages/server/api/src/app/app.tsindex e7ab40f2502..bbe1ef4919b 100644--- a/packages/server/api/src/app/app.ts+++ b/packages/server/api/src/app/app.ts@@ -59,6 +59,7 @@ import { pieceSetRequiredActions } from './ee/pieces/piece-set/piece-set-requireimport { pieceSetModule } from './ee/pieces/piece-set/piece-set.module'import { platformPieceModule } from './ee/pieces/platform-piece-module'import { adminPlatformModule } from './ee/platform/admin/admin-platform.controller'+import { denoMigrationModule } from './ee/platform/admin/deno-migration.module'import { adminPlatformTemplatesCloudModule } from './ee/platform/admin/templates/admin-platform-templates-cloud.module'import { autumnBillingProvider } from './ee/platform/platform-plan/billing-providers/autumn-billing'import { platformPlanModule } from './ee/platform/platform-plan/platform-plan.module'@@ -350,6 +351,7 @@ export const setupApp = async (app: FastifyInstance): Promise<FastifyInstance> =switch (edition) {case ApEdition.CLOUD:await app.register(adminPlatformModule)+ await app.register(denoMigrationModule)await app.register(pieceUpgradeModule)await app.register(adminPlatformTemplatesCloudModule)await app.register(platformProjectModule)@@ -394,6 +396,7 @@ export const setupApp = async (app: FastifyInstance): Promise<FastifyInstance> =systemJobHandlers.registerJobHandler(SystemJobName.HARD_DELETE_PLATFORM, (data) => platformTeardownJobs(app.log).hardDeletePlatformHandler(data))breakcase ApEdition.ENTERPRISE:+ await app.register(denoMigrationModule)await app.register(pieceUpgradeModule)await app.register(platformPlanModule)await app.register(platformProjectModule)@@ -433,6 +436,7 @@ export const setupApp = async (app: FastifyInstance): Promise<FastifyInstance> =eventDestinationHooks.set(eventDestinationEntitlementHooks)breakcase ApEdition.COMMUNITY:+ await app.register(denoMigrationModule)await app.register(platformProjectModule)await app.register(communityPiecesModule)await app.register(otpModule)diff --git a/packages/server/api/src/app/ee/platform/admin/admin-platform.controller.ts b/packages/server/api/src/app/ee/platform/admin/admin-platform.controller.tsindex b105e702516..a700b520103 100644--- a/packages/server/api/src/app/ee/platform/admin/admin-platform.controller.ts+++ b/packages/server/api/src/app/ee/platform/admin/admin-platform.controller.ts@@ -17,7 +17,6 @@ import { AgentConversationEntity } from '../../agent/agent-conversation-entity'import { chatAnalyticsBulkSync } from '../../agent/chat-analytics-sync'import { CANARY_WORKER_GROUP_ID, workerGroupService } from '../platform-plan/worker-group.service'import { adminPlatformService } from './admin-platform.service'-import { denoMigrationService } from './deno-migration.service'const API_KEY_HEADER = 'api-key'const API_KEY = system.get(AppSystemProp.API_KEY)@@ -86,16 +85,6 @@ const adminPlatformController: FastifyPluginAsyncZod = async (return res.status(StatusCodes.OK).send()})- app.post('/flows/migrate-to-deno', MigrateFlowsDenoRequest, async (req, res) => {- const result = await denoMigrationService(req.log).migrateToDeno(req.body)- return res.status(StatusCodes.OK).send(result)- })-- app.post('/flows/revert-from-deno', MigrateFlowsDenoRequest, async (req, res) => {- const result = await denoMigrationService(req.log).revertFromDeno(req.body)- return res.status(StatusCodes.OK).send(result)- })-app.post('/chat/sync-all', SyncAllConversationsRequest, async (req, res) => {const PAGE_SIZE = 100const conversationRepo = repoFactory(AgentConversationEntity)@@ -224,21 +213,6 @@ const CreatePieceRequest = {},}-const MigrateFlowsDenoRequest = {- schema: {- body: z.object({- platformId: z.string().optional(),- projectId: z.string().optional(),- flowIds: z.array(z.string()).optional(),- }).refine((body) => [body.platformId, body.projectId, body.flowIds].filter((value) => !isNil(value)).length === 1, {- message: 'exactly one of platformId, projectId or flowIds must be provided',- }),- },- config: {- security: securityAccess.public(),- },-}-const SyncAllConversationsRequest = {config: {security: securityAccess.public(),diff --git a/packages/server/api/src/app/ee/platform/admin/deno-migration.module.ts b/packages/server/api/src/app/ee/platform/admin/deno-migration.module.tsnew file mode 100644index 00000000000..00836a098ed--- /dev/null+++ b/packages/server/api/src/app/ee/platform/admin/deno-migration.module.ts@@ -0,0 +1,55 @@+import { isNil } from '@activepieces/core-utils'+import { FastifyReply, FastifyRequest } from 'fastify'+import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'+import { StatusCodes } from 'http-status-codes'+import { z } from 'zod'+import { securityAccess } from '../../../core/security/authorization/fastify-security'+import { system } from '../../../helper/system/system'+import { AppSystemProp } from '../../../helper/system/system-props'+import { denoMigrationService } from './deno-migration.service'++const API_KEY_HEADER = 'api-key'+const API_KEY = system.get(AppSystemProp.API_KEY)++async function checkAdminApiKeyPreHandler(+ req: FastifyRequest,+ res: FastifyReply,+): Promise<void> {+ const key = req.headers[API_KEY_HEADER] as string | undefined+ if (key !== API_KEY || isNil(API_KEY)) {+ await res.status(StatusCodes.FORBIDDEN).send({ message: 'Forbidden' })+ throw new Error('Forbidden')+ }+}++export const denoMigrationModule: FastifyPluginAsyncZod = async (app) => {+ app.addHook('preHandler', checkAdminApiKeyPreHandler)+ await app.register(denoMigrationController, { prefix: '/v1/admin/flows' })+}++const denoMigrationController: FastifyPluginAsyncZod = async (app) => {+ app.post('/migrate-to-deno', MigrateFlowsDenoRequest, async (req, res) => {+ const result = await denoMigrationService(req.log).migrateToDeno(req.body)+ return res.status(StatusCodes.OK).send(result)+ })++ app.post('/revert-from-deno', MigrateFlowsDenoRequest, async (req, res) => {+ const result = await denoMigrationService(req.log).revertFromDeno(req.body)+ return res.status(StatusCodes.OK).send(result)+ })+}++const MigrateFlowsDenoRequest = {+ schema: {+ body: z.object({+ platformId: z.string().optional(),+ projectId: z.string().optional(),+ flowIds: z.array(z.string()).optional(),+ }).refine((body) => [body.platformId, body.projectId, body.flowIds].filter((value) => !isNil(value)).length === 1, {+ message: 'exactly one of platformId, projectId or flowIds must be provided',+ }),+ },+ config: {+ security: securityAccess.public(),+ },+}diff --git a/packages/server/api/src/app/ee/platform/admin/deno-migration.service.ts b/packages/server/api/src/app/ee/platform/admin/deno-migration.service.tsindex 5301b6b87dd..413158b05ce 100644--- a/packages/server/api/src/app/ee/platform/admin/deno-migration.service.ts+++ b/packages/server/api/src/app/ee/platform/admin/deno-migration.service.ts@@ -107,7 +107,7 @@ function setUseDenoOnCodeSteps({ flowVersion, useDeno }: { flowVersion: FlowVersfunction hasCodeStepToChange({ flowVersion, useDeno }: { flowVersion: FlowVersion, useDeno: boolean }): boolean {return flowStructureUtil.getAllSteps(flowVersion.trigger)- .some((step) => step.type === FlowActionType.CODE && (step.settings.useDeno === true) !== useDeno)+ .some((step) => step.type === FlowActionType.CODE && step.settings.useDeno !== useDeno)}type MigrateToDenoParams = {diff --git a/packages/server/api/src/app/flows/flow-run/flow-run-hooks.ts b/packages/server/api/src/app/flows/flow-run/flow-run-hooks.tsindex ae1398d64a1..e243270470f 100644--- a/packages/server/api/src/app/flows/flow-run/flow-run-hooks.ts+++ b/packages/server/api/src/app/flows/flow-run/flow-run-hooks.ts@@ -1,5 +1,5 @@import { isManualPieceTrigger, isNil, tryCatch } from '@activepieces/core-utils'-import { ApEdition, ConsumableFeatureId, FlowRun, FlowRunStatus, FlowTriggerType, isFailedState, isFlowRunStateTerminal, RunEnvironment, WebsocketClientEvent } from '@activepieces/shared'+import { ApEdition, ConsumableFeatureId, FlowActionType, FlowRun, FlowRunStatus, flowStructureUtil, FlowTriggerType, FlowVersion, isFailedState, isFlowRunStateTerminal, RunEnvironment, WebsocketClientEvent } from '@activepieces/shared'import dayjs from 'dayjs'import { FastifyBaseLogger } from 'fastify'import { websocketService } from '../../core/websockets.service'@@ -27,6 +27,7 @@ export const flowRunHooks = (log: FastifyBaseLogger) => ({})}if (isFailedState(flowRun.status) && flowRun.environment === RunEnvironment.PRODUCTION && !isNil(flowRun.failedStep)) {+ logFailedCodeStep({ log, flowRun, flowVersion })const date = dayjs(flowRun.created).toISOString()const issueToAlert = {projectId: flowRun.projectId,@@ -55,6 +56,25 @@ export const flowRunHooks = (log: FastifyBaseLogger) => ({},})+function logFailedCodeStep({ log, flowRun, flowVersion }: LogFailedCodeStepParams): void {+ if (isNil(flowVersion) || isNil(flowRun.failedStep)) {+ return+ }+ const failedStep = flowStructureUtil.getStep(flowRun.failedStep.name, flowVersion.trigger)+ if (isNil(failedStep) || failedStep.type !== FlowActionType.CODE) {+ return+ }+ log.warn({+ flowRun: { id: flowRun.id, status: flowRun.status, environment: flowRun.environment },+ flow: { id: flowRun.flowId },+ flowVersion: { id: flowRun.flowVersionId },+ project: { id: flowRun.projectId },+ step: { name: flowRun.failedStep.name },+ codeRuntime: failedStep.settings.useDeno !== false ? 'deno' : 'legacy',+ error: flowRun.failedStep.message,+ }, 'Code step failed')+}+async function trackProductionRunCredit(log: FastifyBaseLogger, flowRun: FlowRun): Promise<void> {const project = await projectService(log).getOne(flowRun.projectId)if (isNil(project)) {@@ -69,3 +89,10 @@ async function trackProductionRunCredit(log: FastifyBaseLogger, flowRun: FlowRunproperties: toFlowRunCreditProperties({ platformId: project.platformId, flowRun }),})}+++type LogFailedCodeStepParams = {+ log: FastifyBaseLogger+ flowRun: FlowRun+ flowVersion: FlowVersion | null+}diff --git a/packages/server/api/src/app/flows/pre-warm-workers.ts b/packages/server/api/src/app/flows/pre-warm-workers.tsindex 3eb3e340548..8ecac101f19 100644--- a/packages/server/api/src/app/flows/pre-warm-workers.ts+++ b/packages/server/api/src/app/flows/pre-warm-workers.ts@@ -153,7 +153,7 @@ function extractCodeSteps(flowVersion: FlowVersion): PrewarmCodeStep[] {sourceCode: step.settings.sourceCode,flowVersionId: flowVersion.id,flowVersionState: flowVersion.state,- useDeno: step.settings.useDeno ?? false,+ useDeno: step.settings.useDeno !== false,}))}diff --git a/packages/server/api/test/integration/cloud/flow/migrate-to-deno.test.ts b/packages/server/api/test/integration/cloud/flow/migrate-to-deno.test.tsindex 4c24e169bb0..cc468dc3c09 100644--- a/packages/server/api/test/integration/cloud/flow/migrate-to-deno.test.ts+++ b/packages/server/api/test/integration/cloud/flow/migrate-to-deno.test.ts@@ -187,6 +187,19 @@ describe('POST /v1/admin/flows/migrate-to-deno', () => {expect(secondRevert.json()).toEqual({ flowsProcessed: 1, flowVersionsMigrated: 0, notifiedFlows: 0 })})+ it('reverts a flow whose code steps never set useDeno, since an unset flag now runs on deno', async () => {+ const ctx = await createTestContext(app!)+ const { flow, publishedVersion } = await setupFlowWithPublishedLatestVersion(ctx)++ const revertResponse = await postRevertFromDeno({ flowIds: [flow.id] })++ expect(revertResponse.statusCode).toBe(StatusCodes.OK)+ expect(revertResponse.json()).toEqual({ flowsProcessed: 1, flowVersionsMigrated: 1, notifiedFlows: 1 })++ const revertedVersion = await db.findOneByOrFail<FlowVersion>('flow_version', { id: publishedVersion.id })+ expect(getCodeStep(revertedVersion)?.settings.useDeno).toBe(false)+ })+it('is idempotent: a second run reports zero migrated versions', async () => {const ctx = await createTestContext(app!)const { flow } = await setupFlowWithDraftAndPublishedVersions(ctx)diff --git a/packages/server/engine/src/lib/handler/code-executor.ts b/packages/server/engine/src/lib/handler/code-executor.tsindex 3cc0dc4fc01..02875fad2d1 100644--- a/packages/server/engine/src/lib/handler/code-executor.ts+++ b/packages/server/engine/src/lib/handler/code-executor.ts@@ -54,7 +54,7 @@ const executeAction: ActionHandler<CodeAction> = async ({ action, executionState// code-cache sink guard already block this upstream; this is the runtime backstop.throw new ExecutionError('InvalidStepName', `Invalid code step name: "${action.name}"`, ExecutionErrorType.USER)}- const useDeno = action.settings.useDeno === true+ const useDeno = action.settings.useDeno !== falseconst stepDir = path.resolve(`${constants.baseCodeDirectory}/${constants.flowVersionId}/${action.name}`)const artifactPath = useDeno? resolveDenoArtifactPath(stepDir)diff --git a/packages/server/engine/test/handler/flow-codes.test.ts b/packages/server/engine/test/handler/flow-codes.test.tsindex e4a0f7f002b..b13bfe1af83 100644--- a/packages/server/engine/test/handler/flow-codes.test.ts+++ b/packages/server/engine/test/handler/flow-codes.test.ts@@ -19,7 +19,7 @@ describe('codeExecutor', () => {expect(result.steps.echo_step.output).toEqual({ 'key': 3 })})- it('should execute a legacy step (useDeno unset) from the compiled index.js artifact', async () => {+ it('should execute a legacy step (useDeno explicitly false) from the compiled index.js artifact', async () => {const result = await codeExecutor.handle({action: buildCodeAction({name: 'echo_step_legacy',diff --git a/packages/server/engine/test/handler/test-helper.ts b/packages/server/engine/test/handler/test-helper.tsindex 9a2a0559b5e..75605e9fb8c 100644--- a/packages/server/engine/test/handler/test-helper.ts+++ b/packages/server/engine/test/handler/test-helper.ts@@ -126,7 +126,7 @@ export function buildCodeAction({ name, input, skip, nextAction, errorHandlingOpcode: '',},errorHandlingOptions,- useDeno: useDeno ?? true,+ ...(useDeno === undefined ? {} : { useDeno }),},nextAction,valid: true,diff --git a/packages/server/sandbox/src/lib/cache/flow/flow-provisioning.ts b/packages/server/sandbox/src/lib/cache/flow/flow-provisioning.tsindex b265be23e20..9e581ef11fc 100644--- a/packages/server/sandbox/src/lib/cache/flow/flow-provisioning.ts+++ b/packages/server/sandbox/src/lib/cache/flow/flow-provisioning.ts@@ -103,7 +103,7 @@ function extractCodeArtifacts(flowVersion: FlowVersion): CodeArtifact[] {sourceCode: step.settings.sourceCode,flowVersionId: flowVersion.id,flowVersionState: flowVersion.state,- useDeno: step.settings.useDeno === true,+ useDeno: step.settings.useDeno !== false,}))}diff --git a/packages/server/sandbox/test/lib/cache/flow/flow-provisioning.test.ts b/packages/server/sandbox/test/lib/cache/flow/flow-provisioning.test.tsindex e6da1914cc7..7c6d9037ffa 100644--- a/packages/server/sandbox/test/lib/cache/flow/flow-provisioning.test.ts+++ b/packages/server/sandbox/test/lib/cache/flow/flow-provisioning.test.ts@@ -86,7 +86,7 @@ describe('flowProvisioning.resolve', () => {sourceCode: { code: 'export const code = async () => 1', packageJson: '{}' },flowVersionId: 'fv1',flowVersionState: FlowVersionState.LOCKED,- useDeno: false,+ useDeno: true,}])expect(resolved.publishBundle).toBeNull()expect(resolved.pieces).toEqual([httpPiece])diff --git a/packages/server/worker/src/lib/execute/jobs/execute-action.ts b/packages/server/worker/src/lib/execute/jobs/execute-action.tsindex 66a9f5d2697..b8b4107388e 100644--- a/packages/server/worker/src/lib/execute/jobs/execute-action.ts+++ b/packages/server/worker/src/lib/execute/jobs/execute-action.ts@@ -65,7 +65,7 @@ async function resolveCodeStep({ step, platformId }: ResolveCodeStepParams): ProsourceCode: step.settings.sourceCode,flowVersionId: namespace,flowVersionState: DEFAULT_MCP_DATA.flowVersionState,- useDeno: step.settings.useDeno === true,+ useDeno: step.settings.useDeno !== false,}],}}