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

34.0 KB
Raw Blame
import { isNil, spreadIfDefined } from '@activepieces/core-utils'
import { PieceMetadata } from '@activepieces/pieces-framework'
import { aiCostReporter, aiObservability, apDayjs, apVersionUtil, onCallService, UNKNOWN_VERSION, wideEvent } from '@activepieces/server-utils'
import { AddAllowedEmbedOriginsRequestBody, ApEdition, ApEnvironment, AppConnectionWithoutSensitiveData, ApplicationEventName, AuditLogRetentionUpdatedEvent, ConnectionDeletedEvent, ConnectionUpsertedEvent, Flow, FlowActivatedEvent, FlowCreatedEvent, FlowDeactivatedEvent, FlowDeletedEvent, FlowPiecesRevertedEvent, FlowPiecesUpgradedEvent, FlowPublishedEvent, FlowRun, FlowRunFinishedEvent, FlowRunRetriedEvent, FlowRunStartedEvent, FlowUpdatedEvent, Folder, FolderCreatedEvent, FolderDeletedEvent, FolderUpdatedEvent, GitRepoWithoutSensitiveData, ProjectMember, ProjectRelease, ProjectReleaseEvent, ProjectRoleEvent, ProjectWithLimits, SigningKeyEvent, SignUpEvent, Template, UserEmailVerifiedEvent, UserInvitation, UserPasswordResetEvent, UserSignedInEvent, UserWithMetaInformation, VariableWithoutSensitiveData } from '@activepieces/shared'
import replyFrom from '@fastify/reply-from'
import swagger from '@fastify/swagger'
import { createAdapter } from '@socket.io/redis-adapter'
import { FastifyBaseLogger, FastifyInstance, FastifyRequest, HTTPMethods } from 'fastify'
import { jsonSchemaTransform, jsonSchemaTransformObject } from 'fastify-type-provider-zod'
import Mustache from 'mustache'
import { globalRegistry } from 'zod/v4/core'
import { agentsModule } from './agents/agents-module'
import { installAiKeyHealthReporter } from './ai/ai-key-health-reporter'
import { aiProviderService } from './ai/ai-provider-service'
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 { aiUsageJobs } from './ai/usage/ai-usage-jobs'
import { aiUsageModule } from './ai/usage/ai-usage.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'
import { platformAppConnectionModule } from './app-connection/platform-app-connection.module'
import { authenticationModule } from './authentication/authentication.module'
import { otpModule } from './authentication/otp/otp-module'
import { passwordlessAuthModule } from './authentication/passwordless-auth.module'
import { verifiedDomainHooks } from './authentication/verified-domain-hooks'
import { canaryRoutingMiddleware } from './core/canary/canary-routing.middleware'
import { collaborativeModule } from './core/collaborative/collaborative.module'
import { oidcModule } from './core/security/oidc/oidc.module'
import { rateLimitModule } from './core/security/rate-limit'
import { authenticationMiddleware } from './core/security/v2/authn/authentication-middleware'
import { authorizationMiddleware } from './core/security/v2/authz/authorization-middleware'
import { backgroundMigrationRunner } from './database/background-migration-runner'
import { distributedLock, redisConnections } from './database/redis-connections'
import { agentConversationCreditsHooks } from './ee/agent/agent-conversation-credits'
import { agentEvalModule } from './ee/agent/agent-eval-controller'
import { agentHelpers } from './ee/agent/agent-helpers'
import { assertAgentsResolveInProject } from './ee/agent/agent-service'
import { agentModule } from './ee/agent/agent.module'
import { alertsModule } from './ee/alerts/alerts-module'
import { apiKeyModule } from './ee/api-keys/api-key-module'
import { platformOAuth2Service } from './ee/app-connections/platform-oauth2-service'
import { appSumoModule } from './ee/appsumo/appsumo.module'
import { auditEventModule } from './ee/audit-logs/audit-event-module'
import { enterpriseLocalAuthnModule } from './ee/authentication/enterprise-local-authn/enterprise-local-authn-module'
import { federatedAuthModule } from './ee/authentication/federated-authn/federated-authn-module'
import { rbacMiddleware } from './ee/authentication/project-role/rbac-middleware'
import { authnSsoSamlModule } from './ee/authentication/saml-authn/authn-sso-saml-module'
import { authnSsoSamlService } from './ee/authentication/saml-authn/authn-sso-saml-service'
import { embedSubdomainModule } from './ee/embed-subdomain/embed-subdomain.module'
import { embedSubdomainService } from './ee/embed-subdomain/embed-subdomain.service'
import { enterpriseFlagsHooks } from './ee/flags/enterprise-flags.hooks'
import { flowApprovalModule } from './ee/flows/flow-approval/flow-approval.module'
import { eeFlowPublishHook } from './ee/flows/flow-approval/flow-publish-hook'
import { globalConnectionModule } from './ee/global-connections/global-connection-module'
import { appearanceHelper } from './ee/helper/appearance-helper'
import { licenseKeyUsageReportModule } from './ee/license-key-usage-report/license-key-usage-report-module'
import { managedAuthnModule } from './ee/managed-authn/managed-authn-module'
import { oauthAppModule } from './ee/oauth-apps/oauth-app.module'
import { pieceSetRequiredActions } from './ee/pieces/piece-set/piece-set-required-actions'
import { 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'
import { platformTeardownJobs } from './ee/platform/platform-teardown-jobs'
import { eventDestinationEntitlementHooks } from './ee/platform-webhooks/event-destination-entitlement-hooks'
import { platformWebhooksModule } from './ee/platform-webhooks/platform-webhooks.module'
import { projectEnterpriseHooks } from './ee/projects/ee-project-hooks'
import { personalProjectsModule } from './ee/projects/personal-projects/personal-projects.module'
import { personalProjectsService } from './ee/projects/personal-projects/personal-projects.service'
import { platformProjectBackgroundJobs } from './ee/projects/platform-project-jobs'
import { platformProjectModule } from './ee/projects/platform-project-module'
import { projectMemberModule } from './ee/projects/project-members/project-member.module'
import { gitRepoModule } from './ee/projects/project-release/git-sync/git-sync.module'
import { projectReleaseModule } from './ee/projects/project-release/project-release.module'
import { projectReplaceModule } from './ee/projects/project-replace/project-replace.module'
import { projectRoleModule } from './ee/projects/project-role/project-role.module'
import { scimModule } from './ee/scim/scim-module'
import { secretManagersModule } from './ee/secret-managers/secret-managers.module'
import { signingKeyModule } from './ee/signing-key/signing-key-module'
import { userEnterpriseHooks } from './ee/users/ee-user-hooks'
import { userModule } from './ee/users/user.module'
import { eventDestinationHooks } from './event-destinations/event-destinations-hooks'
import { fileModule } from './file/file.module'
import { flagModule } from './flags/flag.module'
import { flagHooks } from './flags/flags.hooks'
import { flowPublishHooks, publishHooksFactory } from './flows/flow/flow-publish-hooks'
import { flowBackgroundJobs } from './flows/flow/flow.jobs'
import { humanInputModule } from './flows/flow/human-input/human-input.module'
import { flowRunModule } from './flows/flow-run/flow-run-module'
import { pieceUpgradeModule } from './flows/flow-version/piece-upgrade.module'
import { flowModule } from './flows/flow.module'
import { folderModule } from './flows/folder/folder.module'
import { domainHelper } from './helper/domain-helper'
import { exceptionHandler } from './helper/exception-handler'
import { clientLogsModule } from './helper/logs/client-logs.module'
import { openapiModule } from './helper/openapi/openapi.module'
import { rejectedPromiseHandler } from './helper/promise-handler'
import { system } from './helper/system/system'
import { AppSystemProp } from './helper/system/system-props'
import { SystemJobName } from './helper/system-jobs/common'
import { systemJobHandlers } from './helper/system-jobs/job-handlers'
import { SystemJobBackoff, systemJobsSchedule } from './helper/system-jobs/system-job'
import { systemSnapshot } from './helper/system-snapshot'
import { validateEnvPropsOnStartup } from './helper/system-validator'
import { shutdownTelemetry } from './helper/telemetry.utils'
import { knowledgeBaseModule } from './knowledge-base/knowledge-base.module'
import { mcpActivityController } from './mcp/activity/mcp-activity-controller'
import { mcpServerModule } from './mcp/mcp-module'
import { mcpOAuthApproveController } from './mcp/oauth/code/mcp-oauth-approve.controller'
import { mcpOAuthGrantsController } from './mcp/oauth/token/mcp-oauth-grants.controller'
import { communityPiecesModule } from './pieces/community-piece-module'
import { startDevPieceWatcher } from './pieces/dev-piece-watcher'
import { pieceModule } from './pieces/metadata/piece-metadata-controller'
import { pieceMetadataService } from './pieces/metadata/piece-metadata-service'
import { pieceSyncService } from './pieces/piece-sync-service'
import { billingProvider } from './platform/billing-provider'
import { piecesReportModule } from './platform/pieces-report/pieces-report.module'
import { platformConfigurationModule } from './platform/platform-configuration.module'
import { platformModule } from './platform/platform.module'
import { projectHooks } from './project/project-hooks'
import { storeEntryModule } from './store-entry/store-entry.module'
import { tablesModule } from './tables/tables.module'
import { templateModule } from './template/template.module'
import { toolSearchReindexJob } from './tool-search/tool-search-reindex.job'
import { appEventRoutingModule } from './trigger/app-event-routing/app-event-routing.module'
import { triggerModule } from './trigger/trigger.module'
import { platformUserModule } from './user/platform/platform-user-module'
import { userHooks } from './user/user-hooks'
import { invitationModule } from './user-invitations/user-invitation.module'
import { variableModule } from './variable/variable.module'
import { resumePageHooks } from './waitpoints/resume-page-hooks'
import { sweepOverdueDeadlines } from './waitpoints/waitpoint-deadline-sweep'
import { webhookModule } from './webhooks/webhook-module'
import { engineResponseWatcher } from './workers/engine-response-watcher'

import { workerCapacity } from './workers/machine/worker-capacity'
import { migrateQueuesAndRunConsumers, workerModule } from './workers/worker-module'

export const setupApp = async (app: FastifyInstance): Promise<FastifyInstance> => {

    app.addContentTypeParser('application/octet-stream', { parseAs: 'buffer' }, async (_request: FastifyRequest, payload: unknown) => {
        return payload as Buffer
    })

    registerOpenApiSchemas()

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    await app.register(swagger as any, {
        hideUntagged: true,
        transform: jsonSchemaTransform,
        transformObject: jsonSchemaTransformObject,
        openapi: {
            openapi: '3.1.0',
            servers: [
                {
                    url: 'https://cloud.activepieces.com/api',
                    description: 'Production Server',
                },
            ],
            components: {
                securitySchemes: {
                    apiKey: {
                        type: 'http',
                        description: 'Use your api key generated from the admin console',
                        scheme: 'bearer',
                    },
                },
                schemas: {
                    'global-connection': { $ref: '#/components/schemas/app-connection' },
                },
            },
            info: {
                title: 'Activepieces Documentation',
                version: '0.0.0',
            },
            externalDocs: {
                url: 'https://www.activepieces.com/docs',
                description: 'Find more info here',
            },
        },
    })


    await app.register(rateLimitModule)
    app.addHook('onResponse', async (request, reply) => {
        // eslint-disable-next-line                                                                                                                                                                                                                     
        reply.header('x-request-id', request.id)
    })
    app.addHook('onRequest', async (request, reply) => {
        const route = app.hasRoute({
            method: request.method as HTTPMethods,
            url: request.routeOptions.url!,
        })
        request.log = request.log.child({ route: request.routeOptions.url })
        if (!route) {
            return reply.code(404).send({
                statusCode: 404,
                error: 'Not Found',
                message: 'Route not found',
            })
        }
    })

    app.addHook('preHandler', authenticationMiddleware)

    // Enrich the current wide-event with tenant identifiers resolved by the auth middleware.
    // request.principal is set by authenticationMiddleware; for public routes it may be
    // undefined (the middleware returns early), so we guard with a try/catch.
    app.addHook('preHandler', (request, _reply, done) => {
        try {
            const principal = request.principal
            const projectId = extractProjectId(principal)
            const platformId = extractPlatformId(principal)
            wideEvent.set({
                ...spreadIfDefined('project', isNil(projectId) ? undefined : { id: projectId }),
                ...spreadIfDefined('platform', isNil(platformId) ? undefined : { id: platformId }),
                ...spreadIfDefined('principalType', principal?.type),
            })
        }
        catch {
            // principal getter may throw before auth completes — safe to ignore
        }
        done()
    })

    app.addHook('preHandler', authorizationMiddleware)
    app.addHook('preHandler', rbacMiddleware)

    const canaryAppUrl = system.get(AppSystemProp.CANARY_APP_URL)
    if (!isNil(canaryAppUrl)) {
        await app.register(replyFrom, { base: canaryAppUrl })
        app.addHook('preHandler', canaryRoutingMiddleware)
    }

    await systemJobsSchedule(app.log).init()
    await app.register(fileModule)
    await app.register(flagModule)
    await app.register(storeEntryModule)
    await app.register(folderModule)
    await pieceSyncService(app.log).setup()
    toolSearchReindexJob(app.log).register()
    // Boot backfill: build the tool-search index if the flag is on but it is empty or only partially
    // embedded (a populated deployment fires no sync delta, and a build that failed midway leaves rows
    // unembedded). Fire-and-forget — a no-op once fully built, and must never block or fail boot.
    rejectedPromiseHandler(toolSearchReindexJob(app.log).backfillIfNeeded(), app.log)
    await toolSearchReindexJob(app.log).scheduleRecurringReconcile()
    await pieceMetadataService(app.log).setup()
    await app.register(pieceModule)
    await app.register(collaborativeModule)
    await app.register(flowModule)
    await app.register(flowRunModule)
    await app.register(webhookModule)
    await app.register(appConnectionModule)
    await app.register(platformAppConnectionModule)
    await app.register(variableModule)
    await app.register(openapiModule)
    await app.register(appEventRoutingModule)
    await app.register(authenticationModule)
    await app.register(triggerModule)
    await app.register(platformModule)
    await app.register(piecesReportModule)
    await app.register(platformConfigurationModule)
    await app.register(humanInputModule)
    await app.register(mcpServerModule)
    await app.register(mcpOAuthApproveController)
    await app.register(mcpOAuthGrantsController)
    await app.register(mcpActivityController)
    await app.register(agentsModule)
    await app.register(platformUserModule)
    await app.register(alertsModule)
    await app.register(invitationModule)
    await app.register(workerModule)
    await workerCapacity.setup()
    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)
    await app.register(userModule)
    await app.register(templateModule)
    await app.register(platformAnalyticsModule)

    // Dev-only: accept browser debug logs into the shared evlog fs drain so a
    // chat run can be reconstructed end-to-end (web + api + worker). Never in cloud/prod.
    const clientLogsEnabled = system.get(AppSystemProp.LOG_FILE) === 'true' && system.getEdition() !== ApEdition.CLOUD
    if (clientLogsEnabled) {
        await app.register(clientLogsModule)
    }

    systemJobHandlers.registerJobHandler(SystemJobName.DELETE_FLOW, (data) => flowBackgroundJobs(app.log).deleteFlowHandler(data))
    systemJobHandlers.registerJobHandler(SystemJobName.HARD_DELETE_PROJECT, (data) => platformProjectBackgroundJobs(app.log).hardDeleteProjectHandler(data))
    systemJobHandlers.registerJobHandler(SystemJobName.CREATE_MISSING_PERSONAL_PROJECTS, (data) => personalProjectsService(app.log).createMissingHandler(data))

    systemJobHandlers.registerJobHandler(SystemJobName.CHAT_STALE_SWEEP, async () => {
        await agentHelpers.recoverAllStaleStreamingConversations({ log: app.log })
    })
    await systemJobsSchedule(app.log).upsertJob({
        job: {
            name: SystemJobName.CHAT_STALE_SWEEP,
            data: {},
            jobId: SystemJobName.CHAT_STALE_SWEEP,
        },
        schedule: {
            type: 'repeated',
            cron: '* * * * *',
        },
    })

    systemJobHandlers.registerJobHandler(SystemJobName.WAITPOINT_DEADLINE_SWEEP, async () => {
        await sweepOverdueDeadlines({ log: app.log })
    })
    await systemJobsSchedule(app.log).upsertJob({
        job: {
            name: SystemJobName.WAITPOINT_DEADLINE_SWEEP,
            data: {},
            jobId: SystemJobName.WAITPOINT_DEADLINE_SWEEP,
        },
        schedule: {
            type: 'repeated',
            cron: '* * * * *',
        },
    })

    systemJobHandlers.registerJobHandler(SystemJobName.RUN_BACKGROUND_MIGRATIONS, async () => {
        await backgroundMigrationRunner.run({ log: app.log })
    })

    app.get(
        '/redirect',
        async (
            request: FastifyRequest<{ Querystring: { code: string } }>,
            reply,
        ) => {
            const code = request.query.code
            if (!code) {
                return reply.type('text/plain').send('The code is missing in url')
            }
            return reply
                .type('text/html')
                .header('Content-Security-Policy', 'default-src \'none\'; script-src \'unsafe-inline\'')
                .header('X-Content-Type-Options', 'nosniff')
                .send(Mustache.render(REDIRECT_HTML_TEMPLATE, { code }))
        },
    )

    await validateEnvPropsOnStartup(app.log)

    const edition = system.getEdition()
    app.log.info({
        edition,
    }, 'Activepieces Edition')
    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)
            await app.register(platformPlanModule)
            await app.register(projectMemberModule)
            await app.register(appSumoModule)
            await app.register(signingKeyModule)
            await app.register(authnSsoSamlModule)
            await app.register(managedAuthnModule)
            await app.register(oauthAppModule)
            await app.register(platformPieceModule)
            await app.register(pieceSetModule)
            await app.register(otpModule)
            await app.register(enterpriseLocalAuthnModule)
            await app.register(passwordlessAuthModule)
            await app.register(federatedAuthModule)
            await app.register(apiKeyModule)
            await app.register(gitRepoModule)
            await app.register(auditEventModule)
            await app.register(platformWebhooksModule)
            await app.register(projectRoleModule)
            await app.register(personalProjectsModule)
            await app.register(projectReleaseModule)
            await app.register(projectReplaceModule)
            await app.register(globalConnectionModule)
            await app.register(secretManagersModule)
            await app.register(scimModule)
            await app.register(flowApprovalModule)
            await app.register(embedSubdomainModule)
            await app.register(agentModule)
            await app.register(agentEvalModule)
            await app.register(aiToolConfigModule)
            setPlatformOAuthService(platformOAuth2Service(app.log))
            projectHooks.set(projectEnterpriseHooks)
            userHooks.set(userEnterpriseHooks)
            flagHooks.set(enterpriseFlagsHooks)
            publishHooksFactory.set(eeFlowPublishHook)
            billingProvider.set(autumnBillingProvider)
            await aiUsageJobs.register(app.log)
            await app.register(aiUsageModule)
            resumePageHooks.set((log) => ({
                getTheme: (params) => appearanceHelper.getTheme({ ...params, log }),
                getPublicApiBaseUrl: (params) => embedSubdomainService(log).getPublicApiBaseUrl(params),
            }))
            verifiedDomainHooks.set(authnSsoSamlService)
            flowPublishHooks.set((log) => ({ assertReferencesResolve: assertAgentsResolveInProject, findMissingRequiredActions: (params) => pieceSetRequiredActions(log).findMissing(params) }))
            aiUsageHooks.set(agentConversationCreditsHooks)
            eventDestinationHooks.set(eventDestinationEntitlementHooks)
            exceptionHandler.initializeSentry(system.get(AppSystemProp.SENTRY_DSN))
            systemJobHandlers.registerJobHandler(SystemJobName.HARD_DELETE_PLATFORM, (data) => platformTeardownJobs(app.log).hardDeletePlatformHandler(data))
            break
        case ApEdition.ENTERPRISE:
            await app.register(denoMigrationModule)
            await app.register(pieceUpgradeModule)
            await app.register(platformPlanModule)
            await app.register(platformProjectModule)
            await app.register(projectMemberModule)
            await app.register(signingKeyModule)
            await app.register(authnSsoSamlModule)
            await app.register(managedAuthnModule)
            await app.register(oauthAppModule)
            await app.register(platformPieceModule)
            await app.register(pieceSetModule)
            await app.register(otpModule)
            await app.register(enterpriseLocalAuthnModule)
            await app.register(federatedAuthModule)
            await app.register(apiKeyModule)
            await app.register(gitRepoModule)
            await app.register(auditEventModule)
            await app.register(platformWebhooksModule)
            await app.register(projectRoleModule)
            await app.register(personalProjectsModule)
            await app.register(projectReleaseModule)
            await app.register(projectReplaceModule)
            await app.register(globalConnectionModule)
            await app.register(secretManagersModule)
            await app.register(scimModule)
            await app.register(flowApprovalModule)
            await app.register(embedSubdomainModule)
            await app.register(agentModule)
            await app.register(agentEvalModule)
            await app.register(aiToolConfigModule)
            setPlatformOAuthService(platformOAuth2Service(app.log))
            projectHooks.set(projectEnterpriseHooks)
            userHooks.set(userEnterpriseHooks)
            flagHooks.set(enterpriseFlagsHooks)
            publishHooksFactory.set(eeFlowPublishHook)
            billingProvider.set(autumnBillingProvider)
            await aiUsageJobs.register(app.log)
            await app.register(aiUsageModule)
            resumePageHooks.set((log) => ({
                getTheme: (params) => appearanceHelper.getTheme({ ...params, log }),
                getPublicApiBaseUrl: (params) => embedSubdomainService(log).getPublicApiBaseUrl(params),
            }))
            flowPublishHooks.set((log) => ({ assertReferencesResolve: assertAgentsResolveInProject, findMissingRequiredActions: (params) => pieceSetRequiredActions(log).findMissing(params) }))
            aiUsageHooks.set(agentConversationCreditsHooks)
            eventDestinationHooks.set(eventDestinationEntitlementHooks)
            break
        case ApEdition.COMMUNITY:
            await app.register(denoMigrationModule)
            await app.register(platformProjectModule)
            await app.register(communityPiecesModule)
            await app.register(otpModule)
            break
    }

    const isCanaryApp = system.getBoolean(AppSystemProp.IS_CANARY_APP) ?? false
    if (isCanaryApp) {
        app.log.info('[setupApp] Skipping system jobs worker on canary app instance')
    }
    else {
        await systemJobsSchedule(app.log).startWorker()
    }

    app.addHook('onClose', async () => {
        app.log.info('Shutting down')
        await systemJobsSchedule(app.log).close()
        await redisConnections.destroy()
        await distributedLock(app.log).destroy()
        await engineResponseWatcher(app.log).shutdown()
        await shutdownTelemetry()
    })

    return app
}



