The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
update AI reward builder for new customer source options
Pedro Ladeira3f2a64331a0c
diff --git a/apps/web/lib/ai/ai-reward-schema.ts b/apps/web/lib/ai/ai-reward-schema.tsindex 19c67ef43b..2da250448c 100644--- a/apps/web/lib/ai/ai-reward-schema.ts+++ b/apps/web/lib/ai/ai-reward-schema.ts@@ -1,5 +1,6 @@import {CONDITION_OPERATORS,+ CUSTOMER_SOURCES,isOneOffRewardEvent,REWARD_CONDITIONS,} from "@/lib/zod/schemas/rewards";@@ -225,6 +226,12 @@ export function getAIRewardGenerationSchema(event: AIRewardEvent) {.describe("When supported is false: brief explanation of what is not supported. When supported is true: null or omit.",),+ unavailableSource: z+ .enum(CUSTOMER_SOURCES)+ .nullish()+ .describe(+ "When supported is false because the request needs a customer source listed under 'Unavailable option values': that option id. Otherwise null or omit.",+ ),reward: buildEventRewardObjectSchema(event).nullish().describe(diff --git a/apps/web/lib/ai/generate-reward.ts b/apps/web/lib/ai/generate-reward.tsindex 66cfd13e3f..b5d5c8e0d4 100644--- a/apps/web/lib/ai/generate-reward.ts+++ b/apps/web/lib/ai/generate-reward.ts@@ -7,6 +7,7 @@ import {import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";import { getSession } from "@/lib/auth";import { prisma } from "@/lib/prisma";+import { getCustomerSourceAvailability } from "@/lib/rewards/get-customer-source-availability";import { PlanProps } from "@/lib/types";import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";@@ -29,12 +30,45 @@ const inputSchema = z.object({prompt: z.string().min(1).max(2000),});-function buildSystemPrompt(event: (typeof AI_REWARD_EVENTS)[number]) {+function buildSystemPrompt(+ event: (typeof AI_REWARD_EVENTS)[number],+ {+ programId,+ installedIntegrationIds,+ }: { programId?: string | null; installedIntegrationIds: string[] },+) {+ // Customer sources this workspace can't use (same rules as the manual builder)+ const unavailableSources = (+ REWARD_CONDITIONS[event].entities+ .find(({ id }) => id === "customer")+ ?.attributes.find(({ id }) => id === "source")?.options ?? []+ )+ .map(({ id }) => ({+ id,+ ...getCustomerSourceAvailability({+ source: id,+ programId: programId ?? undefined,+ installedIntegrationIds,+ }),+ }))+ .filter(({ hidden, missingIntegration }) => hidden || missingIntegration);+const entities = REWARD_CONDITIONS[event].entities.map((entity) => {const attrs = entity.attributes.map((attr) => {const options = attr.options- ? ` options=[${attr.options.map((o) => `${o.id}`).join(", ")}]`+ ? ` options=[${attr.options+ .filter(+ ({ id }) =>+ attr.id !== "source" ||+ !unavailableSources.some((source) => source.id === id),+ )+ .map(({ id, description }) =>+ description+ ? `${id}: ${description.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")}`+ : id,+ )+ .join("; ")}]`: "";return ` - ${attr.id} (${attr.type}${options})`;})@@ -42,6 +76,10 @@ function buildSystemPrompt(event: (typeof AI_REWARD_EVENTS)[number]) {return ` - ${entity.id}:\n${attrs}`;});+ const integrationSources = unavailableSources.filter(+ ({ missingIntegration }) => missingIntegration,+ );+return `You are a partner reward structure assistant for Dub. Convert the user's natural-language reward idea into a structured reward configuration.Event type: ${event}@@ -61,11 +99,25 @@ Unsupported requests (important):- Set supported=false when the request cannot be expressed accurately with the allowed attributes. Set reward to null and explain briefly in reason.- Do NOT approximate, stretch meanings, or substitute a "close enough" attribute.- Examples of unsupported: billing interval / plan cadence (yearly vs monthly plans), plan names or tiers not identified via productId or an explicitly named metadata field, or any condition on a field not listed below.+- For enum attributes, options are listed as "id: description". Use only the id as the condition value, and pick the option whose description matches the user's intent.- customer.subscriptionDurationMonths is how long the customer has already been subscribed — it is NOT whether their plan is billed yearly or monthly.- When supported=true, provide a complete reward object. When supported=false, reward must be null.Allowed entities and attributes for ${event}:-${entities.join("\n")}`;+${entities.join("\n")}${+ integrationSources.length+ ? `++Unavailable customer sources (do NOT use these):+${integrationSources+ .map(+ ({ id, missingIntegration }) =>+ `- ${id}: requires the ${missingIntegration?.name} integration, which is not installed`,+ )+ .join("\n")}+If the user asks for one of these, set supported=false, set unavailableSource to its id, and explain in reason that the integration must be installed first.`+ : ""+ }`;}export async function generateReward(input: z.infer<typeof inputSchema>) {@@ -90,6 +142,9 @@ export async function generateReward(input: z.infer<typeof inputSchema>) {where: { userId: session.user.id },select: { role: true },},+ installedIntegrations: {+ select: { integrationId: true },+ },},});@@ -137,7 +192,12 @@ export async function generateReward(input: z.infer<typeof inputSchema>) {const result = streamText({model: anthropic("claude-sonnet-4-6"),output: Output.object({ schema: generationSchema }),- system: buildSystemPrompt(event),+ system: buildSystemPrompt(event, {+ programId: workspace.defaultProgramId,+ installedIntegrationIds: workspace.installedIntegrations.map(+ ({ integrationId }) => integrationId,+ ),+ }),prompt,temperature: 0.3,maxOutputTokens: 2000,diff --git a/apps/web/lib/rewards/get-customer-source-availability.ts b/apps/web/lib/rewards/get-customer-source-availability.tsindex 21f5a7039b..c636ce0164 100644--- a/apps/web/lib/rewards/get-customer-source-availability.ts+++ b/apps/web/lib/rewards/get-customer-source-availability.ts@@ -4,7 +4,7 @@ import { HUBSPOT_INTEGRATION_ID, STRIPE_INTEGRATION_ID } from "@dub/utils";type RequiredIntegration = { id: string; slug: string; name: string };-const CUSTOMER_SOURCE_REQUIRED_INTEGRATIONS: Partial<+export const CUSTOMER_SOURCE_REQUIRED_INTEGRATIONS: Partial<Record<CustomerSource, RequiredIntegration>> = {trial: { id: STRIPE_INTEGRATION_ID, slug: "stripe", name: "Stripe" },diff --git a/apps/web/tests/misc/ai-reward-schema.test.ts b/apps/web/tests/misc/ai-reward-schema.test.tsindex e1abbb3de4..603788a50b 100644--- a/apps/web/tests/misc/ai-reward-schema.test.ts+++ b/apps/web/tests/misc/ai-reward-schema.test.ts@@ -282,6 +282,25 @@ describe("getAIRewardGenerationSchema — unsupported refusal", () => {expect(result.success).toBe(true);});+ it("accepts supported=false with an unavailable customer source", () => {+ const result = schema.safeParse({+ supported: false,+ reason: "HubSpot must be installed first.",+ unavailableSource: "hubspot",+ reward: null,+ });+ expect(result.success).toBe(true);+ });++ it("rejects an unknown unavailable customer source", () => {+ const result = schema.safeParse({+ supported: false,+ unavailableSource: "salesforce",+ reward: null,+ });+ expect(result.success).toBe(false);+ });+it("defers app validation to getAIRewardSchema (not generation envelope)", () => {const clickSchema = getAIRewardGenerationSchema("click");const result = clickSchema.safeParse({diff --git a/apps/web/ui/partners/rewards/ai-reward-builder.tsx b/apps/web/ui/partners/rewards/ai-reward-builder.tsxindex e72979b34b..86a203431b 100644--- a/apps/web/ui/partners/rewards/ai-reward-builder.tsx+++ b/apps/web/ui/partners/rewards/ai-reward-builder.tsx@@ -6,6 +6,7 @@ import {getAIRewardSchema,} from "@/lib/ai/ai-reward-schema";import { generateReward } from "@/lib/ai/generate-reward";+import { CUSTOMER_SOURCE_REQUIRED_INTEGRATIONS } from "@/lib/rewards/get-customer-source-availability";import useWorkspace from "@/lib/swr/use-workspace";import { REWARD_CONDITION_ATTRIBUTES } from "@/lib/zod/schemas/rewards";import { CustomToast } from "@/ui/shared/custom-toast";@@ -315,10 +316,16 @@ export function useAIRewardBuilder({if (lastPartial.supported === false) {discard({ keepPrompt: true });++ const missingIntegration = lastPartial.unavailableSource+ ? CUSTOMER_SOURCE_REQUIRED_INTEGRATIONS[lastPartial.unavailableSource]+ : undefined;+toast.custom(() => (<CustomToast variant="error">- This reward setup isn't supported yet. [Reach out to- support](https://dub.co/support) if you need help configuring this.+ {missingIntegration+ ? `This reward setup requires the ${missingIntegration.name} integration. [Install ${missingIntegration.name}](/${workspaceSlug}/settings/integrations/${missingIntegration.slug}) to use it.`+ : "This reward setup isn't supported yet. [Reach out to support](https://dub.co/support) if you need help configuring this."}</CustomToast>));void mutateWorkspace();