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

14.2 KB
Raw Blame
import { ActivepiecesError, ErrorCode, isNil, PlatformUsageMetric, tryCatch } from '@activepieces/core-utils'
import { apDayjs } from '@activepieces/server-utils'
import { ApEdition, AppSumoCreditsBillableFeature, CancellationReason, ConsumableFeatureId, ConsumableProductAutoTopupParams, CreditsBillableFeature, FlowRun, PurchasablePlan, RunEnvironment, SeatsBillableFeature, UnconsumableFeatureId } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { AiUsageBlock } from '../ai/usage/ai-usage-block'
import { hooksFactory } from '../helper/hooks-factory'
import { system } from '../helper/system/system'

export const billingProvider = hooksFactory.create<BillingProvider>(() => ({
    listPlans: async () => {
        return []
    },
    getBillingOverview: async () => {
        return emptyBillingOverview({})
    },
    createCheckoutSession: async () => {
        return { checkoutUrl: null }
    },
    getBillingPortalUrl: async () => {
        return { url: '' }
    },
    adjustUnconsumableFeatureQuantity: async () => {
        return { checkoutUrl: null }
    },
    configureAutoTopUp: async () => {
        return
    },
    setupPayment: async () => {
        return { url: null }
    },
    cancelSubscription: async () => {
        return
    },
    reactivateSubscription: async () => {
        return
    },
    trackFeature: async () => {
        return
    },
    ensureEnrolled: async () => {
        return
    },
    compFreeLegacy: async () => {
        return
    },
    refreshEntitlements: async () => {
        return
    },
    applyAppSumoPlan: async () => {
        return
    },
    activateLicense: async () => {
        return
    },
    isBillingEnforced: async () => {
        return false
    },
    shouldBlockOnCredits: async () => {
        return false
    },
    getCreditsAndAppSumoState: async () => {
        return {
            credits: { blocked: false, metered: false, usage: 0, limit: 0, remaining: 0, unlimited: false },
            appSumo: { blocked: false, metered: false, usage: 0, limit: 0, remaining: 0, unlimited: false },
        }
    },
    getConsumablesUsage: async () => {
        return { credits: null, appSumo: null }
    },
    getCreditUsage: async () => {
        return { total: 0, byProject: [] }
    },
    listUsageEvents: async () => {
        return { events: [], nextCursor: null }
    },
}))

export async function assertCreditsAndAppSumoNotExceeded({ platformId, log }: { platformId: string, log: FastifyBaseLogger }): Promise<void> {
    const { credits, appSumo } = await billingProvider.get(log).getCreditsAndAppSumoState(platformId)
    if (appSumo.blocked) {
        throw new ActivepiecesError({
            code: ErrorCode.QUOTA_EXCEEDED,
            params: { metric: PlatformUsageMetric.CREDITS, usage: appSumo.usage, limit: appSumo.limit },
        })
    }
    if (credits.blocked) {
        throw new ActivepiecesError({
            code: ErrorCode.QUOTA_EXCEEDED,
            params: { metric: PlatformUsageMetric.CREDITS, usage: credits.usage, limit: credits.limit },
        })
    }
}

export async function assertCreditsNotExceeded({ platformId, log }: { platformId: string, log: FastifyBaseLogger }): Promise<void> {
    const { credits } = await billingProvider.get(log).getCreditsAndAppSumoState(platformId)
    if (credits.blocked) {
        throw new ActivepiecesError({
            code: ErrorCode.QUOTA_EXCEEDED,
            params: { metric: PlatformUsageMetric.CREDITS, usage: credits.usage, limit: credits.limit },
        })
    }
}

export async function creditsLeftAfter({ platformId, pendingCredits, log }: { platformId: string, pendingCredits: number, log: FastifyBaseLogger }): Promise<number | null> {
    const { data: state, error } = await tryCatch(() => billingProvider.get(log).getCreditsAndAppSumoState(platformId))
    if (isNil(state)) {
        log.warn({ platform: { id: platformId }, error }, 'Credits check failed, allowing the request')
        return null
    }
    const left = [state.credits, state.appSumo].filter((gate) => gate.metered).map((gate) => gate.remaining - pendingCredits)
    return left.length === 0 ? null : Math.min(...left)
}

export async function hasCreditsLeft({ platformId, log }: { platformId: string, log: FastifyBaseLogger }): Promise<boolean> {
    const left = await creditsLeftAfter({ platformId, pendingCredits: 0, log })
    return isNil(left) || left > 0
}

export async function shouldBlockRunOnCredits({ platformId, environment, creditCheckSpeed, log }: RunCreditsGateParams): Promise<boolean> {
    if (system.getEdition() === ApEdition.ENTERPRISE) {
        return false
    }
    if (environment !== RunEnvironment.PRODUCTION) {
        return false
    }
    return billingProvider.get(log).shouldBlockOnCredits({ platformId, creditCheckSpeed })
}

