Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(skills): support version automations (#19296)

tobi_kleeb966c516c1
diff --git a/packages/shared/src/domain/automations.ts b/packages/shared/src/domain/automations.ts
index 9b941903cc..fb5b59f9af 100644
--- a/packages/shared/src/domain/automations.ts
+++ b/packages/shared/src/domain/automations.ts
@@ -8,6 +8,7 @@ import {
export enum TriggerEventSource {
Prompt = "prompt",
+ Skill = "skill",
Monitor = "monitor",
// ProjectNotification groups platform "something went wrong" events (e.g.
// failed exports, blocked evaluators). The specific event lives in the
@@ -21,6 +22,7 @@ export type TriggerEventAction = z.infer<typeof EventActionSchema>;
export const TriggerEventSourceSchema = z.enum([
TriggerEventSource.Prompt,
+ TriggerEventSource.Skill,
TriggerEventSource.Monitor,
TriggerEventSource.ProjectNotification,
]);
@@ -72,7 +74,7 @@ export const ActionTypeSchema = z.enum([
]);
export const AvailableWebhookApiSchema = z.partialRecord(
- z.enum(["prompt", "monitor", "project-notification"]),
+ z.enum(["prompt", "skill", "monitor", "project-notification"]),
z.enum(["v1"]),
);
diff --git a/packages/shared/src/domain/webhooks.ts b/packages/shared/src/domain/webhooks.ts
index e4e0704883..80e4829924 100644
--- a/packages/shared/src/domain/webhooks.ts
+++ b/packages/shared/src/domain/webhooks.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import { jsonSchema } from "../utils/zod";
+import { SkillVersionSchema } from "../features/skills/types";
import { EventActionSchema } from "./automations";
export const WebhookContentTypeHeader = "content-type";
@@ -54,9 +55,20 @@ export const PromptWebhookOutboundSchema = z
export type PromptWebhookOutput = z.infer<typeof PromptWebhookOutboundSchema>;
+export const SkillWebhookOutboundSchema = WebhookOutboundBaseSchema.extend({
+ type: z.literal("skill-version"),
+ skill: SkillVersionSchema,
+ user: z
+ .object({ name: z.string().nullable(), email: z.string().nullable() })
+ .optional(),
+});
+
export const GitHubDispatchWebhookOutboundSchema = z.object({
event_type: z.string(),
- client_payload: PromptWebhookOutboundSchema,
+ client_payload: z.union([
+ PromptWebhookOutboundSchema,
+ SkillWebhookOutboundSchema,
+ ]),
});
export type GitHubDispatchWebhookOutput = z.infer<
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 2e3894aa93..a9bc0743a4 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -8,6 +8,7 @@ import {
} from "../features/batchAction/types";
import { BatchTableNames } from "../interfaces/tableNames";
import { EventActionSchema } from "../domain";
+import { SkillVersionSchema } from "../features/skills/types";
import { PromptDomainSchema } from "../domain/prompts";
import { ObservationAddToDatasetConfigSchema } from "../features/batchAction/addToDatasetTypes";
import {
@@ -308,22 +309,30 @@ export const NotificationEventSchema = z.discriminatedUnion("type", [
// Future notification types can be added here
]);
+const entityChangeUserSchema = z.object({
+ id: z.string(),
+ name: z.string().nullable(),
+ email: z.string().nullable(),
+});
+
export const promptVersionWebhookEnvelopeSchema = z.object({
type: z.literal("prompt-version"),
prompt: PromptDomainSchema,
action: EventActionSchema,
- user: z
- .object({
- id: z.string(),
- name: z.string().nullable(),
- email: z.string().nullable(),
- })
- .optional(),
+ user: entityChangeUserSchema.optional(),
+});
+
+export const skillVersionWebhookEnvelopeSchema = z.object({
+ type: z.literal("skill-version"),
+ skill: SkillVersionSchema,
+ action: EventActionSchema,
+ user: entityChangeUserSchema.optional(),
});
/** WebhookOutboundEnvelopeSchema is the WebhookInput.payload contract: a discriminated union over `type`. The monitor-alert and system variants are unified envelopes (queue payload = HTTP outbound body); the prompt-version variant keeps its original dispatch-time wrap. */
export const WebhookOutboundEnvelopeSchema = z.discriminatedUnion("type", [
promptVersionWebhookEnvelopeSchema,
+ skillVersionWebhookEnvelopeSchema,
MonitorWebhookQueueEventSchema,
ProjectNotificationWebhookQueueEventSchema,
]);
@@ -343,13 +352,15 @@ export const EntityChangeEventSchema = z.discriminatedUnion("entityType", [
promptId: z.string(),
action: EventActionSchema,
prompt: PromptDomainSchema,
- user: z
- .object({
- id: z.string(),
- name: z.string().nullable(),
- email: z.string().nullable(),
- })
- .optional(),
+ user: entityChangeUserSchema.optional(),
+ }),
+ z.object({
+ entityType: z.literal("skill-version"),
+ projectId: z.string(),
+ skillId: z.string(),
+ action: EventActionSchema,
+ skill: SkillVersionSchema,
+ user: entityChangeUserSchema.optional(),
}),
// Add other entity types here in the future
]);
diff --git a/web/src/__tests__/server/unit/skill-service.servertest.ts b/web/src/__tests__/server/unit/skill-service.servertest.ts
index 51cb33e878..15b443626f 100644
--- a/web/src/__tests__/server/unit/skill-service.servertest.ts
+++ b/web/src/__tests__/server/unit/skill-service.servertest.ts
@@ -1,12 +1,22 @@
import { createHash } from "node:crypto";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ProjectAuthedContext } from "@/src/server/api/trpc";
+import type * as SharedServer from "@langfuse/shared/src/server";
import type { PrismaClient } from "@langfuse/shared/src/db";
import { OrganizationId, ProjectId, SystemRoleId } from "@langfuse/shared/rbac";
import { type AuthorizationContext } from "@/src/features/auth/policy/types";
import { SkillService } from "@/src/features/skills/server/skill-service";
import { auditLog } from "@/src/features/audit-logs/server";
+const queueAdd = vi.hoisted(() => vi.fn());
+vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
+ const actual = await importOriginal<typeof SharedServer>();
+ return {
+ ...actual,
+ EntityChangeQueue: { getInstance: () => ({ add: queueAdd }) },
+ };
+});
+
vi.mock("@/src/features/audit-logs/server", () => ({
auditLog: vi.fn(),
}));
@@ -80,8 +90,11 @@ describe("SkillService versions", () => {
findFirst: vi.fn().mockResolvedValue(null),
findFirstOrThrow: vi.fn().mockResolvedValue({ version: 1 }),
findMany: vi.fn().mockResolvedValue([]),
- update: vi.fn(),
+ update: vi
+ .fn()
+ .mockResolvedValue({ updatedAt: new Date("2026-10-23T12:00:00Z") }),
updateMany: vi.fn(),
+ updateManyAndReturn: vi.fn().mockResolvedValue([]),
delete: vi.fn(),
deleteMany: vi.fn().mockResolvedValue({ count: 2 }),
create,
@@ -170,6 +183,107 @@ describe("SkillService versions", () => {
};
}
+ it("does not publish changes from a rolled-back transaction", async () => {
+ const test = setup();
+ test.transaction.mockImplementation(async (callback) => {
+ await callback(test.tx);
+ throw new Error("commit failed");
+ });
+ await expect(test.service.createVersion(test.params)).rejects.toThrow(
+ "commit failed",
+ );
+ expect(queueAdd).not.toHaveBeenCalled();
+ });
+
+ it("keeps a committed version successful when the automation queue is unavailable", async () => {
+ const test = setup();
+ queueAdd.mockRejectedValueOnce(new Error("queue unavailable"));
+ await expect(
+ test.service.createVersion(test.params),
+ ).resolves.toMatchObject({ id: "skill" });
+ expect(queueAdd).toHaveBeenCalledOnce();
+ });
+
+ it("publishes stored snapshots for changed tag versions", async () => {
+ const test = setup();
+ const updatedAt = new Date("2026-10-30T12:00:00Z");
+ test.tx.skill.findFirst.mockResolvedValue(test.skill);
+ test.tx.skill.updateManyAndReturn.mockResolvedValue([{ id: "skill" }]);
+ test.tx.skill.findMany.mockResolvedValue([
+ { ...test.skill, tags: ["support"], updatedAt },
+ ]);
+ await test.service.setTags({
+ projectId: "project",
+ name: "test-skill",
+ tags: ["support"],
+ actor: test.params.actor,
+ });
+ expect(test.tx.skill.updateManyAndReturn).toHaveBeenCalledWith({
+ where: {
+ projectId: "project",
+ name: "test-skill",
+ NOT: { tags: { equals: ["support"] } },
+ },
+ data: { tags: { set: ["support"] } },
+ select: { id: true },
+ });
+ expect(queueAdd.mock.calls.map((call) => call[1].payload)).toMatchObject([
+ {
+ action: "updated",
+ skill: { id: "skill", tags: ["support"], updatedAt },
+ },
+ ]);
+ });
+
+ it("publishes deletion with its former labels and the restored latest version", async () => {
+ const test = setup();
+ const deleted = {
+ ...test.skill,
+ version: 2,
+ labels: ["latest", "production"],
+ };
+ const previous = { ...test.skill, id: "previous", labels: [] };
+ test.tx.skill.findFirst
+ .mockResolvedValueOnce(deleted)
+ .mockResolvedValueOnce(previous);
+ await test.service.deleteVersion({
+ projectId: "project",
+ name: "test-skill",
+ version: 2,
+ actor: test.params.actor,
+ });
+ expect(queueAdd.mock.calls.map((call) => call[1].payload)).toEqual([
+ expect.objectContaining({
+ action: "deleted",
+ skill: expect.objectContaining({
+ id: "skill",
+ labels: ["latest", "production"],
+ }),
+ }),
+ expect.objectContaining({
+ action: "updated",
+ skill: expect.objectContaining({ id: "previous", labels: ["latest"] }),
+ }),
+ ]);
+ });
+
+ it("publishes each deleted version when deleting an entire skill", async () => {
+ const test = setup();
+ test.tx.skill.findMany.mockResolvedValue([
+ test.skill,
+ { ...test.skill, id: "previous", version: 2 },
+ ]);
+ await test.service.deleteSkill({
+ projectId: "project",
+ name: "test-skill",
+ actor: test.params.actor,
+ });
+ expect(queueAdd.mock.calls.map((call) => call[1].payload)).toEqual([
+ expect.objectContaining({ action: "deleted", skillId: "skill" }),
+ expect.objectContaining({ action: "deleted", skillId: "previous" }),
+ ]);
+ });
+
it("includes labels from older versions without counting their tags", async () => {
const test = setup();
test.db.skill.findMany
@@ -381,21 +495,38 @@ describe("SkillService versions", () => {
it("creates with only latest and leaves deployment labels on the previous version", async () => {
const test = setup();
+ const commit = Promise.withResolvers<void>();
+ test.transaction.mockImplementation(async (callback) => {
+ const result = await callback(test.tx);
+ await commit.promise;
+ return result;
+ });
const previous = {
+ ...test.skill,
id: "previous",
version: 1,
labels: ["latest", "production", "stable"],
};
test.tx.skill.findFirst.mockResolvedValue(previous);
test.tx.skill.findMany.mockResolvedValue([previous]);
+ test.create.mockResolvedValue({
+ ...test.skill,
+ version: 2,
+ labels: ["latest"],
+ });
const params = {
...test.params,
input: { ...test.params.input, labels: ["production"] },
};
- await test.service.createVersion(params);
+ const mutation = test.service.createVersion(params);
+ await vi.waitFor(() => expect(test.create).toHaveBeenCalledOnce());
+ expect(queueAdd).not.toHaveBeenCalled();
+ commit.resolve();
+ await mutation;
expect(test.create).toHaveBeenCalledWith({
+ include: expect.any(Object),
data: expect.objectContaining({
version: 2,
labels: ["latest"],
@@ -404,7 +535,27 @@ describe("SkillService versions", () => {
expect(test.tx.skill.update).toHaveBeenCalledWith({
where: { projectId: "project", id: "previous" },
data: { labels: { set: ["production", "stable"] } },
+ select: { updatedAt: true },
+ });
+ expect(queueAdd.mock.calls.map((call) => call[1].payload)).toMatchObject([
+ {
+ action: "updated",
+ skill: { id: "previous", labels: ["production", "stable"] },
+ },
+ { action: "created", skill: { id: "skill", labels: ["latest"] } },
+ ]);
+ const created = queueAdd.mock.calls[1]![1].payload.skill;
+ expect(created.files).toHaveLength(3);
+ expect(created.files[0]).toMatchObject({
+ path: "SKILL.md",
+ sha256Hash: test.blobs[0]!.sha256Hash,
});
+ expect(
+ created.files.every(
+ (file: Record<string, unknown>) =>
+ !("content" in file) && !("blob" in file),
+ ),
+ ).toBe(true);
});
it("blocks whole-skill deletion when an older version has a protected label", async () => {
@@ -447,6 +598,7 @@ describe("SkillService versions", () => {
expect(test.tx.skill.update).toHaveBeenCalledExactlyOnceWith({
where: { projectId: "project", id: "skill" },
data: { labels: { set: ["production", "stable", "latest"] } },
+ select: { updatedAt: true },
});
});
@@ -456,7 +608,7 @@ describe("SkillService versions", () => {
test.tx.skill.findFirst.mockResolvedValue(test.skill);
test.tx.skill.findMany.mockResolvedValue([
test.skill,
- { id: "previous", labels: ["stable"] },
+ { ...test.skill, id: "previous", labels: ["stable"] },
]);
await test.service.setLabels({
@@ -470,11 +622,24 @@ describe("SkillService versions", () => {
expect(test.tx.skill.update).toHaveBeenCalledWith({
where: { projectId: "project", id: "skill" },
data: { labels: { set: ["stable", "latest"] } },
+ select: { updatedAt: true },
});
expect(test.tx.skill.update).toHaveBeenCalledWith({
where: { projectId: "project", id: "previous" },
data: { labels: { set: [] } },
+ select: { updatedAt: true },
});
+ expect(queueAdd.mock.calls.map((call) => call[1].payload)).toMatchObject([
+ {
+ action: "updated",
+ skill: {
+ id: "skill",
+ labels: ["stable", "latest"],
+ updatedAt: new Date("2026-10-23T12:00:00Z"),
+ },
+ },
+ { action: "updated", skill: { id: "previous", labels: [] } },
+ ]);
});
it("deduplicates text and derives UTF-8 metadata inside the version transaction", async () => {
@@ -505,6 +670,7 @@ describe("SkillService versions", () => {
}),
);
expect(test.create).toHaveBeenCalledWith({
+ include: expect.any(Object),
data: expect.objectContaining({
name: "test-skill",
description: "A test skill",
diff --git a/web/src/features/automations/components/AutomationForm.clienttest.tsx b/web/src/features/automations/components/AutomationForm.clienttest.tsx
index 5878f260a9..fc13987481 100644
--- a/web/src/features/automations/components/AutomationForm.clienttest.tsx
+++ b/web/src/features/automations/components/AutomationForm.clienttest.tsx
@@ -31,6 +31,11 @@ vi.mock("@/src/utils/api", () => ({
useQuery: () => ({ data: { labels: [], tags: [] }, isFetching: false }),
},
},
+ skills: {
+ filterOptions: {
+ useQuery: () => ({ data: { labels: [], tags: [] }, isFetching: false }),
+ },
+ },
projects: { byId: { useQuery: () => ({ data: undefined }) } },
naturalLanguageFilters: {
createCompletion: { useMutation: () => ({ mutateAsync: vi.fn() }) },
@@ -64,6 +69,10 @@ vi.mock("@/src/features/organizations/hooks", () => ({
useLangfuseCloudRegion: () => ({ isLangfuseCloud: true, region: "US" }),
}));
+vi.mock("@/src/features/events", () => ({
+ useReadPath: () => ({ isV4: true }),
+}));
+
import { AutomationForm } from "./AutomationForm";
describe("AutomationForm handleActionTypeChange", () => {
diff --git a/web/src/features/automations/components/AutomationForm.tsx b/web/src/features/automations/components/AutomationForm.tsx
index e92577ca60..cab66845b7 100644
--- a/web/src/features/automations/components/AutomationForm.tsx
+++ b/web/src/features/automations/components/AutomationForm.tsx
@@ -59,6 +59,9 @@ import { webhookSchema } from "./actions/WebhookActionForm";
import { Alert } from "@/src/components/design-system/Alert/Alert";
import Link from "next/link";
import { Info } from "@langfuse/icons";
+import { useIsFeatureEnabled } from "@/src/features/feature-flags";
+import { useReadPath } from "@/src/features/events";
+import { useVersionFilterOptions } from "../hooks/useVersionFilterOptions";
// Define Slack action schema
const slackSchema = z.object({
@@ -83,8 +86,8 @@ const pagerDutySchema = z.object({
region: PagerDutyRegionSchema,
});
-/** promptEventActionDefaults is the default eventAction set for a fresh prompt-source automation. */
-const promptEventActionDefaults: string[] = ["created", "updated", "deleted"];
+/** versionEventActionDefaults is the default eventAction set for a fresh version-source automation. */
+const versionEventActionDefaults: string[] = ["created", "updated", "deleted"];
/** projectNotificationName derives the auto-generated channel name from the destination — the name field is hidden for this source. */
const projectNotificationName = (data: FormValues): string => {
@@ -215,11 +218,12 @@ const formSchema = z
}),
])
.superRefine((data, ctx) => {
- // Prompt-source triggers require at least one event action; monitor and
+ // Prompt and skill triggers require at least one event action; monitor and
// project-notification sources don't use this field (project-notification
// triggers are match-all).
if (
- data.eventSource === TriggerEventSource.Prompt &&
+ (data.eventSource === TriggerEventSource.Prompt ||
+ data.eventSource === TriggerEventSource.Skill) &&
data.eventAction.length === 0
) {
ctx.addIssue({
@@ -234,15 +238,22 @@ type FormValues = z.infer<typeof formSchema>;
/** EventSourceField renders the trigger source picker and routes changes through onSourceChange so the parent can reset dependent fields. */
const EventSourceField = ({
+ projectId,
control,
onSourceChange,
disabled,
}: {
+ projectId: string;
control: Control<FormValues>;
onSourceChange: (value: TriggerEventSource) => void;
disabled: boolean;
}) => {
const { isLangfuseCloud } = useLangfuseCloudRegion();
+ const { isV4 } = useReadPath();
+ const skillsEnabled = useIsFeatureEnabled("skillManagement", {
+ projectId,
+ enableForAdmins: false,
+ });
return (
<FormField
control={control}
@@ -264,6 +275,10 @@ const EventSourceField = ({
</FormControl>
<SelectContent>
<SelectItem value={TriggerEventSource.Prompt}>Prompt</SelectItem>
+ {((isV4 && skillsEnabled) ||
+ field.value === TriggerEventSource.Skill) && (
+ <SelectItem value={TriggerEventSource.Skill}>Skill</SelectItem>
+ )}
{(isLangfuseCloud ||
field.value === TriggerEventSource.Monitor) && (
<SelectItem value={TriggerEventSource.Monitor}>
@@ -285,22 +300,28 @@ const EventSourceField = ({
);
};
-/** PromptTriggerFields renders the eventAction picker and inline filter builder for prompt-source automations. */
-const PromptTriggerFields = ({
+/** VersionTriggerFields renders the eventAction picker and inline filter builder for prompt and skill automations. */
+const VersionTriggerFields = ({
projectId,
+ eventSource,
control,
disabled,
}: {
projectId: string;
+ eventSource: TriggerEventSource;
control: Control<FormValues>;
disabled: boolean;
}) => {
const [optionsOpened, setOptionsOpened] = React.useState(false);
- const { data: filterOptions, isFetching: optionsLoading } =
- api.prompts.filterOptions.useQuery(
- { projectId },
- { enabled: optionsOpened },
- );
+ const isSkill = eventSource === TriggerEventSource.Skill;
+ const resource = isSkill ? "skill" : "prompt";
+ const { filterOptions, isFetching: optionsLoading } = useVersionFilterOptions(
+ {
+ projectId,
+ eventSource,
+ enabled: optionsOpened,
+ },
+ );
return (
<>
@@ -319,16 +340,15 @@ const PromptTriggerFields = ({
options={[
{
value: "created",
- description: "Whenever a new prompt version is created",
+ description: `Whenever a new ${resource} version is created`,
},
{
value: "updated",
- description:
- "Whenever tags or labels on a prompt version are updated",
+ description: `Whenever tags or labels on a ${resource} version are updated`,
},
{
value: "deleted",
- description: "Whenever a prompt version is deleted",
+ description: `Whenever a ${resource} version is deleted`,
},
]}
className="my-0 w-auto overflow-hidden"
@@ -473,8 +493,9 @@ export const AutomationForm = ({
const resolvedEventAction: string[] =
automation?.trigger.eventActions ??
- (resolvedEventSource === TriggerEventSource.Prompt
- ? promptEventActionDefaults
+ (resolvedEventSource === TriggerEventSource.Prompt ||
+ resolvedEventSource === TriggerEventSource.Skill
+ ? versionEventActionDefaults
: resolvedEventSource === TriggerEventSource.ProjectNotification
? // New channels start with every event enabled; the per-event
// toggles in the settings section manage them afterwards.
@@ -724,7 +745,7 @@ export const AutomationForm = ({
if (value === TriggerEventSource.Monitor) {
form.setValue("eventAction", []);
} else {
- form.setValue("eventAction", promptEventActionDefaults);
+ form.setValue("eventAction", versionEventActionDefaults);
}
form.setValue("filter", []);
};
@@ -788,6 +809,7 @@ export const AutomationForm = ({
<CardContent className="space-y-4">
{!lockedEventSource && (
<EventSourceField
+ projectId={projectId}
control={form.control}
onSourceChange={handleEventSourceChange}
disabled={!hasAccess || !isEditing}
@@ -796,8 +818,10 @@ export const AutomationForm = ({
{watchedEventSource === TriggerEventSource.Monitor ? (
<MonitorTriggerFields projectId={projectId} />
) : (
- <PromptTriggerFields
+ <VersionTriggerFields
+ key={watchedEventSource}
projectId={projectId}
+ eventSource={watchedEventSource}
control={form.control}
disabled={!hasAccess || !isEditing}
/>
diff --git a/web/src/features/automations/components/actions/WebhookActionHandler.tsx b/web/src/features/automations/components/actions/WebhookActionHandler.tsx
index ed5284e8d4..a1129ce8b5 100644
--- a/web/src/features/automations/components/actions/WebhookActionHandler.tsx
+++ b/web/src/features/automations/components/actions/WebhookActionHandler.tsx
@@ -45,6 +45,8 @@ const apiVersionForEventSource = (
eventSource?: TriggerEventSource,
): z.infer<typeof AvailableWebhookApiSchema> => {
switch (eventSource) {
+ case TriggerEventSource.Skill:
+ return { skill: "v1" };
case TriggerEventSource.Monitor:
return { monitor: "v1" };
case TriggerEventSource.ProjectNotification:
diff --git a/web/src/features/automations/hooks/useVersionFilterOptions.ts b/web/src/features/automations/hooks/useVersionFilterOptions.ts
new file mode 100644
index 0000000000..27812c92d7
--- /dev/null
+++ b/web/src/features/automations/hooks/useVersionFilterOptions.ts
@@ -0,0 +1,32 @@
+import { TriggerEventSource } from "@langfuse/shared";
+import { api } from "@/src/utils/api";
+
+export function useVersionFilterOptions({
+ projectId,
+ eventSource,
+ enabled,
+}: {
+ projectId: string;
+ eventSource: TriggerEventSource;
+ enabled: boolean;
+}) {
+ const isSkill = eventSource === TriggerEventSource.Skill;
+ const promptOptions = api.prompts.filterOptions.useQuery(
+ { projectId },
+ { enabled: enabled && !isSkill },
+ );
+ const skillOptions = api.skills.filterOptions.useQuery(
+ { projectId },
+ { enabled: enabled && isSkill },
+ );
+
+ return {
+ filterOptions: isSkill
+ ? {
+ labels: skillOptions.data?.labels.map((value) => ({ value })) ?? [],
+ tags: skillOptions.data?.tags ?? [],
+ }
+ : promptOptions.data,
+ isFetching: isSkill ? skillOptions.isFetching : promptOptions.isFetching,
+ };
+}
diff --git a/web/src/features/skills/components/SkillsPage.tsx b/web/src/features/skills/components/SkillsPage.tsx
index c83cdb727d..d692db5b51 100644
--- a/web/src/features/skills/components/SkillsPage.tsx
+++ b/web/src/features/skills/components/SkillsPage.tsx
@@ -11,6 +11,7 @@ import {
Plus,
Terminal,
Trash,
+ Zap,
} from "@langfuse/icons";
import {
NumberParam,
@@ -145,6 +146,10 @@ function SkillsHeaderActions({
closeMenu,
}: SkillsHeaderActionsProps) {
const capture = usePostHogClientCapture();
+ const canReadAutomations = useHasProjectAccess({
+ projectId,
+ scope: "automations:read",
+ });
function handleInstall() {
closeMenu?.();
@@ -153,6 +158,14 @@ function SkillsHeaderActions({
return (
<div className="flex max-w-full flex-wrap items-center gap-2">
+ {canReadAutomations && (
+ <DesignSystemButton
+ href={`/project/${projectId}/automations`}
+ text="Automations"
+ icon={Zap}
+ variant="secondary"
+ />
+ )}
<DropdownMenu
ariaLabel="Use skill"
items={[
diff --git a/web/src/features/skills/server/skill-service.ts b/web/src/features/skills/server/skill-service.ts
index 8e390468c7..8ad44bed51 100644
--- a/web/src/features/skills/server/skill-service.ts
+++ b/web/src/features/skills/server/skill-service.ts
@@ -17,9 +17,15 @@ import {
type ListSkillsQuery,
type FilterState,
type SkillSelector,
+ type SkillVersionResponse,
+ type TriggerEventAction,
} from "@langfuse/shared";
import type { Prisma, PrismaClient, SkillBlob } from "@langfuse/shared/src/db";
import {
+ EntityChangeQueue,
+ QueueJobs,
+ QueueName,
+ logger,
SkillCacheService,
escapeSqlLikePattern,
redis,
@@ -35,6 +41,8 @@ import {
} from "@/src/features/prompts/server/utils/authorizeProtectedLabelMutation";
import { type SkillListOrderBy } from "../constants/skillsSorting";
+type SkillChange = { skill: SkillVersionResponse; action: TriggerEventAction };
+
type SkillActor =
| Pick<ProjectAuthedContext, "session">
| (ApiKeyProjectContext & { ctx?: AuthorizationContext });
@@ -183,20 +191,25 @@ export class SkillService {
});
const name = frontmatter.name;
+ const changes: SkillChange[] = [];
const skillId = await this.prisma.$transaction(async (tx) => {
await this.lockSkill(tx, params.projectId, name);
const latest = await tx.skill.findFirst({
where: { projectId: params.projectId, name },
orderBy: { version: "desc" },
- select: { id: true, version: true, labels: true, tags: true },
+ include: skillFilesInclude,
});
if (latest) {
- await this.removeLatestLabel({
+ const updatedLatest = await this.removeLatestLabel({
tx,
projectId: params.projectId,
latest,
actor: params.actor,
});
+ changes.push({
+ action: "updated",
+ skill: serializeVersion({ ...latest, ...updatedLatest }),
+ });
}
const versionFiles = await this.storeVersionFiles({
tx,
@@ -205,6 +218,7 @@ export class SkillService {
referencedBlobs,
});
const skill = await tx.skill.create({
+ include: skillFilesInclude,
data: {
id: randomUUID(),
projectId: params.projectId,
@@ -250,9 +264,11 @@ export class SkillService {
},
tx,
);
+ changes.push({ action: "created", skill: serializeVersion(skill) });
return skill.id;
});
+ await this.publishChanges(changes, params.actor);
return this.getById({ projectId: params.projectId, skillId });
}
@@ -510,6 +526,7 @@ export class SkillService {
actor: SkillActor;
}) {
const input = UpdateSkillLabelsBodySchema.parse({ labels: params.labels });
+ const changes: SkillChange[] = [];
const skillId = await this.prisma.$transaction(async (tx) => {
await this.lockSkill(tx, params.projectId, params.name);
const target = await tx.skill.findFirst({
@@ -534,7 +551,7 @@ export class SkillService {
const versions = await tx.skill.findMany({
where: { projectId: params.projectId, name: params.name },
- select: { id: true, labels: true },
+ include: skillFilesInclude,
});
const nextLabels = [...new Set(input.labels)];
for (const version of versions) {
@@ -548,12 +565,21 @@ export class SkillService {
]
: version.labels.filter((label) => !nextLabels.includes(label));
if (version.labels.join("\0") === labels.join("\0")) continue;
- await tx.skill.update({
+ const updated = await tx.skill.update({
where: {
projectId: params.projectId,
id: version.id,
},
data: { labels: { set: labels } },
+ select: { updatedAt: true },
+ });
+ changes.push({
+ action: "updated",
+ skill: serializeVersion({
+ ...version,
+ labels,
+ updatedAt: updated.updatedAt,
+ }),
});
await auditLog(
{
@@ -570,6 +596,7 @@ export class SkillService {
}
return target.id;
});
+ await this.publishChanges(changes, params.actor);
return this.getById({ projectId: params.projectId, skillId });
}
@@ -581,6 +608,7 @@ export class SkillService {
actor: SkillActor;
}) {
const input = UpdateSkillTagsBodySchema.parse({ tags: params.tags });
+ const changes: SkillChange[] = [];
const skillId = await this.prisma.$transaction(async (tx) => {
await this.lockSkill(tx, params.projectId, params.name);
const target = await tx.skill.findFirst({
@@ -594,10 +622,27 @@ export class SkillService {
if (!target) throw new LangfuseNotFoundError("Skill not found");
const tags = [...new Set(input.tags)];
- await tx.skill.updateMany({
- where: { projectId: params.projectId, name: params.name },
+ const updated = await tx.skill.updateManyAndReturn({
+ where: {
+ projectId: params.projectId,
+ name: params.name,
+ NOT: { tags: { equals: tags } },
+ },
data: { tags: { set: tags } },
+ select: { id: true },
});
+ if (updated.length > 0) {
+ const versions = await tx.skill.findMany({
+ where: {
+ projectId: params.projectId,
+ id: { in: updated.map(({ id }) => id) },
+ },
+ include: skillFilesInclude,
+ });
+ for (const version of versions) {
+ changes.push({ action: "updated", skill: serializeVersion(version) });
+ }
+ }
await auditLog(
{
...params.actor,
@@ -611,6 +656,7 @@ export class SkillService {
);
return target.id;
});
+ await this.publishChanges(changes, params.actor);
return this.getById({ projectId: params.projectId, skillId });
}
@@ -619,12 +665,13 @@ export class SkillService {
name: string;
actor: SkillActor;
}): Promise<void> {
+ const changes: SkillChange[] = [];
const where = { projectId: params.projectId, name: params.name };
const versions = await this.prisma.$transaction(async (tx) => {
await this.lockSkill(tx, params.projectId, params.name);
const versions = await tx.skill.findMany({
where,
- select: { version: true, labels: true, tags: true },
+ include: skillFilesInclude,
orderBy: { version: "asc" },
});
if (!versions.length) throw new LangfuseNotFoundError("Skill not found");
@@ -651,8 +698,15 @@ export class SkillService {
tx,
);
await tx.skill.deleteMany({ where });
+ changes.push(
+ ...versions.map((skill) => ({
+ action: "deleted" as const,
+ skill: serializeVersion(skill),
+ })),
+ );
return versions.map(({ version }) => ({ name: params.name, version }));
});
+ await this.publishChanges(changes, params.actor);
await this.skillCacheService.invalidateCache({
projectId: params.projectId,
versions,
@@ -665,6 +719,7 @@ export class SkillService {
version: number;
actor: SkillActor;
}): Promise<void> {
+ const changes: SkillChange[] = [];
await this.prisma.$transaction(async (tx) => {
await this.lockSkill(tx, params.projectId, params.name);
const target = await tx.skill.findFirst({
@@ -696,20 +751,30 @@ export class SkillService {
await tx.skill.delete({
where: { projectId: params.projectId, id: target.id },
});
+ changes.push({ action: "deleted", skill: serializeVersion(target) });
if (target.labels.includes(SKILL_LATEST_LABEL)) {
const latest = await tx.skill.findFirst({
where: { projectId: params.projectId, name: params.name },
orderBy: { version: "desc" },
- select: { id: true, labels: true },
+ include: skillFilesInclude,
});
if (latest) {
const labels = [...new Set([...latest.labels, SKILL_LATEST_LABEL])];
- await tx.skill.update({
+ const updated = await tx.skill.update({
where: {
projectId: params.projectId,
id: latest.id,
},
data: { labels: { set: labels } },
+ select: { updatedAt: true },
+ });
+ changes.push({
+ action: "updated",
+ skill: serializeVersion({
+ ...latest,
+ labels,
+ updatedAt: updated.updatedAt,
+ }),
});
await auditLog(
{
@@ -726,12 +791,54 @@ export class SkillService {
}
}
});
+ await this.publishChanges(changes, params.actor);
await this.skillCacheService.invalidateCache({
projectId: params.projectId,
versions: [{ name: params.name, version: params.version }],
});
}
+ private async publishChanges(changes: SkillChange[], actor: SkillActor) {
+ const user = "session" in actor ? actor.session.user : undefined;
+ await Promise.all(
+ changes.map(async ({ skill, action }) => {
+ try {
+ await EntityChangeQueue.getInstance()?.add(
+ QueueName.EntityChangeQueue,
+ {
+ timestamp: new Date(),
+ id: randomUUID(),
+ name: QueueJobs.EntityChangeJob,
+ payload: {
+ entityType: "skill-version",
+ projectId: skill.projectId,
+ skillId: skill.id,
+ action,
+ skill,
+ ...(user
+ ? {
+ user: {
+ id: user.id,
+ name: user.name ?? null,
+ email: user.email ?? null,
+ },
+ }
+ : {}),
+ },
+ },
+ );
+ } catch (error) {
+ logger.error("Failed to publish skill change event", {
+ error,
+ projectId: skill.projectId,
+ skillId: skill.id,
+ action,
+ });
+ }
+ }),
+ );
+ }
+
private async prepareVersionFiles(params: {
projectId: string;
files: CreateSkillVersionBody["files"];
@@ -813,16 +920,17 @@ export class SkillService {
projectId: string;
latest: { id: string; labels: string[] };
actor: SkillActor;
- }): Promise<void> {
+ }) {
const labels = params.latest.labels.filter(
(label) => label !== SKILL_LATEST_LABEL,
);
- await params.tx.skill.update({
+ const updated = await params.tx.skill.update({
where: {
projectId: params.projectId,
id: params.latest.id,
},
data: { labels: { set: labels } },
+ select: { updatedAt: true },
});
await auditLog(
{
@@ -836,6 +944,7 @@ export class SkillService {
},
params.tx,
);
+ return { labels, updatedAt: updated.updatedAt };
}
private async storeVersionFiles(params: {
diff --git a/worker/src/__tests__/promptVersionProcessor.test.ts b/worker/src/__tests__/promptVersionProcessor.test.ts
index 7c81de8e72..1ed63c4e93 100644
--- a/worker/src/__tests__/promptVersionProcessor.test.ts
+++ b/worker/src/__tests__/promptVersionProcessor.test.ts
@@ -9,8 +9,10 @@ import {
import {
createOrgProjectAndApiKey,
EntityChangeEventType,
+ EntityChangeEventSchema,
} from "@langfuse/shared/src/server";
import { ActionType, prisma } from "@langfuse/shared/src/db";
+import { skillVersionProcessor } from "../features/entityChange/skillVersionProcessor";
import { promptVersionProcessor } from "../features/entityChange/promptVersionProcessor";
describe("promptVersionChangeWorker", () => {
@@ -177,4 +179,98 @@ describe("promptVersionChangeWorker", () => {
}
},
);
+ it("routes serialized skill events only to matching skill automations", async () => {
+ const automationId = v4();
+ for (const source of [
+ TriggerEventSource.Skill,
+ TriggerEventSource.Prompt,
+ ]) {
+ await prisma.automation.create({
+ data: {
+ id: source === TriggerEventSource.Skill ? automationId : v4(),
+ project: { connect: { id: projectId } },
+ name: `${source} automation`,
+ action: {
+ create: {
+ projectId,
+ type: ActionType.WEBHOOK,
+ config: {
+ type: "WEBHOOK",
+ url: "https://webhook.example.com/test",
+ headers: {},
+ },
+ },
+ },
+ trigger: {
+ create: {
+ projectId,
+ eventSource: source,
+ eventActions: ["created"],
+ status: JobConfigState.ACTIVE,
+ filter: [
+ {
+ column: "Name",
+ operator: "=",
+ value: "test-skill",
+ type: "string",
+ },
+ ],
+ },
+ },
+ },
+ });
+ }
+ const skillId = v4();
+ const event: Extract<
+ EntityChangeEventType,
+ { entityType: "skill-version" }
+ > = {
+ entityType: "skill-version",
+ projectId,
+ skillId,
+ action: "created",
+ skill: {
+ id: skillId,
+ projectId,
+ name: "test-skill",
+ description: "Test skill",
+ frontmatter: {},
+ version: 2,
+ tags: [],
+ labels: ["latest"],
+ commitMessage: null,
+ files: [],
+ createdBy: "test-user",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ },
+ };
+ const hydrated = EntityChangeEventSchema.parse(
+ JSON.parse(JSON.stringify(event)),
+ );
+ if (hydrated.entityType !== "skill-version")
+ throw new Error("Unexpected event type");
+ expect(hydrated.skill.createdAt).toBeInstanceOf(Date);
+ await skillVersionProcessor(hydrated);
+ const executions = await prisma.automationExecution.findMany({
+ where: { projectId },
+ });
+ expect(executions).toHaveLength(1);
+ expect(executions[0]).toMatchObject({
+ automationId,
+ sourceId: skillId,
+ status: ActionExecutionStatus.PENDING,
+ input: { type: "skill-version", skillVersion: 2 },
+ });
+ await skillVersionProcessor({
+ ...event,
+ skill: { ...event.skill, name: "different-skill" },
+ });
+ expect(
+ await prisma.automationExecution.count({ where: { projectId } }),
+ ).toBe(1);
+ await expect(
+ skillVersionProcessor({ ...event, projectId: v4() }),
+ ).rejects.toThrow("identity does not match");
+ });
});
diff --git a/worker/src/__tests__/slack-message-builder.test.ts b/worker/src/__tests__/slack-message-builder.test.ts
index 229c3a38dc..eb2855e660 100644
--- a/worker/src/__tests__/slack-message-builder.test.ts
+++ b/worker/src/__tests__/slack-message-builder.test.ts
@@ -38,6 +38,36 @@ describe("SlackMessageBuilder", () => {
},
};
+ it("renders skill version notifications with a version-specific skill link", () => {
+ const payload: WebhookInput["payload"] = {
+ type: "skill-version",
+ action: "created",
+ skill: {
+ id: "skill-id",
+ projectId: "project-456",
+ name: "test-skill",
+ version: 2,
+ description: "Test skill",
+ frontmatter: {},
+ tags: [],
+ labels: ["latest"],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ createdBy: "test-user",
+ commitMessage: null,
+ files: [],
+ },
+ };
+ const message = SlackMessageBuilder.buildMessage(payload);
+ expect(message.blocks[2]).toMatchObject({
+ text: {
+ text: expect.stringContaining(
+ "/project/project-456/skills/test-skill?version=2",
+ ),
+ },
+ });
+ });
+
describe("buildPromptVersionMessage", () => {
it("should build complete prompt-version message with all fields", () => {
const blocks =
diff --git a/worker/src/__tests__/webhooks.test.ts b/worker/src/__tests__/webhooks.test.ts
index 880c518765..124d6d92c2 100644
--- a/worker/src/__tests__/webhooks.test.ts
+++ b/worker/src/__tests__/webhooks.test.ts
@@ -297,6 +297,122 @@ describe("Webhook Integration Tests", () => {
webhookServer.teardown();
});
+ describe("skill version delivery", () => {
+ it.each([
+ { github: false, oversized: false },
+ { github: true, oversized: true },
+ ])(
+ "serializes skill metadata (github=$github, oversized=$oversized)",
+ async ({ github, oversized }) => {
+ if (github) {
+ await prisma.action.update({
+ where: { id: actionId, projectId },
+ data: {
+ type: "GITHUB_DISPATCH",
+ config: {
+ type: "GITHUB_DISPATCH",
+ url: "https://webhook.example.com/dispatches",
+ eventType: "skill-update",
+ githubToken: encrypt("github-test-token"),
+ displayGitHubToken: "github-...",
+ },
+ },
+ });
+ }
+ const skillId = v4();
+ const webhookInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ type: "skill-version",
+ action: "created",
+ skill: {
+ id: skillId,
+ projectId,
+ name: "test-skill",
+ description: "Test skill",
+ version: 2,
+ frontmatter: oversized ? { detail: "x".repeat(70_000) } : {},
+ tags: [],
+ labels: ["latest"],
+ commitMessage: null,
+ createdBy: "test-user",
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ updatedAt: new Date("2026-01-01T00:00:00Z"),
+ files: [
+ {
+ id: "file-id",
+ blobId: "blob-id",
+ path: "SKILL.md",
+ sha256Hash: "file-hash",
+ contentType: "text/markdown",
+ contentLength: 42,
+ },
+ ],
+ },
+ user: {
+ id: "internal-user",
+ name: "Test user",
+ email: "[email protected]",
+ },
+ },
+ };
+ Object.assign(webhookInput.payload.skill.files[0], {
+ content: "must not be exported",
+ });
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ triggerId,
+ actionId,
+ automationId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: skillId,
+ input: {},
+ },
+ });
+ await executeWebhook(webhookInput, { skipValidation: true });
+ const requests = webhookServer.getReceivedRequests();
+ expect(requests).toHaveLength(1);
+ const request = requests[0];
+ const parsed = JSON.parse(request.body);
+ const payload = github ? parsed.client_payload : parsed;
+ expect(payload).toMatchObject({
+ id: executionId,
+ type: "skill-version",
+ action: "created",
+ apiVersion: "v1",
+ skill: { id: skillId, projectId, name: "test-skill", version: 2 },
+ });
+ expect(payload).not.toHaveProperty("prompt");
+ expect(payload.user?.id).toBeUndefined();
+ if (github) {
+ expect(parsed.event_type).toBe("skill-update");
+ expect(Buffer.byteLength(request.body, "utf8")).toBeLessThan(
+ 64 * 1024,
+ );
+ }
+ if (oversized) {
+ expect(payload.truncation.payloadTruncated).toBe(true);
+ expect(payload.skill.files).toBeUndefined();
+ } else {
+ expect(payload.skill.createdAt).toBe("2026-01-01T00:00:00.000Z");
+ expect(payload.skill.files).toMatchObject([
+ { path: "SKILL.md", sha256Hash: "file-hash", contentLength: 42 },
+ ]);
+ expect(payload.skill.files[0].content).toBeUndefined();
+ }
+ expect(
+ await prisma.automationExecution.findUnique({
+ where: { id: executionId },
+ }),
+ ).toMatchObject({ status: ActionExecutionStatus.COMPLETED });
+ },
+ );
+ });
+
describe("executeWebhook function", () => {
it("should execute webhook successfully with signature", async () => {
// Get the full prompt for the payload
@@ -2586,50 +2702,81 @@ describe("Webhook Integration Tests", () => {
);
});
- it("sends prompt changes as change events and completes the execution", async () => {
- const fullPrompt = await prisma.prompt.findUniqueOrThrow({
- where: { id: promptId },
- });
- const input: WebhookInput = {
- projectId,
- automationId,
- executionId,
- payload: {
- prompt: PromptDomainSchema.parse(fullPrompt),
- action: "created",
- type: "prompt-version",
- },
- };
- await prisma.automationExecution.create({
- data: {
- id: executionId,
+ it.each(["prompt", "skill"] as const)(
+ "sends %s changes as change events and completes the execution",
+ async (entity) => {
+ const fullPrompt = await prisma.prompt.findUniqueOrThrow({
+ where: { id: promptId },
+ });
+ const input: WebhookInput = {
projectId,
- triggerId,
automationId,
- actionId,
- status: ActionExecutionStatus.PENDING,
- sourceId: executionId,
- input: {},
- },
- });
+ executionId,
+ payload:
+ entity === "prompt"
+ ? {
+ prompt: PromptDomainSchema.parse(fullPrompt),
+ action: "created",
+ type: "prompt-version",
+ }
+ : {
+ type: "skill-version",
+ action: "created",
+ skill: {
+ id: v4(),
+ projectId,
+ name: "test-skill",
+ version: 1,
+ description: "Test skill",
+ frontmatter: {},
+ files: [],
+ tags: [],
+ labels: ["latest"],
+ commitMessage: null,
+ createdBy: "test-user",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ },
+ },
+ };
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: executionId,
+ input: {},
+ },
+ });
- await executeWebhook(input);
+ await executeWebhook(input);
- const { url, body } = lastPagerDutyRequest();
- expect(url).toBe("https://events.pagerduty.com/v2/change/enqueue");
- expect(body).toMatchObject({
- routing_key: routingKey,
- payload: {
- summary: 'Langfuse prompt "test-prompt" version 1 created',
- custom_details: { prompt_name: "test-prompt", prompt_version: 1 },
- },
- });
- expect(body).not.toHaveProperty("event_action");
- const execution = await prisma.automationExecution.findUniqueOrThrow({
- where: { id: executionId },
- });
- expect(execution.status).toBe(ActionExecutionStatus.COMPLETED);
- });
+ const { url, body } = lastPagerDutyRequest();
+ expect(url).toBe("https://events.pagerduty.com/v2/change/enqueue");
+ expect(body).toMatchObject({
+ routing_key: routingKey,
+ payload: {
+ summary: `Langfuse ${entity} "test-${entity}" version 1 created`,
+ custom_details: {
+ [`${entity}_name`]: `test-${entity}`,
+ [`${entity}_version`]: 1,
+ },
+ },
+ });
+ expect(body).not.toHaveProperty("event_action");
+ expect(body.links[0].href).toContain(
+ `/project/${projectId}/${entity}s/`,
+ );
+ expect(body.links[0].href).toContain("version=1");
+ const execution = await prisma.automationExecution.findUniqueOrThrow({
+ where: { id: executionId },
+ });
+ expect(execution.status).toBe(ActionExecutionStatus.COMPLETED);
+ },
+ );
it("always triggers project notifications keyed by event type and resource", async () => {
await prisma.automationExecution.create({
diff --git a/worker/src/features/entityChange/entityChangeWorker.ts b/worker/src/features/entityChange/entityChangeWorker.ts
index e4de18c0a5..c75445e149 100644
--- a/worker/src/features/entityChange/entityChangeWorker.ts
+++ b/worker/src/features/entityChange/entityChangeWorker.ts
@@ -3,6 +3,7 @@ import {
logger,
type EntityChangeEventType,
} from "@langfuse/shared/src/server";
+import { skillVersionProcessor } from "./skillVersionProcessor";
import { promptVersionProcessor } from "./promptVersionProcessor";
/**
@@ -24,11 +25,17 @@ export const entityChangeWorker = async (
if (span) {
span.setAttribute("entityType", event.entityType);
span.setAttribute("projectId", event.projectId);
- span.setAttribute("promptId", event.promptId);
+ if (event.entityType === "prompt-version") {
+ span.setAttribute("promptId", event.promptId);
+ } else {
+ span.setAttribute("skillId", event.skillId);
+ }
span.setAttribute("action", event.action);
}
switch (event.entityType) {
+ case "skill-version":
+ return await skillVersionProcessor(event);
case "prompt-version":
return await promptVersionProcessor(event);
default:
diff --git a/worker/src/features/entityChange/promptVersionProcessor.ts b/worker/src/features/entityChange/promptVersionProcessor.ts
index 45436697e4..7e0523e856 100644
--- a/worker/src/features/entityChange/promptVersionProcessor.ts
+++ b/worker/src/features/entityChange/promptVersionProcessor.ts
@@ -24,7 +24,7 @@ import { v4 } from "uuid";
* Process prompt change events with in-memory filtering
*/
export const promptVersionProcessor = async (
- event: EntityChangeEventType,
+ event: Extract<EntityChangeEventType, { entityType: "prompt-version" }>,
): Promise<void> => {
try {
if (logger.isLevelEnabled("debug")) {
diff --git a/worker/src/features/entityChange/skillVersionProcessor.ts b/worker/src/features/entityChange/skillVersionProcessor.ts
new file mode 100644
index 0000000000..fdec76eb1e
--- /dev/null
+++ b/worker/src/features/entityChange/skillVersionProcessor.ts
@@ -0,0 +1,116 @@
+import {
+ ActionExecutionStatus,
+ InternalServerError,
+ JobConfigState,
+ TriggerEventSource,
+} from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ type EntityChangeEventType,
+ getAutomations,
+ getTriggerConfigurations,
+ logger,
+ matchesTriggerFilter,
+ QueueJobs,
+ QueueName,
+ WebhookQueue,
+} from "@langfuse/shared/src/server";
+import { randomUUID } from "node:crypto";
+
+type SkillVersionEvent = Extract<
+ EntityChangeEventType,
+ { entityType: "skill-version" }
+>;
+
+async function enqueueSkillAutomationAction(
+ event: SkillVersionEvent,
+ trigger: { id: string; actionIds: string[] },
+): Promise<void> {
+ if (trigger.actionIds.length !== 1) {
+ throw new InternalServerError("Expected one action per skill automation");
+ }
+ const actionId = trigger.actionIds[0];
+ const automations = await getAutomations({
+ projectId: event.projectId,
+ actionId,
+ });
+ if (automations.length !== 1) {
+ throw new InternalServerError("Expected one automation per action");
+ }
+ const automationId = automations[0].id;
+ const executionId = randomUUID();
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId: event.projectId,
+ automationId,
+ triggerId: trigger.id,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: event.skillId,
+ input: {
+ type: "skill-version",
+ skillName: event.skill.name,
+ skillVersion: event.skill.version,
+ skillId: event.skillId,
+ automationId,
+ },
+ },
+ });
+ await WebhookQueue.getInstance()?.add(QueueName.WebhookQueue, {
+ timestamp: new Date(),
+ id: randomUUID(),
+ name: QueueJobs.WebhookJob,
+ payload: {
+ projectId: event.projectId,
+ automationId,
+ executionId,
+ payload: {
+ type: "skill-version",
+ action: event.action,
+ skill: event.skill,
+ ...(event.user ? { user: event.user } : {}),
+ },
+ },
+ });
+}
+
+export async function skillVersionProcessor(
+ event: SkillVersionEvent,
+): Promise<void> {
+ if (
+ event.skill.projectId !== event.projectId ||
+ event.skill.id !== event.skillId
+ ) {
+ throw new InternalServerError(
+ "Skill event identity does not match its envelope",
+ );
+ }
+ const triggers = await getTriggerConfigurations({
+ projectId: event.projectId,
+ eventSource: TriggerEventSource.Skill,
+ status: JobConfigState.ACTIVE,
+ });
+ for (const trigger of triggers) {
+ if (
+ !matchesTriggerFilter(
+ {
+ Name: event.skill.name,
+ Labels: event.skill.labels,
+ Tags: event.skill.tags,
+ action: event.action,
+ },
+ trigger,
+ )
+ )
+ continue;
+ try {
+ await enqueueSkillAutomationAction(event, trigger);
+ } catch (error) {
+ logger.error(
+ `Error processing trigger ${trigger.id} for skill ${event.skillId} in project ${event.projectId}`,
+ error,
+ );
+ }
+ }
+}
diff --git a/worker/src/features/pagerduty/buildPagerDutyEvent.ts b/worker/src/features/pagerduty/buildPagerDutyEvent.ts
index 4289203ad3..09d5f7690d 100644
--- a/worker/src/features/pagerduty/buildPagerDutyEvent.ts
+++ b/worker/src/features/pagerduty/buildPagerDutyEvent.ts
@@ -50,7 +50,8 @@ export function buildPagerDutyEvent(args: {
case "project-notification":
return buildProjectNotificationEvent(args.envelope.event, context);
case "prompt-version":
- return buildPromptChangeEvent(args.envelope, context);
+ case "skill-version":
+ return buildVersionChangeEvent(args.envelope, context);
}
}
@@ -250,12 +251,17 @@ function buildProjectNotificationEvent(
};
}
-/** buildPromptChangeEvent records a prompt version change as a PagerDuty change event, which never pages anyone. */
-function buildPromptChangeEvent(
- envelope: Extract<PagerDutyEnvelope, { type: "prompt-version" }>,
+/** buildVersionChangeEvent records a prompt or skill version change without paging anyone. */
+function buildVersionChangeEvent(
+ envelope: Extract<
+ PagerDutyEnvelope,
+ { type: "prompt-version" | "skill-version" }
+ >,
context: EventContext,
): PagerDutyEvent {
- const { prompt } = envelope;
+ const entity = envelope.type === "prompt-version" ? "prompt" : "skill";
+ const version =
+ envelope.type === "prompt-version" ? envelope.prompt : envelope.skill;
return {
kind: "change",
event: {
@@ -263,28 +269,33 @@ function buildPromptChangeEvent(
links: compactLinks([
{
href: safeUrl(() =>
- buildPromptUrl({
- projectId: context.projectId,
- name: prompt.name,
- version: prompt.version,
- }),
+ envelope.type === "prompt-version"
+ ? buildPromptUrl({
+ projectId: context.projectId,
+ name: version.name,
+ version: version.version,
+ })
+ : new URL(
+ `project/${encodeURIComponent(context.projectId)}/skills/${encodeURIComponent(version.name)}?version=${version.version}`,
+ getProductBaseUrl(),
+ ).toString(),
),
- text: "View prompt in Langfuse",
+ text: `View ${entity} in Langfuse`,
},
]),
payload: {
summary: truncatePagerDutySummary(
- `Langfuse prompt "${prompt.name}" version ${prompt.version} ${envelope.action}`,
+ `Langfuse ${entity} "${version.name}" version ${version.version} ${envelope.action}`,
),
source: source(context.projectName),
timestamp: new Date().toISOString(),
custom_details: {
- prompt_name: prompt.name,
- prompt_version: prompt.version,
+ [`${entity}_name`]: version.name,
+ [`${entity}_version`]: version.version,
action: envelope.action,
- labels: prompt.labels,
- tags: prompt.tags,
- commit_message: prompt.commitMessage,
+ labels: version.labels,
+ tags: version.tags,
+ commit_message: version.commitMessage,
},
},
},
@@ -309,15 +320,23 @@ type PagerDutyEnvelope =
| {
type: "prompt-version";
action: string;
- prompt: {
- name: string;
- version: number;
- labels: string[];
- tags: string[];
- commitMessage: string | null;
- };
+ prompt: VersionChange;
+ }
+ | {
+ type: "skill-version";
+ action: string;
+ skill: VersionChange;
};
+/** VersionChange is the prompt or skill metadata included in a PagerDuty change event. */
+type VersionChange = {
+ name: string;
+ version: number;
+ labels: string[];
+ tags: string[];
+ commitMessage: string | null;
+};
+
/** ProjectNotificationEvent is the subset of a project notification PagerDuty needs. */
type ProjectNotificationEvent = {
eventType: string;
diff --git a/worker/src/features/slack/slackMessageBuilder.ts b/worker/src/features/slack/slackMessageBuilder.ts
index 8388d7deff..a57d8ff319 100644
--- a/worker/src/features/slack/slackMessageBuilder.ts
+++ b/worker/src/features/slack/slackMessageBuilder.ts
@@ -13,6 +13,11 @@ type PromptVersionPayload = Extract<
{ type: "prompt-version" }
>;
+type SkillVersionPayload = Extract<
+ WebhookInputPayload,
+ { type: "skill-version" }
+>;
+
const getProductBaseUrl = () => {
if (!env.NEXTAUTH_URL) return undefined;
@@ -117,6 +122,40 @@ export class SlackMessageBuilder {
return blocks;
}
+ static buildSkillVersionMessage(
+ payload: SkillVersionPayload,
+ ): SlackMessage["blocks"] {
+ const { skill, action } = payload;
+ const baseUrl = getProductBaseUrl();
+ const url = baseUrl
+ ? new URL(
+ `project/${skill.projectId}/skills/${encodeURIComponent(skill.name)}`,
+ baseUrl,
+ )
+ : undefined;
+ url?.searchParams.set("version", String(skill.version));
+ return [
+ {
+ type: "header",
+ text: { type: "plain_text", text: `Skill ${action}` },
+ },
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `*${escapeSlackMrkdwn(skill.name)}* (version ${skill.version}) has been *${action}*`,
+ },
+ },
+ ...(url
+ ? [
+ buildSlackLinkSection([
+ { label: "View Skill", url: url.toString() },
+ ]),
+ ]
+ : []),
+ ];
+ }
+
/**
* Build a simple fallback message for unsupported event types
*/
@@ -174,6 +213,8 @@ export class SlackMessageBuilder {
static buildMessage(payload: WebhookInputPayload): SlackMessage {
try {
switch (payload.type) {
+ case "skill-version":
+ return { blocks: this.buildSkillVersionMessage(payload) };
case "prompt-version":
return { blocks: this.buildPromptVersionMessage(payload) };
default: {
diff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.ts
index e5f318182b..a5fa9e43a6 100644
--- a/worker/src/queues/webhooks.ts
+++ b/worker/src/queues/webhooks.ts
@@ -2,6 +2,7 @@
import {
InternalServerError,
PromptWebhookOutboundSchema,
+ SkillWebhookOutboundSchema,
WebhookDefaultHeaders,
ActionExecutionStatus,
LangfuseNotFoundError,
@@ -128,6 +129,14 @@ function buildWebhookOutboundPayload(input: WebhookInput) {
}
return parsed.data;
}
+ if (input.payload.type === "skill-version") {
+ return SkillWebhookOutboundSchema.parse({
+ id: input.executionId,
+ timestamp: new Date(),
+ apiVersion: "v1",
+ ...input.payload,
+ });
+ }
const promptPayload = input.payload;
const parsed = PromptWebhookOutboundSchema.safeParse({
id: input.executionId,
@@ -688,6 +697,64 @@ async function executeWebhookAction({
});
}
+function buildSkillDispatchPayload(
+ validated: Extract<
+ ReturnType<typeof buildWebhookOutboundPayload>,
+ { type: "skill-version" }
+ >,
+ eventType: string,
+): string {
+ let githubPayload = JSON.stringify({
+ event_type: eventType,
+ client_payload: validated,
+ });
+ if (
+ Buffer.byteLength(githubPayload, "utf8") >=
+ GITHUB_REPOSITORY_DISPATCH_MAX_PAYLOAD_BYTES
+ ) {
+ githubPayload = JSON.stringify({
+ event_type: eventType,
+ client_payload: {
+ id: validated.id,
+ timestamp: validated.timestamp,
+ type: validated.type,
+ apiVersion: validated.apiVersion,
+ action: validated.action,
+ skill: {
+ id: validated.skill.id,
+ name: validated.skill.name,
+ version: validated.skill.version,
+ projectId: validated.skill.projectId,
+ },
+ truncation: {
+ payloadTruncated: true,
+ truncatedFields: [
+ "skill.files",
+ "skill.frontmatter",
+ "skill.description",
+ "skill.tags",
+ "skill.labels",
+ "skill.commitMessage",
+ "skill.createdBy",
+ "skill.createdAt",
+ "skill.updatedAt",
+ "user",
+ ],
+ },
+ },
+ });
+ }
+ if (
+ Buffer.byteLength(githubPayload, "utf8") >=
+ GITHUB_REPOSITORY_DISPATCH_MAX_PAYLOAD_BYTES
+ ) {
+ throw new InternalServerError(
+ "Skill repository dispatch payload exceeds GitHub's size limit",
+ );
+ }
+ return githubPayload;
+}
+
/**
* Execute GitHub Dispatch action with repository dispatch API
*/
@@ -758,6 +825,8 @@ async function executeGitHubDispatchAction({
},
},
});
+ } else if (envelope.type === "skill-version") {
+ githubPayload = buildSkillDispatchPayload(envelope, eventType);
} else {
// monitor-alert: post the envelope as client_payload.
const monitorEnvelope = envelope as Extract<