export async function getAdapter() {
    const redisConnectionInstance = await redisConnections.useExisting()
    const sub = redisConnectionInstance.duplicate()
    const pub = redisConnectionInstance.duplicate()
    return createAdapter(pub, sub, {
        requestsTimeout: 30000,
    })
}


export async function appPostBoot(app: FastifyInstance): Promise<void> {

    app.log.info(`
             _____   _______   _____  __      __  ______   _____    _____   ______    _____   ______    _____
    /\\      / ____| |__   __| |_   _| \\ \\    / / |  ____| |  __ \\  |_   _| |  ____|  / ____| |  ____|  / ____|
   /  \\    | |         | |      | |    \\ \\  / /  | |__    | |__) |   | |   | |__    | |      | |__    | (___
  / /\\ \\   | |         | |      | |     \\ \\/ /   |  __|   |  ___/    | |   |  __|   | |      |  __|    \\___ \\
 / ____ \\  | |____     | |     _| |_     \\  /    | |____  | |       _| |_  | |____  | |____  | |____   ____) |
/_/    \\_\\  \\_____|    |_|    |_____|     \\/     |______| |_|      |_____| |______|  \\_____| |______| |_____/

The application started on ${await domainHelper.getPublicApiUrl({ path: '' })}, as specified by the AP_FRONTEND_URL variables.`)

    const environment = system.get(AppSystemProp.ENVIRONMENT)
    const pieces = process.env.AP_DEV_PIECES

    assertReleaseReadable(app.log)
    aiObservability.init({ enabled: system.getEdition() === ApEdition.CLOUD })
    aiCostReporter.install({
        log: app.log,
        report: (request) => aiUsageService(app.log).report(request),
        pageWebhookUrl: () => system.get(AppSystemProp.PAGE_ONCALL_WEBHOOK),
    })
    installAiKeyHealthReporter(app.log)
    systemSnapshot.start({ log: app.log })
    await migrateQueuesAndRunConsumers(app)
    app.log.info('Queues migrated and consumers run')
    dispatchBackgroundMigrations(app.log).catch(error => {
        app.log.warn({ error: error instanceof Error ? error.message : String(error) }, '[appPostBoot] Failed to dispatch background migrations job; next pod boot will retry')
    })
    if (environment === ApEnvironment.DEVELOPMENT) {
        app.log.warn(
            `[WARNING]: The application is running in ${environment} mode.`,
        )
        app.log.warn(
            `[WARNING]: This is only shows pieces specified in AP_DEV_PIECES ${pieces} environment variable.`,
        )
    }
    void startDevPieceWatcher(app)
}