export async function assertRunCreditsNotExceeded({ platformId, environment, creditCheckSpeed, log }: RunCreditsGateParams): Promise<void> {
    const blocked = await shouldBlockRunOnCredits({ platformId, environment, creditCheckSpeed, log })
    if (!blocked) {
        return
    }
    throw new ActivepiecesError({
        code: ErrorCode.QUOTA_EXCEEDED,
        params: { metric: PlatformUsageMetric.CREDITS },
    })
}

export function toFlowRunCreditProperties({ platformId, flowRun }: ToFlowRunCreditPropertiesParams): FlowRunCreditConsumptionProperties {
    return {
        platformId,
        projectId: flowRun.projectId,
        flowId: flowRun.flowId,
        flowRunId: flowRun.id,
        environment: flowRun.environment,
    }
}

export function emptyBillingOverview({ startDate, endDate, unavailable = false }: EmptyBillingOverviewParams): BillingOverview {
    return {
        startDate: startDate ?? apDayjs().startOf('month').toISOString(),
        endDate: endDate ?? apDayjs().endOf('month').toISOString(),
        nextBillingAmount: 0,
        cancelAt: null,
        trialEndsAt: null,
        planInterval: null,
        planName: null,
        scheduledPlanName: null,
        billingPortalAvailable: false,
        creditsResetInterval: null,
        creditsFeature: null,
        appSumoCreditsFeature: null,
        seatsFeature: null,
        includedSeats: null,
        additionalSeats: null,
        unavailable,
    }
}

export enum CreditUsageSource {
    FLOW_RUN = 'flow_run',
    AI = 'ai',
    CHAT = 'chat',
    AGENT_DRAFT = 'agent_draft',
    MCP = 'mcp',
    AI_USAGE = 'ai_usage',
}

type ToFlowRunCreditPropertiesParams = {
    platformId: string
    flowRun: FlowRun
}

type EmptyBillingOverviewParams = {
    startDate?: string
    endDate?: string
    unavailable?: boolean
}

type RunCreditsGateParams = {
    platformId: string
    environment: RunEnvironment
    creditCheckSpeed: CreditCheckSpeed
    log: FastifyBaseLogger
}

export type ShouldBlockOnCreditsParams = {
    platformId: string
    creditCheckSpeed: CreditCheckSpeed
}

export type CreditEventBreakdownEntry = {
    provider: string
    model: string
    messages: number
    toolCalls: number
}

type CreditConsumptionPropertiesBase = {
    platformId: string
    projectId: string
}

export type FlowRunCreditConsumptionProperties = CreditConsumptionPropertiesBase & {
    flowId: string
    flowRunId: string
    environment: string
}

export type AgentDraftCreditConsumptionProperties = CreditConsumptionPropertiesBase & {
    provider: string | null
}

export type AiCreditConsumptionProperties = FlowRunCreditConsumptionProperties & {
    messages: number
    toolCalls: number
    breakdown: CreditEventBreakdownEntry[]
    costUsd?: number
    creditUsdValue?: number
    inputTokens?: number
    outputTokens?: number
    usage?: AiUsageBlock
}

export type McpCallCreditConsumptionProperties = {
    platformId: string
    projectId: string | null
    toolName: string
    clientId: string
}

export type ChatCreditConsumptionProperties = CreditConsumptionPropertiesBase & {
    userId: string
    conversationId: string
    turnIndex: number
    messages: number
    toolCalls: number
    provider: string | null
    model: string | null
    tier: string
    costUsd?: number
    creditUsdValue?: number
    inputTokens?: number
    outputTokens?: number
    usage?: AiUsageBlock
}

export type AiUsageOnlyProperties = {
    usage: AiUsageBlock
}

export type ChatAppSumoConsumptionProperties = CreditConsumptionPropertiesBase & {
    conversationId: string
    turnIndex: number
    tier: string
}

type TrackUsageParamsBase = {
    platformId: string
    value: number
    idempotencyKey: string
}

export type TrackCreditsParams =
    | (TrackUsageParamsBase & { source: CreditUsageSource.FLOW_RUN, properties: FlowRunCreditConsumptionProperties })
    | (TrackUsageParamsBase & { source: CreditUsageSource.AI, properties: AiCreditConsumptionProperties })
    | (TrackUsageParamsBase & { source: CreditUsageSource.CHAT, properties: ChatCreditConsumptionProperties })
    | (TrackUsageParamsBase & { source: CreditUsageSource.AGENT_DRAFT, properties: AgentDraftCreditConsumptionProperties })
    | (TrackUsageParamsBase & { source: CreditUsageSource.MCP, properties: McpCallCreditConsumptionProperties })
    | (TrackUsageParamsBase & { source: CreditUsageSource.AI_USAGE, properties: AiUsageOnlyProperties })

export type TrackAppSumoAiUsageParams = TrackUsageParamsBase & (
    { source: CreditUsageSource.AGENT_DRAFT, properties: AgentDraftCreditConsumptionProperties } |
    { source: CreditUsageSource.AI, properties: AiCreditConsumptionProperties } |
    { source: CreditUsageSource.CHAT, properties: ChatAppSumoConsumptionProperties } |
    { source: CreditUsageSource.MCP, properties: McpCallCreditConsumptionProperties }
)

