🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore: fix github webhooks (#10932)
Max Deichmann413beb952ab3
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex e9c2c8ac34..9c3665c1ab 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -158,6 +158,7 @@ export type DashboardWidgetChartType =export const ActionType = {WEBHOOK: "WEBHOOK",SLACK: "SLACK",+ GITHUB_DISPATCH: "GITHUB_DISPATCH",} as const;export type ActionType = (typeof ActionType)[keyof typeof ActionType];export const ActionExecutionStatus = {diff --git a/packages/shared/prisma/migrations/20251204213345_add_github_dispatch_action_type/migration.sql b/packages/shared/prisma/migrations/20251204213345_add_github_dispatch_action_type/migration.sqlnew file mode 100644index 0000000000..8219ff8fc4--- /dev/null+++ b/packages/shared/prisma/migrations/20251204213345_add_github_dispatch_action_type/migration.sql@@ -0,0 +1,6 @@+-- Migration: Add GitHub Dispatch Action Type+-- This migration adds support for GitHub repository dispatch actions by:+-- 1. Adding GITHUB_DISPATCH to the ActionType enum++-- AlterEnum+ALTER TYPE "ActionType" ADD VALUE 'GITHUB_DISPATCH';diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 6b70360f48..9dfd4ec499 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -1449,6 +1449,7 @@ model Automation {enum ActionType {WEBHOOKSLACK+ GITHUB_DISPATCH// More action types can be added as needed}diff --git a/packages/shared/src/domain/automations.ts b/packages/shared/src/domain/automations.tsindex 754b1abcde..bba0c8a6b1 100644--- a/packages/shared/src/domain/automations.ts+++ b/packages/shared/src/domain/automations.ts@@ -37,7 +37,7 @@ export type ActionDomainWithSecrets = Omit<Action, "config"> & {config: ActionConfigWithSecrets;};-export const ActionTypeSchema = z.enum(["WEBHOOK", "SLACK"]);+export const ActionTypeSchema = z.enum(["WEBHOOK", "SLACK", "GITHUB_DISPATCH"]);export const AvailableWebhookApiSchema = z.record(z.enum(["prompt"]),@@ -87,19 +87,54 @@ export const SlackActionConfigSchema = z.object({export type SlackActionConfig = z.infer<typeof SlackActionConfigSchema>;+export const GitHubDispatchActionConfigSchema = z.object({+ type: z.literal("GITHUB_DISPATCH"),+ url: z.url(),+ eventType: z.string().min(1).max(100),+ githubToken: z.string(),+ displayGitHubToken: z.string(),+ lastFailingExecutionId: z.string().nullish(),+});++export const SafeGitHubDispatchActionConfigSchema =+ GitHubDispatchActionConfigSchema.omit({+ githubToken: true,+ });++export type SafeGitHubDispatchActionConfig = z.infer<+ typeof SafeGitHubDispatchActionConfigSchema+>;++export const GitHubDispatchActionCreateSchema = z.object({+ type: z.literal("GITHUB_DISPATCH"),+ url: z.string().url().optional(), // Optional for updates, validated in helper+ eventType: z.string().min(1).max(100).optional(), // Optional for updates, validated in helper+ githubToken: z.string().optional(), // Optional for updates, validated in helper+});++export type GitHubDispatchActionCreate = z.infer<+ typeof GitHubDispatchActionCreateSchema+>;+export type GitHubDispatchActionConfigWithSecrets = z.infer<+ typeof GitHubDispatchActionConfigSchema+>;+export const ActionConfigSchema = z.discriminatedUnion("type", [WebhookActionConfigSchema,SlackActionConfigSchema,+ GitHubDispatchActionConfigSchema,]);export const ActionCreateSchema = z.discriminatedUnion("type", [WebhookActionCreateSchema,SlackActionConfigSchema,+ GitHubDispatchActionCreateSchema,]);export const SafeActionConfigSchema = z.discriminatedUnion("type", [SafeWebhookActionConfigSchema,SlackActionConfigSchema,+ SafeGitHubDispatchActionConfigSchema,]);export type ActionTypes = z.infer<typeof ActionTypeSchema>;@@ -169,3 +204,52 @@ export function convertToSafeWebhookConfig(lastFailingExecutionId: webhookConfig.lastFailingExecutionId,};}++/**+ * Type guard to check if a config is a valid GitHub dispatch configuration with secrets+ */+export function isGitHubDispatchActionConfig(+ config: unknown,+): config is GitHubDispatchActionConfigWithSecrets {+ return GitHubDispatchActionConfigSchema.safeParse(config).success;+}++/**+ * Type guard to check if an entire action has valid GitHub dispatch configuration+ */+export function isGitHubDispatchAction(action: {+ type: string;+ config: unknown;+}): action is {+ type: "GITHUB_DISPATCH";+ config: GitHubDispatchActionConfigWithSecrets;+} {+ return (+ action.type === "GITHUB_DISPATCH" &&+ isGitHubDispatchActionConfig(action.config)+ );+}++/**+ * Type guard for safe GitHub dispatch config (without secrets)+ */+export function isSafeGitHubDispatchActionConfig(+ config: unknown,+): config is SafeGitHubDispatchActionConfig {+ return SafeGitHubDispatchActionConfigSchema.safeParse(config).success;+}++/**+ * Converts GitHub dispatch config with secrets to safe config by only including allowed fields+ */+export function convertToSafeGitHubDispatchConfig(+ config: GitHubDispatchActionConfigWithSecrets,+): SafeGitHubDispatchActionConfig {+ return {+ type: config.type,+ url: config.url,+ eventType: config.eventType,+ displayGitHubToken: config.displayGitHubToken,+ lastFailingExecutionId: config.lastFailingExecutionId,+ };+}diff --git a/packages/shared/src/domain/webhooks.ts b/packages/shared/src/domain/webhooks.tsindex f551169990..06938e86d2 100644--- a/packages/shared/src/domain/webhooks.ts+++ b/packages/shared/src/domain/webhooks.ts@@ -35,3 +35,12 @@ export const PromptWebhookOutboundSchema = z.and(WebhookOutboundBaseSchema);export type PromptWebhookOutput = z.infer<typeof PromptWebhookOutboundSchema>;++export const GitHubDispatchWebhookOutboundSchema = z.object({+ event_type: z.string(),+ client_payload: PromptWebhookOutboundSchema,+});++export type GitHubDispatchWebhookOutput = z.infer<+ typeof GitHubDispatchWebhookOutboundSchema+>;diff --git a/web/src/__tests__/async/automations-trpc.servertest.ts b/web/src/__tests__/async/automations-trpc.servertest.tsindex 7e3cad70ce..71352d2d9d 100644--- a/web/src/__tests__/async/automations-trpc.servertest.ts+++ b/web/src/__tests__/async/automations-trpc.servertest.ts@@ -2202,4 +2202,362 @@ describe("automations trpc", () => {).rejects.toThrow("User does not have access to this resource or action");});});++ describe("automations.createAutomation with GITHUB_DISPATCH", () => {+ it("should create a new GitHub dispatch automation", async () => {+ const { project, caller } = await prepare();++ // Create test prompt+ await prisma.prompt.create({+ data: {+ id: v4(),+ projectId: project.id,+ name: "test-prompt",+ version: 1,+ type: "text",+ prompt: { text: "Hello world" },+ createdBy: "test-user",+ },+ });++ const response = await caller.automations.createAutomation({+ projectId: project.id,+ name: "New GitHub Dispatch Automation",+ eventSource: "prompt",+ eventAction: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ actionType: "GITHUB_DISPATCH",+ actionConfig: {+ type: "GITHUB_DISPATCH",+ url: "https://api.github.com/repos/owner/repo/dispatches",+ eventType: "langfuse-prompt-created",+ githubToken: "ghp_test_token_123456",+ },+ });++ expect(response.trigger).toMatchObject({+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ status: JobConfigState.ACTIVE,+ });++ expect(response.action).toMatchObject({+ projectId: project.id,+ type: "GITHUB_DISPATCH",+ config: expect.objectContaining({+ type: "GITHUB_DISPATCH",+ url: "https://api.github.com/repos/owner/repo/dispatches",+ eventType: "langfuse-prompt-created",+ }),+ });++ expect(response.webhookSecret).toBeDefined();+ expect(typeof response.webhookSecret).toBe("string");+ expect(response.webhookSecret).toBe("ghp_test_token_123456");++ // Verify the automation link was created+ const automation = await prisma.automation.findFirst({+ where: {+ triggerId: response.trigger.id,+ actionId: response.action.id,+ },+ });++ expect(automation).toMatchObject({+ name: "New GitHub Dispatch Automation",+ });++ // Verify token is encrypted in database+ const createdAction = await prisma.action.findUnique({+ where: { id: response.action.id },+ });++ const config = createdAction?.config as any;+ expect(config.githubToken).toBeDefined();+ expect(config.githubToken).not.toBe("ghp_test_token_123456"); // Should be encrypted+ expect(config.displayGitHubToken).toMatch(/^ghp_...6$/); // Should be masked++ // Verify the response doesn't expose the encrypted token+ const responseConfig = response.action.config as any;+ expect(responseConfig).not.toHaveProperty("githubToken");+ expect(responseConfig.displayGitHubToken).toMatch(/^ghp_...6$/);+ });++ it("should fail to create GitHub dispatch automation with invalid URL", async () => {+ const { project, caller } = await prepare();++ await expect(+ caller.automations.createAutomation({+ projectId: project.id,+ name: "Invalid GitHub URL",+ eventSource: "prompt",+ eventAction: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ actionType: "GITHUB_DISPATCH",+ actionConfig: {+ type: "GITHUB_DISPATCH",+ url: "https://example.com/not-github",+ eventType: "test-event",+ githubToken: "ghp_token_123",+ },+ }),+ ).rejects.toThrow();+ });++ it("should fail to create GitHub dispatch automation without token", async () => {+ const { project, caller } = await prepare();++ await expect(+ caller.automations.createAutomation({+ projectId: project.id,+ name: "No GitHub Token",+ eventSource: "prompt",+ eventAction: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ actionType: "GITHUB_DISPATCH",+ actionConfig: {+ type: "GITHUB_DISPATCH",+ url: "https://api.github.com/repos/owner/repo/dispatches",+ githubToken: "",+ },+ }),+ ).rejects.toThrow();+ });+ });++ describe("automations.updateAutomation with GITHUB_DISPATCH", () => {+ it("should update GitHub dispatch automation URL without requiring token", async () => {+ const { project, caller } = await prepare();++ // Create initial automation+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ },+ });++ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "GITHUB_DISPATCH",+ config: {+ type: "GITHUB_DISPATCH",+ url: "https://api.github.com/repos/owner/repo/dispatches",+ eventType: "old-event",+ githubToken: encrypt("ghp_old_token"),+ displayGitHubToken: "ghp_...ken",+ },+ },+ });++ const automation = await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Original GitHub Dispatch",+ },+ });++ // Update URL and event type without providing new token+ const response = await caller.automations.updateAutomation({+ projectId: project.id,+ automationId: automation.id,+ name: "Updated GitHub Dispatch",+ eventSource: "prompt",+ eventAction: ["created", "updated"],+ filter: [],+ status: JobConfigState.ACTIVE,+ actionType: "GITHUB_DISPATCH",+ actionConfig: {+ type: "GITHUB_DISPATCH",+ url: "https://api.github.com/repos/owner/new-repo/dispatches",+ eventType: "new-event",+ githubToken: "", // Empty token means keep existing+ },+ });++ expect(response.action.id).toBe(action.id);+ expect(response.action.type).toBe("GITHUB_DISPATCH");++ const config = response.action.config as any;+ expect(config.url).toBe(+ "https://api.github.com/repos/owner/new-repo/dispatches",+ );+ expect(config.eventType).toBe("new-event");+ expect(config.displayGitHubToken).toBe("ghp_...ken"); // Preserved++ // Verify secrets not exposed in response+ expect(config).not.toHaveProperty("githubToken");++ // Verify the automation name was updated+ const updatedAutomation = await prisma.automation.findFirst({+ where: { id: automation.id },+ });+ expect(updatedAutomation?.name).toBe("Updated GitHub Dispatch");+ });++ it("should update GitHub dispatch automation with new token", async () => {+ const { project, caller } = await prepare();++ // Create initial automation+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ },+ });++ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "GITHUB_DISPATCH",+ config: {+ type: "GITHUB_DISPATCH",+ url: "https://api.github.com/repos/owner/repo/dispatches",+ eventType: "test-event-type",+ githubToken: encrypt("ghp_old_token_123"),+ displayGitHubToken: "ghp_...123",+ },+ },+ });++ const automation = await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "GitHub Dispatch Token Update",+ },+ });++ // Update with new token+ const response = await caller.automations.updateAutomation({+ projectId: project.id,+ automationId: automation.id,+ name: "GitHub Dispatch Token Update",+ eventSource: "prompt",+ eventAction: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ actionType: "GITHUB_DISPATCH",+ actionConfig: {+ type: "GITHUB_DISPATCH",+ url: "https://api.github.com/repos/owner/repo/dispatches",+ githubToken: "ghp_new_token_456",+ },+ });++ // Verify token is NOT returned (users provided it themselves)+ expect(response.webhookSecret).toBeUndefined();++ const config = response.action.config as any;+ expect(config.displayGitHubToken).toMatch(/^ghp_...6$/);+ expect(config).not.toHaveProperty("githubToken");++ // Verify token is encrypted in database+ const updatedAction = await prisma.action.findUnique({+ where: { id: action.id },+ });++ const dbConfig = updatedAction?.config as any;+ expect(dbConfig.githubToken).not.toBe("ghp_new_token_456"); // Encrypted+ expect(decrypt(dbConfig.githubToken)).toBe("ghp_new_token_456"); // Can decrypt+ });++ it("should preserve encrypted token when updating without providing new token", async () => {+ const { project, caller } = await prepare();++ const originalToken = "ghp_original_token_xyz";+ const encryptedToken = encrypt(originalToken);++ // Create initial automation with encrypted token+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ },+ });++ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "GITHUB_DISPATCH",+ config: {+ type: "GITHUB_DISPATCH",+ url: "https://api.github.com/repos/owner/repo/dispatches",+ eventType: "original-event-type",+ githubToken: encryptedToken,+ displayGitHubToken: "ghp_...xyz",+ },+ },+ });++ const automation = await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "GitHub Dispatch Preserve Token",+ },+ });++ // Update URL without providing token+ await caller.automations.updateAutomation({+ projectId: project.id,+ automationId: automation.id,+ name: "GitHub Dispatch Preserve Token",+ eventSource: "prompt",+ eventAction: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ actionType: "GITHUB_DISPATCH",+ actionConfig: {+ type: "GITHUB_DISPATCH",+ url: "https://api.github.com/repos/new-owner/new-repo/dispatches",+ eventType: "new-event-type",+ // githubToken intentionally omitted+ },+ });++ // Verify token was preserved (not double-encrypted)+ const updatedAction = await prisma.action.findUnique({+ where: { id: action.id },+ });++ const dbConfig = updatedAction?.config as any;++ // Token should still be the same encrypted value+ expect(dbConfig.githubToken).toBe(encryptedToken);++ // Should still decrypt to original plaintext+ expect(decrypt(dbConfig.githubToken)).toBe(originalToken);++ // Verify URL and eventType were updated+ expect(dbConfig.url).toBe(+ "https://api.github.com/repos/new-owner/new-repo/dispatches",+ );+ expect(dbConfig.eventType).toBe("new-event-type");+ });+ });});diff --git a/web/src/features/automations/components/actions/ActionHandlerRegistry.ts b/web/src/features/automations/components/actions/ActionHandlerRegistry.tsindex 6ec122c3d1..e9f99aa491 100644--- a/web/src/features/automations/components/actions/ActionHandlerRegistry.ts+++ b/web/src/features/automations/components/actions/ActionHandlerRegistry.ts@@ -3,6 +3,7 @@ import { type FieldValues } from "react-hook-form";import { type BaseActionHandler } from "./BaseActionHandler";import { WebhookActionHandler } from "./WebhookActionHandler";import { SlackActionHandler } from "./SlackActionHandler";+import { GitHubDispatchActionHandler } from "./GitHubDispatchActionHandler";export class ActionHandlerRegistry {private static handlers: Map<ActionType, BaseActionHandler<FieldValues>> =@@ -12,6 +13,7 @@ export class ActionHandlerRegistry {// Initialize handlers in static blockthis.handlers.set("WEBHOOK", new WebhookActionHandler());this.handlers.set("SLACK", new SlackActionHandler());+ this.handlers.set("GITHUB_DISPATCH", new GitHubDispatchActionHandler());}static getHandler<T extends FieldValues = FieldValues>(diff --git a/web/src/features/automations/components/actions/GitHubDispatchActionForm.tsx b/web/src/features/automations/components/actions/GitHubDispatchActionForm.tsxnew file mode 100644index 0000000000..08e9432048--- /dev/null+++ b/web/src/features/automations/components/actions/GitHubDispatchActionForm.tsx@@ -0,0 +1,136 @@+import { Input } from "@/src/components/ui/input";+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { type UseFormReturn } from "react-hook-form";+import { type ActionDomain } from "@langfuse/shared";+import { ExternalLink } from "lucide-react";+import Link from "next/link";++interface GitHubDispatchActionFormProps {+ form: UseFormReturn<any>;+ disabled: boolean;+ projectId: string;+ action?: ActionDomain;+}++export const GitHubDispatchActionForm: React.FC<+ GitHubDispatchActionFormProps+> = ({ form, disabled }) => {+ const displayGitHubToken = form.watch("githubDispatch.displayGitHubToken");++ return (+ <div className="space-y-4">+ <FormField+ control={form.control}+ name="githubDispatch.url"+ rules={{ required: "Repository Dispatch URL is required" }}+ render={({ field }) => (+ <FormItem>+ <FormLabel className="flex items-center">+ Repository Dispatch URL{" "}+ <span className="ml-1 text-destructive">*</span>+ </FormLabel>+ <FormControl>+ <Input+ placeholder="https://api.github.com/repos/owner/repo/dispatches"+ disabled={disabled}+ {...field}+ />+ </FormControl>+ <FormDescription>+ GitHub API endpoint for repository dispatch.{" "}+ <Link+ href="https://docs.github.com/en/rest/repos/repos#create-a-repository-dispatch-event"+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center text-primary hover:underline"+ >+ Learn more <ExternalLink className="ml-1 h-3 w-3" />+ </Link>+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />++ <FormField+ control={form.control}+ name="githubDispatch.eventType"+ rules={{ required: "Event type is required" }}+ render={({ field }) => (+ <FormItem>+ <FormLabel className="flex items-center">+ Event Type <span className="ml-1 text-destructive">*</span>+ </FormLabel>+ <FormControl>+ <Input+ placeholder="prompt-update"+ disabled={disabled}+ {...field}+ />+ </FormControl>+ <FormDescription>+ Event type for GitHub Actions workflow triggers. This will be used+ in the{" "}+ <code className="text-xs">on.repository_dispatch.types</code>{" "}+ filter in your workflow file.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />++ <FormField+ control={form.control}+ name="githubDispatch.githubToken"+ render={({ field }) => (+ <FormItem>+ <FormLabel className="flex items-center">+ GitHub Personal Access Token+ {!displayGitHubToken && (+ <span className="ml-1 text-destructive">*</span>+ )}+ </FormLabel>+ <FormControl>+ <Input+ type="password"+ placeholder={displayGitHubToken || "ghp_..."}+ disabled={disabled}+ {...field}+ />+ </FormControl>+ <FormDescription>+ GitHub PAT with <code className="text-xs">repo</code> scope for+ repository dispatch.+ {displayGitHubToken+ ? " Leave empty to keep existing token."+ : ""}{" "}+ <Link+ href="https://github.com/settings/tokens/new?scopes=repo&description=Langfuse%20Automation"+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center text-primary hover:underline"+ >+ Create token <ExternalLink className="ml-1 h-3 w-3" />+ </Link>+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ );+};++// Schema exported for use in automationForm.tsx+export const githubDispatchSchema = {+ url: "",+ eventType: "",+ githubToken: "",+};diff --git a/web/src/features/automations/components/actions/GitHubDispatchActionHandler.tsx b/web/src/features/automations/components/actions/GitHubDispatchActionHandler.tsxnew file mode 100644index 0000000000..a612585f5f--- /dev/null+++ b/web/src/features/automations/components/actions/GitHubDispatchActionHandler.tsx@@ -0,0 +1,120 @@+import React from "react";+import { type UseFormReturn } from "react-hook-form";+import { type BaseActionHandler } from "./BaseActionHandler";+import { GitHubDispatchActionForm } from "./GitHubDispatchActionForm";+import {+ type AutomationDomain,+ type ActionCreate,+ type ActionDomain,+} from "@langfuse/shared";+import { z } from "zod/v4";++// Define the form schema for GitHub dispatch actions+export const GitHubDispatchActionFormSchema = z.object({+ githubDispatch: z.object({+ url: z.string().url("Invalid URL"),+ eventType: z.string().min(1, "Event type is required").max(100),+ githubToken: z.string(),+ displayGitHubToken: z.string().optional(), // Display value for existing token+ }),+});++type GitHubDispatchActionFormData = z.infer<+ typeof GitHubDispatchActionFormSchema+>;++export class GitHubDispatchActionHandler+ implements BaseActionHandler<GitHubDispatchActionFormData>+{+ actionType = "GITHUB_DISPATCH" as const;++ getDefaultValues(+ automation?: AutomationDomain,+ ): GitHubDispatchActionFormData {+ return {+ githubDispatch: {+ url:+ (automation?.action?.type === "GITHUB_DISPATCH" &&+ automation?.action?.config &&+ "url" in automation.action.config &&+ automation.action.config.url) ||+ "",+ eventType:+ (automation?.action?.type === "GITHUB_DISPATCH" &&+ automation?.action?.config &&+ "eventType" in automation.action.config &&+ automation.action.config.eventType) ||+ "",+ githubToken: "", // Never populate with existing token for security+ displayGitHubToken:+ automation?.action?.type === "GITHUB_DISPATCH" &&+ automation?.action?.config &&+ "displayGitHubToken" in automation.action.config+ ? automation.action.config.displayGitHubToken+ : undefined,+ },+ };+ }++ validateFormData(formData: GitHubDispatchActionFormData): {+ isValid: boolean;+ errors?: string[];+ } {+ const errors: string[] = [];++ if (!formData.githubDispatch?.url) {+ errors.push("GitHub dispatch URL is required");+ }++ if (!formData.githubDispatch?.eventType) {+ errors.push("Event type is required");+ } else if (formData.githubDispatch.eventType.length > 100) {+ errors.push("Event type must be 100 characters or less");+ }++ // Token is required only if there's no existing token (displayGitHubToken)+ if (+ !formData.githubDispatch?.githubToken &&+ !formData.githubDispatch?.displayGitHubToken+ ) {+ errors.push("GitHub token is required");+ }++ return {+ isValid: errors.length === 0,+ errors: errors.length > 0 ? errors : undefined,+ };+ }++ buildActionConfig(formData: GitHubDispatchActionFormData): ActionCreate {+ return {+ type: "GITHUB_DISPATCH",+ // Only include fields if they have values (for updates)+ ...(formData.githubDispatch?.url+ ? { url: formData.githubDispatch.url }+ : {}),+ ...(formData.githubDispatch?.eventType+ ? { eventType: formData.githubDispatch.eventType }+ : {}),+ ...(formData.githubDispatch?.githubToken+ ? { githubToken: formData.githubDispatch.githubToken }+ : {}),+ };+ }++ renderForm(props: {+ form: UseFormReturn<GitHubDispatchActionFormData>;+ disabled: boolean;+ projectId: string;+ action?: ActionDomain;+ }) {+ return (+ <GitHubDispatchActionForm+ form={props.form}+ disabled={props.disabled}+ projectId={props.projectId}+ action={props.action}+ />+ );+ }+}diff --git a/web/src/features/automations/components/actions/index.ts b/web/src/features/automations/components/actions/index.tsindex 6d326b41f5..b914a8c886 100644--- a/web/src/features/automations/components/actions/index.ts+++ b/web/src/features/automations/components/actions/index.ts@@ -1,4 +1,5 @@export { type BaseActionHandler } from "./BaseActionHandler";export { WebhookActionHandler } from "./WebhookActionHandler";export { SlackActionHandler } from "./SlackActionHandler";+export { GitHubDispatchActionHandler } from "./GitHubDispatchActionHandler";export { ActionHandlerRegistry } from "./ActionHandlerRegistry";diff --git a/web/src/features/automations/components/automationForm.tsx b/web/src/features/automations/components/automationForm.tsxindex f15b184629..1f508debdb 100644--- a/web/src/features/automations/components/automationForm.tsx+++ b/web/src/features/automations/components/automationForm.tsx@@ -53,6 +53,14 @@ const slackSchema = z.object({messageTemplate: z.string().optional(),});+// Define GitHub Dispatch action schema+const githubDispatchSchema = z.object({+ url: z.string().url("Invalid URL"),+ eventType: z.string().min(1, "Event type is required").max(100),+ githubToken: z.string(),+ displayGitHubToken: z.string().optional(),+});+// Define the TriggerEventSource enum directly in this file to match the backendenum TriggerEventSource {Prompt = "prompt",@@ -78,13 +86,21 @@ const formSchema = z.discriminatedUnion("actionType", [actionType: z.literal("SLACK"),slack: slackSchema,}),+ baseFormSchema.extend({+ actionType: z.literal("GITHUB_DISPATCH"),+ githubDispatch: githubDispatchSchema,+ }),]);type FormValues = z.infer<typeof formSchema>;interface AutomationFormProps {projectId: string;- onSuccess?: (automationId?: string, webhookSecret?: string) => void;+ onSuccess?: (+ automationId?: string,+ webhookSecret?: string,+ actionType?: "WEBHOOK" | "GITHUB_DISPATCH",+ ) => void;onCancel?: () => void;automation?: AutomationDomain;isEditing?: boolean;@@ -182,6 +198,22 @@ export const AutomationForm = ({messageTemplate: slackDefaults.slack.messageTemplate || "",},};+ } else if (actionType === "GITHUB_DISPATCH") {+ // Use action handler to get default values with proper typing+ const handler = ActionHandlerRegistry.getHandler("GITHUB_DISPATCH");+ const githubDefaults = handler.getDefaultValues(automation);+ return {+ ...baseValues,+ actionType: "GITHUB_DISPATCH" as const,+ eventSource: TriggerEventSource.Prompt,+ githubDispatch: {+ url: githubDefaults.githubDispatch.url || "",+ eventType: githubDefaults.githubDispatch.eventType || "",+ githubToken: githubDefaults.githubDispatch.githubToken || "",+ displayGitHubToken:+ githubDefaults.githubDispatch.displayGitHubToken || undefined,+ },+ };} else {throw new Error("Invalid action type");}@@ -262,7 +294,11 @@ export const AutomationForm = ({description: `Successfully created automation "${data.name}".`,});- onSuccess?.(result.automation.id, result.webhookSecret);+ onSuccess?.(+ result.automation.id,+ result.webhookSecret,+ data.actionType as "WEBHOOK" | "GITHUB_DISPATCH",+ );}};@@ -283,6 +319,10 @@ export const AutomationForm = ({const handler = ActionHandlerRegistry.getHandler("SLACK");const defaultValues = handler.getDefaultValues();form.setValue("slack", defaultValues.slack);+ } else if (value === "GITHUB_DISPATCH") {+ const handler = ActionHandlerRegistry.getHandler("GITHUB_DISPATCH");+ const defaultValues = handler.getDefaultValues();+ form.setValue("githubDispatch", defaultValues.githubDispatch);}// If we are creating a new automation, update the default name@@ -502,7 +542,9 @@ export const AutomationForm = ({? "Webhook": actionType === "SLACK"? "Slack"- : "Annotation Queue"}+ : actionType === "GITHUB_DISPATCH"+ ? "GitHub Dispatch"+ : "Annotation Queue"}</SelectItem>),)}diff --git a/web/src/features/automations/components/automations.tsx b/web/src/features/automations/components/automations.tsxindex 87637300e8..ffc503ba4b 100644--- a/web/src/features/automations/components/automations.tsx+++ b/web/src/features/automations/components/automations.tsx@@ -161,9 +161,9 @@ export default function AutomationsPage() {const handleCreateSuccess = (automationId?: string,webhookSecret?: string,+ actionType?: "WEBHOOK" | "GITHUB_DISPATCH",) => {- // Show webhook secret if provided- if (webhookSecret) {+ if (webhookSecret && actionType === "WEBHOOK") {setWebhookSecret(webhookSecret);setShowSecretDialog(true);}diff --git a/web/src/features/automations/server/githubDispatchHelpers.ts b/web/src/features/automations/server/githubDispatchHelpers.tsnew file mode 100644index 0000000000..0dac565228--- /dev/null+++ b/web/src/features/automations/server/githubDispatchHelpers.ts@@ -0,0 +1,143 @@+import { encrypt } from "@langfuse/shared/encryption";+import {+ type ActionCreate,+ type ActionConfig,+ type GitHubDispatchActionConfigWithSecrets,+ type GitHubDispatchActionCreate,+ isGitHubDispatchActionConfig,+} from "@langfuse/shared";+import {+ getActionByIdWithSecrets,+ validateWebhookURL,+} from "@langfuse/shared/src/server";+import { TRPCError } from "@trpc/server";++interface GitHubDispatchConfigOptions {+ actionConfig: ActionCreate;+ actionId?: string;+ projectId: string;+}++export async function processGitHubDispatchActionConfig({+ actionConfig,+ actionId,+ projectId,+}: GitHubDispatchConfigOptions): Promise<{+ finalActionConfig: ActionConfig;+ githubToken?: string; // For one-time display+}> {+ if (actionConfig.type !== "GITHUB_DISPATCH") {+ throw new Error("Action type is not GITHUB_DISPATCH");+ }++ const gitHubDispatchConfig = actionConfig as GitHubDispatchActionCreate;++ const existingAction = actionId+ ? await getActionByIdWithSecrets({ projectId, actionId })+ : undefined;++ let existingActionConfig: GitHubDispatchActionConfigWithSecrets | undefined;+ if (existingAction) {+ if (!isGitHubDispatchActionConfig(existingAction.config)) {+ throw new Error(+ `Existing action ${actionId} does not have valid GitHub dispatch configuration`,+ );+ }+ existingActionConfig = existingAction.config;+ }++ // Determine URL to use+ let urlToUse: string;+ if (gitHubDispatchConfig.url && gitHubDispatchConfig.url.trim() !== "") {+ urlToUse = gitHubDispatchConfig.url;+ } else if (existingActionConfig?.url) {+ urlToUse = existingActionConfig.url;+ } else {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Repository Dispatch URL is required",+ });+ }++ try {+ await validateWebhookURL(urlToUse);+ } catch (error) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `Invalid webhook URL: ${error instanceof Error ? error.message : "Unknown error"}`,+ });+ }++ // Validate GitHub API URL format+ const urlPattern =+ /^https:\/\/api\.github\.com\/repos\/[^\/]+\/[^\/]+\/dispatches$/;+ const enterprisePattern =+ /^https:\/\/[^\/]+\/api\/v3\/repos\/[^\/]+\/[^\/]+\/dispatches$/;++ if (!urlPattern.test(urlToUse) && !enterprisePattern.test(urlToUse)) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ "URL must be a valid GitHub repository dispatch endpoint (e.g., https://api.github.com/repos/owner/repo/dispatches)",+ });+ }++ // Determine event type to use+ let eventTypeToUse: string;+ if (+ gitHubDispatchConfig.eventType &&+ gitHubDispatchConfig.eventType.trim() !== ""+ ) {+ eventTypeToUse = gitHubDispatchConfig.eventType;+ } else if (existingActionConfig?.eventType) {+ eventTypeToUse = existingActionConfig.eventType;+ } else {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Event type is required",+ });+ }++ let tokenToUse: string;+ let displayToken: string;+ let returnToken: string | undefined;++ if (+ gitHubDispatchConfig.githubToken &&+ gitHubDispatchConfig.githubToken.trim() !== ""+ ) {+ tokenToUse = gitHubDispatchConfig.githubToken;+ displayToken = maskGitHubToken(tokenToUse);+ returnToken = tokenToUse;+ } else if (existingActionConfig?.githubToken) {+ tokenToUse = existingActionConfig.githubToken;+ displayToken = existingActionConfig.displayGitHubToken;+ returnToken = undefined;+ } else {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "GitHub Personal Access Token is required",+ });+ }++ return {+ finalActionConfig: {+ type: "GITHUB_DISPATCH",+ url: urlToUse,+ eventType: eventTypeToUse,+ githubToken: returnToken !== undefined ? encrypt(tokenToUse) : tokenToUse,+ displayGitHubToken: displayToken,+ lastFailingExecutionId: existingActionConfig?.lastFailingExecutionId,+ },+ githubToken: returnToken,+ };+}++function maskGitHubToken(token: string): string {+ if (token.length < 6) {+ return token;+ }+ const prefix = token.substring(0, 4);+ const suffix = token.substring(token.length - 1);+ return `${prefix}...${suffix}`;+}diff --git a/web/src/features/automations/server/router.ts b/web/src/features/automations/server/router.tsindex 9f41192bf3..26a061496a 100644--- a/web/src/features/automations/server/router.ts+++ b/web/src/features/automations/server/router.ts@@ -9,6 +9,8 @@ import {isSafeWebhookActionConfig,isWebhookAction,convertToSafeWebhookConfig,+ isGitHubDispatchAction,+ convertToSafeGitHubDispatchConfig,} from "@langfuse/shared";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { v4 } from "uuid";@@ -21,6 +23,7 @@ import {} from "@langfuse/shared/src/server";import { generateWebhookSecret, encrypt } from "@langfuse/shared/encryption";import { processWebhookActionConfig } from "./webhookHelpers";+import { processGitHubDispatchActionConfig } from "./githubDispatchHelpers";import { TRPCError } from "@trpc/server";import { auditLog } from "@/src/features/audit-logs/auditLog";@@ -277,6 +280,13 @@ export const automationsRouter = createTRPCRouter({"Slack integration not found. Please connect your Slack workspace first.",});}+ } else if (input.actionType === "GITHUB_DISPATCH") {+ const githubResult = await processGitHubDispatchActionConfig({+ actionConfig: input.actionConfig,+ projectId: input.projectId,+ });+ finalActionConfig = githubResult.finalActionConfig;+ newUnencryptedWebhookSecret = githubResult.githubToken;}const [trigger, action, automation] = await ctx.prisma.$transaction(@@ -336,7 +346,9 @@ export const automationsRouter = createTRPCRouter({...action,config: isWebhookAction(action)? convertToSafeWebhookConfig(action.config)- : action.config,+ : isGitHubDispatchAction(action)+ ? convertToSafeGitHubDispatchConfig(action.config)+ : action.config,},trigger,automation,@@ -388,6 +400,13 @@ export const automationsRouter = createTRPCRouter({"Slack integration not found. Please connect your Slack workspace first.",});}+ } else if (input.actionType === "GITHUB_DISPATCH") {+ const githubResult = await processGitHubDispatchActionConfig({+ actionConfig: input.actionConfig,+ actionId: existingAutomation.action.id,+ projectId: input.projectId,+ });+ finalActionConfig = githubResult.finalActionConfig;}const [action, trigger, automation] = await ctx.prisma.$transaction(@@ -462,7 +481,9 @@ export const automationsRouter = createTRPCRouter({...action,config: isWebhookAction(action)? convertToSafeWebhookConfig(action.config)- : action.config,+ : isGitHubDispatchAction(action)+ ? convertToSafeGitHubDispatchConfig(action.config)+ : action.config,},trigger,automation,diff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.tsindex 9aa65e08e6..14bb0fec39 100644--- a/worker/src/queues/webhooks.ts+++ b/worker/src/queues/webhooks.ts@@ -7,6 +7,9 @@ import {JobConfigState,isSlackActionConfig,isWebhookAction,+ isGitHubDispatchAction,+ type AutomationDomain,+ type ActionDomainWithSecrets,} from "@langfuse/shared";import { decrypt, createSignatureHeader } from "@langfuse/shared/encryption";import { prisma } from "@langfuse/shared/src/db";@@ -73,6 +76,12 @@ export const executeWebhook = async (input,automation,});+ } else if (automation.action.type === "GITHUB_DISPATCH") {+ await executeGitHubDispatchAction({+ input,+ automation,+ skipValidation: options?.skipValidation,+ });} else {throw new InternalServerError(`Unsupported action type: ${automation.action.type}`,@@ -89,99 +98,39 @@ export const executeWebhook = async (};/**- * Execute webhook action with HTTP request and signature validation+ * Shared HTTP execution logic for webhook and GitHub dispatch actions+ * Handles: fetch with timeout, retry logic, status validation, execution tracking*/-async function executeWebhookAction({- input,- automation,+async function executeHttpAction({+ url,+ payload,+ headers,+ projectId,skipValidation,+ automation,+ executionId,+ executionStart,+ actionConfig,}: {- input: WebhookInput;- automation: Awaited<ReturnType<typeof getAutomationById>>;+ url: string;+ payload: string;+ headers: Record<string, string>;+ projectId: string;skipValidation?: boolean;-}) {- if (!automation) return;-- const { projectId, executionId } = input;- const executionStart = new Date();+ automation: AutomationDomain;+ executionId: string;+ executionStart: Date;+ actionConfig: ActionDomainWithSecrets;+}): Promise<{ httpStatus: number; responseBody: string }> {let httpStatus: number | undefined;let responseBody: string | undefined;try {- const actionConfig = await getActionByIdWithSecrets({- projectId,- actionId: automation.action.id,- });-- if (!actionConfig) {- throw new InternalServerError("Action config not found");- }-- if (!isWebhookAction(actionConfig)) {- throw new InternalServerError(- "Action config is not a valid webhook configuration",- );- }-- const webhookConfig = actionConfig.config;-- // Validate and prepare webhook payload- const validatedPayload = PromptWebhookOutboundSchema.safeParse({- id: input.executionId,- timestamp: new Date(),- type: input.payload.type,- apiVersion: "v1",- action: input.payload.action,- prompt: input.payload.prompt,- });-- if (!validatedPayload.success) {- throw new InternalServerError(- `Invalid webhook payload: ${validatedPayload.error.message}`,- );- }-- // Prepare webhook payload with prompt always last- const { prompt, ...otherFields } = validatedPayload.data;- const webhookPayload = JSON.stringify({- ...otherFields,- prompt,- });-- // Prepare headers with signature if secret exists- const requestHeaders: Record<string, string> = {};-- // Add webhook config headers first- if (webhookConfig.requestHeaders) {- for (const [key, value] of Object.entries(webhookConfig.requestHeaders)) {- requestHeaders[key] = value.value;- }- }-- // Add default headers with precedence- for (const [key, value] of Object.entries(WebhookDefaultHeaders)) {- requestHeaders[key] = value;- }-- try {- const decryptedSecret = decrypt(webhookConfig.secretKey);- const signature = createSignatureHeader(webhookPayload, decryptedSecret);- requestHeaders["x-langfuse-signature"] = signature;- } catch (error) {- logger.error(- "Failed to decrypt webhook secret or generate signature",- error,- );- throw new InternalServerError("Failed to generate webhook signature");- }-- // Execute webhook with retries+ // Execute HTTP request with retriesawait backOff(async () => {- logger.debug(- `Sending webhook to ${webhookConfig.url} with payload ${JSON.stringify(- webhookPayload,- )} and headers ${JSON.stringify(requestHeaders)}`,+ logger.info(+ `Sending HTTP request to ${url} for action ${automation.action.id}`,);// Create AbortController for timeout@@ -193,13 +142,13 @@ async function executeWebhookAction({try {// Skip validation when flag is set (for tests with MSW mocking)if (!skipValidation) {- await validateWebhookURL(webhookConfig.url);+ await validateWebhookURL(url);}- const res = await fetch(webhookConfig.url, {+ const res = await fetch(url, {method: "POST",- body: webhookPayload,- headers: requestHeaders,+ body: payload,+ headers,signal: abortController.signal,});@@ -208,19 +157,19 @@ async function executeWebhookAction({if (!res.ok) {logger.warn(- `Webhook does not return 2xx status: failed with status ${res.status} for url ${webhookConfig.url} and project ${projectId}. Body: ${responseBody}`,+ `Webhook does not return 2xx status: failed with status ${res.status} for url ${url} and project ${projectId}. Body: ${responseBody}`,);throw new Error(- `Webhook does not return 2xx status: failed with status ${res.status} for url ${webhookConfig.url} and project ${projectId}`,+ `Webhook does not return 2xx status: failed with status ${res.status} for url ${url} and project ${projectId}`,);}} catch (error) {if (error instanceof Error && error.name === "AbortError") {logger.warn(- `Webhook timeout after ${env.LANGFUSE_WEBHOOK_TIMEOUT_MS}ms for url ${webhookConfig.url} and project ${projectId}`,+ `Webhook timeout after ${env.LANGFUSE_WEBHOOK_TIMEOUT_MS}ms for url ${url} and project ${projectId}`,);throw new Error(- `Webhook timeout after ${env.LANGFUSE_WEBHOOK_TIMEOUT_MS}ms for url ${webhookConfig.url} and project ${projectId}`,+ `Webhook timeout after ${env.LANGFUSE_WEBHOOK_TIMEOUT_MS}ms for url ${url} and project ${projectId}`,);}throw error;@@ -247,28 +196,24 @@ async function executeWebhookAction({finishedAt: new Date(),},});++ return { httpStatus: httpStatus!, responseBody: responseBody! };} catch (error) {- logger.error("Error executing webhook action", error);+ logger.error("Error executing HTTP action", error);- // Handle webhook action failure with retry logic and trigger disabling+ // Handle action failure with retry logic and trigger disablingconst shouldRetryJob =error instanceof LangfuseNotFoundError ||error instanceof InternalServerError;if (shouldRetryJob) {- logger.warn(`Retrying BullMQ for webhook action ${automation.action.id}`);+ logger.warn(`Retrying BullMQ for action ${automation.action.id}`);throw error; // Trigger BullMQ retry}- // Get action config for updating in case of failure- const failureActionConfig = await getActionByIdWithSecrets({- projectId,- actionId: automation.action.id,- });-- if (!failureActionConfig) {+ if (!actionConfig) {logger.error("Action config not found for failure handling");- return;+ throw error;}// Update execution status and check if we should disable trigger@@ -314,15 +259,21 @@ async function executeWebhookAction({});// Update action config to store the failing execution ID- await tx.action.update({- where: { id: automation.action.id, projectId },- data: {- config: {- ...failureActionConfig.config,- lastFailingExecutionId: executionId,+ // Type guard to ensure we only update webhook or GitHub dispatch configs+ if (+ isWebhookAction(actionConfig) ||+ isGitHubDispatchAction(actionConfig)+ ) {+ await tx.action.update({+ where: { id: automation.action.id, projectId },+ data: {+ config: {+ ...actionConfig.config,+ lastFailingExecutionId: executionId,+ } as any, // Cast needed for Prisma Json type},- },- });+ });+ }logger.warn(`Automation ${automation.trigger.id} disabled after ${consecutiveFailures} consecutive failures in project ${projectId}`,@@ -331,11 +282,212 @@ async function executeWebhookAction({});logger.debug(- `Webhook action failed for action ${automation.action.id} in project ${projectId}`,+ `HTTP action failed for action ${automation.action.id} in project ${projectId}`,);++ // Error has been handled - don't rethrow+ // Return empty response to indicate failure was handled+ return { httpStatus: httpStatus || 0, responseBody: responseBody || "" };}}+/**+ * Execute webhook action with HTTP request and signature validation+ */+async function executeWebhookAction({+ input,+ automation,+ skipValidation,+}: {+ input: WebhookInput;+ automation: Awaited<ReturnType<typeof getAutomationById>>;+ skipValidation?: boolean;+}) {+ if (!automation) return;++ const { projectId, executionId } = input;+ const executionStart = new Date();++ const actionConfig = await getActionByIdWithSecrets({+ projectId,+ actionId: automation.action.id,+ });++ if (!actionConfig) {+ throw new InternalServerError("Action config not found");+ }++ if (!isWebhookAction(actionConfig)) {+ throw new InternalServerError(+ "Action config is not a valid webhook configuration",+ );+ }++ const webhookConfig = actionConfig.config;++ // Validate and prepare webhook payload+ const validatedPayload = PromptWebhookOutboundSchema.safeParse({+ id: input.executionId,+ timestamp: new Date(),+ type: input.payload.type,+ apiVersion: "v1",+ action: input.payload.action,+ prompt: input.payload.prompt,+ });++ if (!validatedPayload.success) {+ throw new InternalServerError(+ `Invalid webhook payload: ${validatedPayload.error.message}`,+ );+ }++ // Prepare webhook payload with prompt always last+ const { prompt, ...otherFields } = validatedPayload.data;+ const webhookPayload = JSON.stringify({+ ...otherFields,+ prompt,+ });++ // Prepare headers with signature if secret exists+ const requestHeaders: Record<string, string> = {};++ // Add webhook config headers first+ if (webhookConfig.requestHeaders) {+ for (const [key, value] of Object.entries(webhookConfig.requestHeaders)) {+ requestHeaders[key] = value.value;+ }+ }++ // Add default headers with precedence+ for (const [key, value] of Object.entries(WebhookDefaultHeaders)) {+ requestHeaders[key] = value;+ }++ try {+ const decryptedSecret = decrypt(webhookConfig.secretKey);+ const signature = createSignatureHeader(webhookPayload, decryptedSecret);+ requestHeaders["x-langfuse-signature"] = signature;+ } catch (error) {+ logger.error(+ "Failed to decrypt webhook secret or generate signature",+ error,+ );+ throw new InternalServerError("Failed to generate webhook signature");+ }++ // Execute HTTP request using shared function+ await executeHttpAction({+ url: webhookConfig.url,+ payload: webhookPayload,+ headers: requestHeaders,+ projectId,+ skipValidation,+ automation,+ executionId,+ executionStart,+ actionConfig,+ });+}++/**+ * Execute GitHub Dispatch action with repository dispatch API+ */+async function executeGitHubDispatchAction({+ input,+ automation,+ skipValidation,+}: {+ input: WebhookInput;+ automation: Awaited<ReturnType<typeof getAutomationById>>;+ skipValidation?: boolean;+}) {+ if (!automation) return;++ const { projectId, executionId } = input;+ const executionStart = new Date();++ const actionConfig = await getActionByIdWithSecrets({+ projectId,+ actionId: automation.action.id,+ });++ if (!actionConfig) {+ throw new InternalServerError("Action config not found");+ }++ if (!isGitHubDispatchAction(actionConfig)) {+ throw new InternalServerError(+ "Action config is not a valid GitHub dispatch configuration",+ );+ }++ const githubConfig = actionConfig.config;++ // Validate and prepare Langfuse payload+ const validatedPayload = PromptWebhookOutboundSchema.safeParse({+ id: input.executionId,+ timestamp: new Date(),+ type: input.payload.type,+ apiVersion: "v1",+ action: input.payload.action,+ prompt: input.payload.prompt,+ });++ if (!validatedPayload.success) {+ throw new InternalServerError(+ `Invalid webhook payload: ${validatedPayload.error.message}`,+ );+ }++ // Use configured event_type (required field)+ const eventType = githubConfig.eventType;++ // Transform to GitHub dispatch format+ const { prompt, ...otherFields } = validatedPayload.data;+ const githubPayload = JSON.stringify({+ event_type: eventType,+ client_payload: {+ ...otherFields,+ prompt,+ },+ });++ // Prepare headers with GitHub token+ const requestHeaders: Record<string, string> = {};++ // Add default headers+ for (const [key, value] of Object.entries(WebhookDefaultHeaders)) {+ requestHeaders[key] = value;+ }++ try {+ const decryptedToken = decrypt(githubConfig.githubToken);++ // Add GitHub token as Bearer auth+ requestHeaders["Authorization"] = `Bearer ${decryptedToken}`;++ // Add signature for optional verification (using GitHub token as secret)+ const signature = createSignatureHeader(githubPayload, decryptedToken);+ requestHeaders["x-langfuse-signature"] = signature;+ } catch (error) {+ logger.error("Failed to decrypt GitHub token or generate signature", error);+ throw new InternalServerError("Failed to generate GitHub authentication");+ }++ // Execute HTTP request using shared function+ await executeHttpAction({+ url: githubConfig.url,+ payload: githubPayload,+ headers: requestHeaders,+ projectId,+ skipValidation,+ automation,+ executionId,+ executionStart,+ actionConfig,+ });+}+/*** Execute Slack action with message sending via SlackService*/