async function dispatchBackgroundMigrations(log: FastifyBaseLogger): Promise<void> {
    await systemJobsSchedule(log).upsertJob({
        job: {
            name: SystemJobName.RUN_BACKGROUND_MIGRATIONS,
            data: {},
            jobId: SystemJobName.RUN_BACKGROUND_MIGRATIONS,
        },
        schedule: {
            type: 'one-time',
            date: apDayjs(),
        },
        customConfig: {
            attempts: 10,
            backoff: { type: SystemJobBackoff.instantBurstThenExponential, delay: 0 },
        },
    })
}

// Front-loads the release-read failure signal to boot time. Without this the only alert is
// emitted lazily on the first worker poll (worker-rpc-service.ts), so a mis-packaged app that
// no worker has polled yet looks healthy. A '0.0.0' read fail-closes the dispatch gate and will
// NOT self-heal on deploy completion, so page immediately and log at error (see the "Release
// Version Detection" section in packages/server/AGENTS.md).
function assertReleaseReadable(log: FastifyBaseLogger): void {
    const version = apVersionUtil.getCurrentRelease()
    if (version !== UNKNOWN_VERSION) {
        log.info({ release: { version } }, '[appPostBoot] Release version detected from package.json')
        return
    }
    log.error({ release: { version } }, '[appPostBoot] App could not read its release version from package.json (reported as 0.0.0); worker dispatch is gated and will NOT self-heal until the deployment is fixed (check cwd/packaging)')
    onCallService(log, system.get(AppSystemProp.PAGE_ONCALL_WEBHOOK)).page({
        code: 'RELEASE_VERSION_UNREADABLE',
        message: 'App could not read its release version from package.json (reported as 0.0.0) at startup; worker dispatch is gated and will NOT self-heal until the deployment is fixed (check cwd/packaging)',
        params: { appVersion: version },
    }).catch((pageError) => {
        log.error({ pageError }, '[appPostBoot] Failed to send on-call page for unreadable release version')
    })
}