export type TrackFeatureParams =
    | ({ featureId: ConsumableFeatureId.AP_CREDITS } & TrackCreditsParams)
    | ({ featureId: ConsumableFeatureId.APP_SUMO_AI_CREDITS } & TrackAppSumoAiUsageParams)

export type CreditUsageByProjectParams = {
    platformId: string
    startDate?: string
    endDate?: string
}

export type ProjectCreditsAggregate = {
    projectId: string
    creditsUsed: number
    aiCreditsUsed: number
}

export type CreditUsage = {
    total: number
    byProject: ProjectCreditsAggregate[]
}

export type CreditsGateState = {
    blocked: boolean
    metered: boolean
    usage: number
    limit: number
    remaining: number
    unlimited: boolean
}

export type CreditsAndAppSumoState = {
    credits: CreditsGateState
    appSumo: CreditsGateState
}

export type AppSumoAiCreditsUsage = {
    usage: number
    limit: number
}

export type CreditsUsage = {
    usage: number
    remaining: number | null
    nextResetAt: string | null
}

export type ConsumablesUsage = {
    credits: CreditsUsage | null
    appSumo: AppSumoAiCreditsUsage | null
}

export type CreateCheckoutSessionParams = {
    platformId: string
    planId: string
    successUrl?: string
}

export type BillingPortalParams = {
    platformId: string
    returnUrl?: string
}

export type BillingInfo = {
    startDate: string
    endDate: string
    nextBillingAmount: number
    cancelAt: string | null
    trialEndsAt: string | null
    planName: string | null
    scheduledPlanName: string | null
    billingPortalAvailable: boolean
    creditsResetInterval: string | null
    planInterval: string | null
}

export type BillingOverview = BillingInfo & {
    creditsFeature: CreditsBillableFeature | null
    appSumoCreditsFeature: AppSumoCreditsBillableFeature | null
    seatsFeature: SeatsBillableFeature | null
    includedSeats: number | null
    additionalSeats: number | null
    unavailable: boolean
}

export type AdjustUnconsumableFeatureQuantityParams = {
    platformId: string
    featureId: UnconsumableFeatureId
    quantity: number
}

export type ConfigureAutoTopUpParams = ConsumableProductAutoTopupParams & {
    platformId: string
}

export type SetupPaymentParams = {
    platformId: string
    redirectUrl?: string
}

export type CancelSubscriptionParams = {
    platformId: string
    feedback: CancellationFeedback
}

export type CancellationFeedback = {
    reasons: CancellationReason[]
    comment: string | null
    canceledByEmail: string | null
}

export type ReactivateSubscriptionParams = {
    platformId: string
}

export enum AppSumoAction {
    ACTIVATE = 'activate',
    REFUND = 'refund',
}

export type ApplyAppSumoPlanParams = {
    platformId: string
    action: AppSumoAction
}

export type ActivateLicenseParams = {
    platformId: string
    licenseKey: string
}

export type BillingProvider = {
    listPlans(platformId: string): Promise<PurchasablePlan[]>
    getBillingOverview(platformId: string): Promise<BillingOverview>
    createCheckoutSession(params: CreateCheckoutSessionParams): Promise<{ checkoutUrl: string | null }>
    getBillingPortalUrl(params: BillingPortalParams): Promise<{ url: string }>
    adjustUnconsumableFeatureQuantity(params: AdjustUnconsumableFeatureQuantityParams): Promise<{ checkoutUrl: string | null }>
    configureAutoTopUp(params: ConfigureAutoTopUpParams): Promise<void>
    setupPayment(params: SetupPaymentParams): Promise<{ url: string | null }>
    cancelSubscription(params: CancelSubscriptionParams): Promise<void>
    reactivateSubscription(params: ReactivateSubscriptionParams): Promise<void>
    trackFeature(params: TrackFeatureParams): Promise<void>
    ensureEnrolled(platformId: string): Promise<void>
    compFreeLegacy(platformId: string): Promise<void>
    refreshEntitlements(platformId: string): Promise<void>
    applyAppSumoPlan(params: ApplyAppSumoPlanParams): Promise<void>
    activateLicense(params: ActivateLicenseParams): Promise<void>
    isBillingEnforced(platformId: string): Promise<boolean>
    shouldBlockOnCredits(params: ShouldBlockOnCreditsParams): Promise<boolean>
    getCreditsAndAppSumoState(platformId: string): Promise<CreditsAndAppSumoState>
    getConsumablesUsage(platformId: string): Promise<ConsumablesUsage>
    getCreditUsage(params: CreditUsageByProjectParams): Promise<CreditUsage>
    listUsageEvents(params: ListUsageEventsParams): Promise<UsageEventsPage>
}

export type ListUsageEventsParams = {
    platformId: string
    startMs: number
    endMs: number
    cursor: string | null
}

export type UsageEventsPage = {
    events: UsageEvent[]
    nextCursor: string | null
}

export type UsageEvent = {
    id: string
    timestamp: number
    properties: Record<string, unknown>
}

export enum CreditCheckSpeed {
    FAST = 'FAST',
    NORMAL = 'NORMAL',
    BACKGROUND = 'BACKGROUND',
}