function extractPlatformId(principal: { platform?: { id?: string } } | null | undefined): string | undefined {
    return principal?.platform?.id
}

function extractProjectId(principal: { projectId?: string } | null | undefined): string | undefined {
    return principal?.projectId
}

function registerOpenApiSchemas() {
    globalRegistry.add(FlowCreatedEvent, { id: ApplicationEventName.FLOW_CREATED })
    globalRegistry.add(FlowUpdatedEvent, { id: ApplicationEventName.FLOW_UPDATED })
    globalRegistry.add(FlowPiecesUpgradedEvent, { id: ApplicationEventName.FLOW_PIECES_UPGRADED })
    globalRegistry.add(FlowPiecesRevertedEvent, { id: ApplicationEventName.FLOW_PIECES_REVERTED })
    globalRegistry.add(FlowDeletedEvent, { id: ApplicationEventName.FLOW_DELETED })
    globalRegistry.add(FlowPublishedEvent, { id: ApplicationEventName.FLOW_PUBLISHED })
    globalRegistry.add(FlowActivatedEvent, { id: ApplicationEventName.FLOW_ACTIVATED })
    globalRegistry.add(FlowDeactivatedEvent, { id: ApplicationEventName.FLOW_DEACTIVATED })
    globalRegistry.add(ConnectionUpsertedEvent, { id: ApplicationEventName.CONNECTION_UPSERTED })
    globalRegistry.add(ConnectionDeletedEvent, { id: ApplicationEventName.CONNECTION_DELETED })
    globalRegistry.add(FolderCreatedEvent, { id: ApplicationEventName.FOLDER_CREATED })
    globalRegistry.add(FolderUpdatedEvent, { id: ApplicationEventName.FOLDER_UPDATED })
    globalRegistry.add(FolderDeletedEvent, { id: ApplicationEventName.FOLDER_DELETED })
    globalRegistry.add(FlowRunStartedEvent, { id: ApplicationEventName.FLOW_RUN_STARTED })
    globalRegistry.add(FlowRunFinishedEvent, { id: ApplicationEventName.FLOW_RUN_FINISHED })
    globalRegistry.add(FlowRunRetriedEvent, { id: ApplicationEventName.FLOW_RUN_RETRIED })
    globalRegistry.add(SignUpEvent, { id: ApplicationEventName.USER_SIGNED_UP })
    globalRegistry.add(UserSignedInEvent, { id: ApplicationEventName.USER_SIGNED_IN })
    globalRegistry.add(UserPasswordResetEvent, { id: ApplicationEventName.USER_PASSWORD_RESET })
    globalRegistry.add(UserEmailVerifiedEvent, { id: ApplicationEventName.USER_EMAIL_VERIFIED })
    globalRegistry.add(SigningKeyEvent, { id: ApplicationEventName.SIGNING_KEY_CREATED })
    globalRegistry.add(AuditLogRetentionUpdatedEvent, { id: ApplicationEventName.AUDIT_LOG_RETENTION_UPDATED })
    globalRegistry.add(ProjectRoleEvent, { id: ApplicationEventName.PROJECT_ROLE_CREATED })
    globalRegistry.add(ProjectReleaseEvent, { id: ApplicationEventName.PROJECT_RELEASE_CREATED })
    globalRegistry.add(Template, { id: 'template' })
    globalRegistry.add(Folder, { id: 'folder' })
    globalRegistry.add(UserWithMetaInformation, { id: 'user' })
    globalRegistry.add(UserInvitation, { id: 'user-invitation' })
    globalRegistry.add(ProjectMember, { id: 'project-member' })
    globalRegistry.add(ProjectWithLimits, { id: 'project' })
    globalRegistry.add(Flow, { id: 'flow' })
    globalRegistry.add(FlowRun, { id: 'flow-run' })
    globalRegistry.add(AppConnectionWithoutSensitiveData, { id: 'app-connection' })
    globalRegistry.add(PieceMetadata, { id: 'piece' })
    globalRegistry.add(GitRepoWithoutSensitiveData, { id: 'git-repo' })
    globalRegistry.add(ProjectRelease, { id: 'project-release' })
    globalRegistry.add(AddAllowedEmbedOriginsRequestBody, { id: 'embedding' })
    globalRegistry.add(VariableWithoutSensitiveData, { id: 'variable' })
}

const REDIRECT_HTML_TEMPLATE = `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Redirect</title></head>
<body>
Redirect successful, this window should close now.
<meta id="ap-oauth-code" content="{{code}}">
<script>
(function () {
    var el = document.getElementById('ap-oauth-code');
    var code = el ? el.getAttribute('content') : null;
    if (window.opener && code) {
        window.opener.postMessage({ code: code }, '*');
    }
})();
</script>
</body>
</html>`