Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

Feat : Add OSS alerting extension hooks (#1318)

Aman Agarwale308d394fd52
diff --git a/src/client/src/__tests__/features/alert-tools.test.ts b/src/client/src/__tests__/features/alert-tools.test.ts
new file mode 100644
index 00000000..aa24c64b
--- /dev/null
+++ b/src/client/src/__tests__/features/alert-tools.test.ts
@@ -0,0 +1,98 @@
+import {
+ createAlertDestinationTool,
+ createAlertTool,
+ deleteAlertDestinationTool,
+ deleteAlertTool,
+ getAlertDestinationTool,
+ getAlertTool,
+ listAlertDestinationsTool,
+ listAlertsTool,
+ testAlertDestinationTool,
+ testAlertTool,
+ updateAlertDestinationTool,
+ updateAlertTool,
+} from "@/features/alert-tools";
+
+const UNAVAILABLE_ERROR = "Alerting is not available in this edition.";
+
+describe("CE alert Otter tool fallbacks", () => {
+ it("createAlertTool returns an unavailable error and does not throw", async () => {
+ await expect(createAlertTool({ name: "Alert" })).resolves.toEqual({
+ success: false,
+ error: UNAVAILABLE_ERROR,
+ });
+ });
+
+ it("updateAlertTool returns an unavailable error", async () => {
+ await expect(updateAlertTool("alert-1", { name: "Alert" })).resolves.toEqual({
+ success: false,
+ error: UNAVAILABLE_ERROR,
+ });
+ });
+
+ it("deleteAlertTool returns an unavailable error", async () => {
+ await expect(deleteAlertTool("alert-1")).resolves.toEqual({
+ success: false,
+ error: UNAVAILABLE_ERROR,
+ });
+ });
+
+ it("listAlertsTool returns an empty list instead of failing", async () => {
+ await expect(listAlertsTool()).resolves.toEqual({ success: true, alerts: [] });
+ });
+
+ it("getAlertTool returns an unavailable error", async () => {
+ await expect(getAlertTool("alert-1")).resolves.toEqual({
+ success: false,
+ error: UNAVAILABLE_ERROR,
+ });
+ });
+
+ it("testAlertTool returns an unavailable error", async () => {
+ await expect(testAlertTool("alert-1")).resolves.toEqual({
+ success: false,
+ error: UNAVAILABLE_ERROR,
+ });
+ });
+
+ it("createAlertDestinationTool returns an unavailable error", async () => {
+ await expect(
+ createAlertDestinationTool({ name: "Dest", providerType: "slack", config: {} })
+ ).resolves.toEqual({ success: false, error: UNAVAILABLE_ERROR });
+ });
+
+ it("updateAlertDestinationTool returns an unavailable error", async () => {
+ await expect(updateAlertDestinationTool("dest-1", { name: "Dest" })).resolves.toEqual({
+ success: false,
+ error: UNAVAILABLE_ERROR,
+ });
+ });
+
+ it("deleteAlertDestinationTool returns an unavailable error", async () => {
+ await expect(deleteAlertDestinationTool("dest-1")).resolves.toEqual({
+ success: false,
+ error: UNAVAILABLE_ERROR,
+ });
+ });
+
+ it("listAlertDestinationsTool returns an empty list instead of failing", async () => {
+ await expect(listAlertDestinationsTool()).resolves.toEqual({
+ success: true,
+ destinations: [],
+ });
+ });
+
+ it("getAlertDestinationTool returns an unavailable error", async () => {
+ await expect(getAlertDestinationTool("dest-1")).resolves.toEqual({
+ success: false,
+ error: UNAVAILABLE_ERROR,
+ });
+ });
+
+ it("testAlertDestinationTool returns an unavailable error", async () => {
+ await expect(testAlertDestinationTool("dest-1")).resolves.toEqual({
+ success: false,
+ error: UNAVAILABLE_ERROR,
+ });
+ });
+});
diff --git a/src/client/src/__tests__/features/alerts.test.ts b/src/client/src/__tests__/features/alerts.test.ts
new file mode 100644
index 00000000..c0f26565
--- /dev/null
+++ b/src/client/src/__tests__/features/alerts.test.ts
@@ -0,0 +1,16 @@
+import { emitAlertSignal, isAlertingEnabled } from "@/features/alerts";
+
+describe("CE alerting feature fallback", () => {
+ it("reports alerting as disabled in this edition", () => {
+ expect(isAlertingEnabled()).toBe(false);
+ });
+
+ it("emitAlertSignal is a safe no-op that resolves to an empty array", async () => {
+ await expect(
+ emitAlertSignal({
+ triggerType: "access_update",
+ fields: { event: "test" },
+ })
+ ).resolves.toEqual([]);
+ });
+});
diff --git a/src/client/src/__tests__/helpers/client/user.test.ts b/src/client/src/__tests__/helpers/client/user.test.ts
index 1ccc2391..1a6b1d0c 100644
--- a/src/client/src/__tests__/helpers/client/user.test.ts
+++ b/src/client/src/__tests__/helpers/client/user.test.ts
@@ -44,6 +44,6 @@ describe('fetchAndPopulateCurrentUserStore', () => {
await fetchAndPopulateCurrentUserStore();
- expect(signOut).toHaveBeenCalled();
+ expect(signOut).toHaveBeenCalledWith({ callbackUrl: '/login' });
});
});
diff --git a/src/client/src/__tests__/helpers/server/rule-engine.test.ts b/src/client/src/__tests__/helpers/server/rule-engine.test.ts
index b2f5f451..6760cc7b 100644
--- a/src/client/src/__tests__/helpers/server/rule-engine.test.ts
+++ b/src/client/src/__tests__/helpers/server/rule-engine.test.ts
@@ -100,6 +100,33 @@ describe('verifyConditionGroupInput', () => {
).toMatchObject({ success: false });
});
+ it('returns error for an invalid condition operator', () => {
+ expect(
+ verifyConditionGroupInput({
+ condition_operator: 'INVALID',
+ conditions: [{ field: 'cost', operator: 'gt' as any, value: '5' }],
+ })
+ ).toEqual({ success: false, err: 'condition_operator must be AND or OR!' });
+ });
+
+ it('returns success for AND condition operator', () => {
+ expect(
+ verifyConditionGroupInput({
+ condition_operator: 'AND',
+ conditions: [{ field: 'cost', operator: 'gt' as any, value: '5' }],
+ })
+ ).toEqual({ success: true });
+ });
+
+ it('returns success for OR condition operator', () => {
+ expect(
+ verifyConditionGroupInput({
+ condition_operator: 'OR',
+ conditions: [{ field: 'cost', operator: 'gt' as any, value: '5' }],
+ })
+ ).toEqual({ success: true });
+ });
+
it('returns success for a group with one valid condition', () => {
expect(
verifyConditionGroupInput({ conditions: [{ field: 'cost', operator: 'gt' as any, value: '5' }] })
diff --git a/src/client/src/__tests__/lib/platform/evaluation/sync-rule-entities.test.ts b/src/client/src/__tests__/lib/platform/evaluation/sync-rule-entities.test.ts
index 1dd8699e..dbe25973 100644
--- a/src/client/src/__tests__/lib/platform/evaluation/sync-rule-entities.test.ts
+++ b/src/client/src/__tests__/lib/platform/evaluation/sync-rule-entities.test.ts
@@ -461,8 +461,8 @@ describe("syncRuleEntitiesFromConfig", () => {
await syncRuleEntitiesFromConfig();
- expect(mockDeleteRuleEntity).toHaveBeenCalledWith("entity-stale");
- expect(mockDeleteRuleEntity).not.toHaveBeenCalledWith("entity-valid");
+ expect(mockDeleteRuleEntity).toHaveBeenCalledWith("entity-stale", { emitAlert: false });
+ expect(mockDeleteRuleEntity).not.toHaveBeenCalledWith("entity-valid", { emitAlert: false });
});
it("deletes entities whose type is not in config", async () => {
@@ -479,7 +479,7 @@ describe("syncRuleEntitiesFromConfig", () => {
await syncRuleEntitiesFromConfig();
- expect(mockDeleteRuleEntity).toHaveBeenCalledWith("entity-1");
+ expect(mockDeleteRuleEntity).toHaveBeenCalledWith("entity-1", { emitAlert: false });
});
it("adds rule entities that are missing from ClickHouse", async () => {
@@ -495,11 +495,14 @@ describe("syncRuleEntitiesFromConfig", () => {
await syncRuleEntitiesFromConfig();
- expect(mockAddRuleEntity).toHaveBeenCalledWith({
- rule_id: "rule-1",
- entity_type: "evaluation",
- entity_id: "type-1",
- });
+ expect(mockAddRuleEntity).toHaveBeenCalledWith(
+ {
+ rule_id: "rule-1",
+ entity_type: "evaluation",
+ entity_id: "type-1",
+ },
+ { emitAlert: false }
+ );
});
it("does not add rule entities that already exist", async () => {
@@ -576,7 +579,8 @@ describe("syncRuleEntitiesFromConfig", () => {
expect(mockAddRuleEntity).toHaveBeenCalledTimes(1);
expect(mockAddRuleEntity).toHaveBeenCalledWith(
- expect.objectContaining({ rule_id: "rule-valid" })
+ expect.objectContaining({ rule_id: "rule-valid" }),
+ { emitAlert: false }
);
});
@@ -621,16 +625,19 @@ describe("syncRuleEntitiesFromConfig", () => {
await syncRuleEntitiesFromConfig();
- expect(mockDeleteRuleEntity).toHaveBeenCalledWith("e2");
- expect(mockDeleteRuleEntity).not.toHaveBeenCalledWith("e1");
+ expect(mockDeleteRuleEntity).toHaveBeenCalledWith("e2", { emitAlert: false });
+ expect(mockDeleteRuleEntity).not.toHaveBeenCalledWith("e1", { emitAlert: false });
expect(mockAddRuleEntity).toHaveBeenCalledWith(
- expect.objectContaining({ rule_id: "rule-b", entity_id: "type-1" })
+ expect.objectContaining({ rule_id: "rule-b", entity_id: "type-1" }),
+ { emitAlert: false }
);
expect(mockAddRuleEntity).toHaveBeenCalledWith(
- expect.objectContaining({ rule_id: "rule-a", entity_id: "type-2" })
+ expect.objectContaining({ rule_id: "rule-a", entity_id: "type-2" }),
+ { emitAlert: false }
);
expect(mockAddRuleEntity).not.toHaveBeenCalledWith(
- expect.objectContaining({ rule_id: "rule-a", entity_id: "type-1" })
+ expect.objectContaining({ rule_id: "rule-a", entity_id: "type-1" }),
+ { emitAlert: false }
);
});
});
diff --git a/src/client/src/__tests__/lib/platform/rule-engine/evaluate.test.ts b/src/client/src/__tests__/lib/platform/rule-engine/evaluate.test.ts
index afc5842c..2766b768 100644
--- a/src/client/src/__tests__/lib/platform/rule-engine/evaluate.test.ts
+++ b/src/client/src/__tests__/lib/platform/rule-engine/evaluate.test.ts
@@ -71,6 +71,17 @@ describe('evaluateRules', () => {
expect(query).toContain("'prompt'");
});
+ it('does not query for unsupported entity types', async () => {
+ const result = await evaluateRules({
+ fields: { model: 'gpt-4' },
+ entity_type: "prompt' OR 1=1 --" as any,
+ include_entity_data: false,
+ });
+
+ expect(result).toEqual({ matchingRuleIds: [], entities: [] });
+ expect(dataCollector).not.toHaveBeenCalled();
+ });
+
it('passes databaseConfigId to dataCollector', async () => {
await evaluateRules({ fields: { model: 'gpt-4' }, entity_type: 'context', include_entity_data: false }, 'db-42');
expect(dataCollector).toHaveBeenCalledWith(expect.any(Object), 'query', 'db-42');
diff --git a/src/client/src/__tests__/lib/platform/vault/vault.test.ts b/src/client/src/__tests__/lib/platform/vault/vault.test.ts
index 10be4127..74e98f22 100644
--- a/src/client/src/__tests__/lib/platform/vault/vault.test.ts
+++ b/src/client/src/__tests__/lib/platform/vault/vault.test.ts
@@ -47,6 +47,9 @@ jest.mock('@/utils/crypto', () => ({
decryptValue: jest.fn((value: string) => value.replace(/^enc:v1:/, '')),
isEncrypted: jest.fn((value: string) => value.startsWith('enc:v1:')),
}));
+jest.mock('@/lib/platform/alerts/signals', () => ({
+ emitManagementAlertSignalSafe: jest.fn(),
+}));
import { getSecretByName, checkNameValidity, deleteSecret, getSecrets, getSecretById, upsertSecret, getSecretsFromDatabaseId } from '@/lib/platform/vault/index';
import { dataCollector } from '@/lib/platform/common';
diff --git a/src/client/src/__tests__/lib/rbac/routes/api/routes.test.ts b/src/client/src/__tests__/lib/rbac/routes/api/routes.test.ts
new file mode 100644
index 00000000..8979d49a
--- /dev/null
+++ b/src/client/src/__tests__/lib/rbac/routes/api/routes.test.ts
@@ -0,0 +1,32 @@
+import { alertingUnavailable } from "@/lib/rbac/routes/api/alerts/unavailable";
+import * as alertsRoute from "@/lib/rbac/routes/api/alerts/route";
+import * as alertByIdRoute from "@/lib/rbac/routes/api/alerts/[id]/route";
+import * as alertTestRoute from "@/lib/rbac/routes/api/alerts/[id]/test/route";
+import * as alertEventsRoute from "@/lib/rbac/routes/api/alerts/events/route";
+import * as alertSpecRoute from "@/lib/rbac/routes/api/alerts/spec/route";
+import * as alertDestinationsRoute from "@/lib/rbac/routes/api/alert-destinations/route";
+import * as alertDestinationByIdRoute from "@/lib/rbac/routes/api/alert-destinations/[id]/route";
+import * as alertDestinationTestRoute from "@/lib/rbac/routes/api/alert-destinations/[id]/test/route";
+import * as alertProvidersRoute from "@/lib/rbac/routes/api/alert-providers/route";
+
+describe("CE alert route handlers (no entitlement/RBAC available in this edition)", () => {
+ it.each([
+ ["alerts/route.ts GET", alertsRoute.GET],
+ ["alerts/route.ts POST", alertsRoute.POST],
+ ["alerts/[id]/route.ts GET", alertByIdRoute.GET],
+ ["alerts/[id]/route.ts PATCH", alertByIdRoute.PATCH],
+ ["alerts/[id]/route.ts DELETE", alertByIdRoute.DELETE],
+ ["alerts/[id]/test/route.ts POST", alertTestRoute.POST],
+ ["alerts/events/route.ts GET", alertEventsRoute.GET],
+ ["alerts/spec/route.ts GET", alertSpecRoute.GET],
+ ["alert-destinations/route.ts GET", alertDestinationsRoute.GET],
+ ["alert-destinations/route.ts POST", alertDestinationsRoute.POST],
+ ["alert-destinations/[id]/route.ts GET", alertDestinationByIdRoute.GET],
+ ["alert-destinations/[id]/route.ts PATCH", alertDestinationByIdRoute.PATCH],
+ ["alert-destinations/[id]/route.ts DELETE", alertDestinationByIdRoute.DELETE],
+ ["alert-destinations/[id]/test/route.ts POST", alertDestinationTestRoute.POST],
+ ["alert-providers/route.ts GET", alertProvidersRoute.GET],
+ ])("%s is wired to the alertingUnavailable fallback", (_name, handler) => {
+ expect(handler).toBe(alertingUnavailable);
+ });
+});
diff --git a/src/client/src/__tests__/lib/rbac/routes/api/unavailable.test.ts b/src/client/src/__tests__/lib/rbac/routes/api/unavailable.test.ts
new file mode 100644
index 00000000..fbcee9e9
--- /dev/null
+++ b/src/client/src/__tests__/lib/rbac/routes/api/unavailable.test.ts
@@ -0,0 +1,24 @@
+import { alertingUnavailable } from "@/lib/rbac/routes/api/alerts/unavailable";
+
+beforeAll(() => {
+ Object.defineProperty(global, "Response", {
+ value: {
+ json: (body: unknown, init?: ResponseInit) => ({
+ status: init?.status ?? 200,
+ json: jest.fn().mockResolvedValue(body),
+ }),
+ },
+ configurable: true,
+ });
+});
+
+describe("alertingUnavailable", () => {
+ it("returns a 402 upgrade-required response with a CE-safe error message", () => {
+ const response: any = alertingUnavailable();
+
+ expect(response.status).toBe(402);
+ expect(response.json()).resolves.toEqual({
+ error: "Alerting is not available in this edition.",
+ });
+ });
+});
diff --git a/src/client/src/__tests__/middleware/check-auth.test.ts b/src/client/src/__tests__/middleware/check-auth.test.ts
index ab625edf..92e08333 100644
--- a/src/client/src/__tests__/middleware/check-auth.test.ts
+++ b/src/client/src/__tests__/middleware/check-auth.test.ts
@@ -40,6 +40,7 @@ describe('checkAuth', () => {
beforeEach(() => {
jest.clearAllMocks();
+ process.env.CRON_JOB_SECRET = 'secret-token';
middleware = checkAuth(nextHandler as any);
});
diff --git a/src/client/src/app/api/alert-destinations/[id]/route.ts b/src/client/src/app/api/alert-destinations/[id]/route.ts
new file mode 100644
index 00000000..a1c10ced
--- /dev/null
+++ b/src/client/src/app/api/alert-destinations/[id]/route.ts
@@ -0,0 +1 @@
+export { DELETE, GET, PATCH } from "@/lib/rbac/routes/api/alert-destinations/[id]/route";
diff --git a/src/client/src/app/api/alert-destinations/[id]/test/route.ts b/src/client/src/app/api/alert-destinations/[id]/test/route.ts
new file mode 100644
index 00000000..e1d5a31d
--- /dev/null
+++ b/src/client/src/app/api/alert-destinations/[id]/test/route.ts
@@ -0,0 +1 @@
+export { POST } from "@/lib/rbac/routes/api/alert-destinations/[id]/test/route";
diff --git a/src/client/src/app/api/alert-destinations/route.ts b/src/client/src/app/api/alert-destinations/route.ts
new file mode 100644
index 00000000..0cc80112
--- /dev/null
+++ b/src/client/src/app/api/alert-destinations/route.ts
@@ -0,0 +1 @@
+export { GET, POST } from "@/lib/rbac/routes/api/alert-destinations/route";
diff --git a/src/client/src/app/api/alert-providers/route.ts b/src/client/src/app/api/alert-providers/route.ts
new file mode 100644
index 00000000..e8f307da
--- /dev/null
+++ b/src/client/src/app/api/alert-providers/route.ts
@@ -0,0 +1 @@
+export { GET } from "@/lib/rbac/routes/api/alert-providers/route";
diff --git a/src/client/src/app/api/alerts/[id]/route.ts b/src/client/src/app/api/alerts/[id]/route.ts
new file mode 100644
index 00000000..005e8a27
--- /dev/null
+++ b/src/client/src/app/api/alerts/[id]/route.ts
@@ -0,0 +1 @@
+export { DELETE, GET, PATCH } from "@/lib/rbac/routes/api/alerts/[id]/route";
diff --git a/src/client/src/app/api/alerts/[id]/test/route.ts b/src/client/src/app/api/alerts/[id]/test/route.ts
new file mode 100644
index 00000000..6e2e175a
--- /dev/null
+++ b/src/client/src/app/api/alerts/[id]/test/route.ts
@@ -0,0 +1 @@
+export { POST } from "@/lib/rbac/routes/api/alerts/[id]/test/route";
diff --git a/src/client/src/app/api/alerts/events/route.ts b/src/client/src/app/api/alerts/events/route.ts
new file mode 100644
index 00000000..3892490d
--- /dev/null
+++ b/src/client/src/app/api/alerts/events/route.ts
@@ -0,0 +1 @@
+export { GET } from "@/lib/rbac/routes/api/alerts/events/route";
diff --git a/src/client/src/app/api/alerts/route.ts b/src/client/src/app/api/alerts/route.ts
new file mode 100644
index 00000000..8969a56b
--- /dev/null
+++ b/src/client/src/app/api/alerts/route.ts
@@ -0,0 +1 @@
+export { GET, POST } from "@/lib/rbac/routes/api/alerts/route";
diff --git a/src/client/src/app/api/alerts/spec/route.ts b/src/client/src/app/api/alerts/spec/route.ts
new file mode 100644
index 00000000..a11b8839
--- /dev/null
+++ b/src/client/src/app/api/alerts/spec/route.ts
@@ -0,0 +1 @@
+export { GET } from "@/lib/rbac/routes/api/alerts/spec/route";
diff --git a/src/client/src/components/(playground)/rule-engine/condition-builder.tsx b/src/client/src/components/(playground)/rule-engine/condition-builder.tsx
index d84384ea..4f5eec20 100644
--- a/src/client/src/components/(playground)/rule-engine/condition-builder.tsx
+++ b/src/client/src/components/(playground)/rule-engine/condition-builder.tsx
@@ -35,15 +35,15 @@ import getMessage from "@/constants/messages";
export const CONDITION_FIELDS = () => {
const m = getMessage();
return [
- { value: "ServiceName", label: m.RULE_FIELD_SERVICE_NAME, dataType: "string", description: m.RULE_FIELD_SERVICE_NAME_DESC },
- { value: "SpanName", label: m.RULE_FIELD_SPAN_NAME, dataType: "string", description: m.RULE_FIELD_SPAN_NAME_DESC },
- { value: "SpanKind", label: m.RULE_FIELD_SPAN_KIND, dataType: "string", description: m.RULE_FIELD_SPAN_KIND_DESC },
+ { value: "ServiceName", label: m.RULE_FIELD_SERVICE_NAME, dataType: "string", description: m.RULE_FIELD_SERVICE_NAME_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "SpanName", label: m.RULE_FIELD_SPAN_NAME, dataType: "string", description: m.RULE_FIELD_SPAN_NAME_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "SpanKind", label: m.RULE_FIELD_SPAN_KIND, dataType: "string", description: m.RULE_FIELD_SPAN_KIND_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
{ value: "Duration", label: m.RULE_FIELD_DURATION, dataType: "number", description: m.RULE_FIELD_DURATION_DESC },
- { value: "StatusCode", label: m.RULE_FIELD_STATUS_CODE, dataType: "string", description: m.RULE_FIELD_STATUS_CODE_DESC },
- { value: "deployment.environment", label: m.RULE_FIELD_DEPLOYMENT_ENV, dataType: "string", description: m.RULE_FIELD_DEPLOYMENT_ENV_DESC },
- { value: "service.name", label: m.RULE_FIELD_SERVICE_NAME_OTEL, dataType: "string", description: m.RULE_FIELD_SERVICE_NAME_OTEL_DESC },
- { value: "gen_ai.system", label: m.RULE_FIELD_GEN_AI_SYSTEM, dataType: "string", description: m.RULE_FIELD_GEN_AI_SYSTEM_DESC },
- { value: "gen_ai.request.model", label: m.RULE_FIELD_MODEL, dataType: "string", description: m.RULE_FIELD_MODEL_DESC },
+ { value: "StatusCode", label: m.RULE_FIELD_STATUS_CODE, dataType: "string", description: m.RULE_FIELD_STATUS_CODE_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "deployment.environment", label: m.RULE_FIELD_DEPLOYMENT_ENV, dataType: "string", description: m.RULE_FIELD_DEPLOYMENT_ENV_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "service.name", label: m.RULE_FIELD_SERVICE_NAME_OTEL, dataType: "string", description: m.RULE_FIELD_SERVICE_NAME_OTEL_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "gen_ai.system", label: m.RULE_FIELD_GEN_AI_SYSTEM, dataType: "string", description: m.RULE_FIELD_GEN_AI_SYSTEM_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
+ { value: "gen_ai.request.model", label: m.RULE_FIELD_MODEL, dataType: "string", description: m.RULE_FIELD_MODEL_DESC, valueSource: "/api/rule-engine/field-values", allowCustomValue: true },
{ value: "gen_ai.usage.input_tokens", label: m.RULE_FIELD_INPUT_TOKENS, dataType: "number", description: m.RULE_FIELD_INPUT_TOKENS_DESC },
{ value: "gen_ai.usage.output_tokens", label: m.RULE_FIELD_OUTPUT_TOKENS, dataType: "number", description: m.RULE_FIELD_OUTPUT_TOKENS_DESC },
{ value: "gen_ai.usage.total_cost", label: m.RULE_FIELD_TOTAL_COST, dataType: "number", description: m.RULE_FIELD_TOTAL_COST_DESC },
@@ -51,11 +51,15 @@ export const CONDITION_FIELDS = () => {
];
};
-// Fields that support dynamic value lookup from otel_traces
-const FIELDS_WITH_VALUES = new Set([
- "ServiceName", "SpanName", "SpanKind", "StatusCode",
- "deployment.environment", "service.name", "gen_ai.system", "gen_ai.request.model",
-]);
+export type ConditionFieldDefinition = {
+ value: string;
+ label: string;
+ dataType: string;
+ description?: string;
+ valueSource?: string;
+ valueOptions?: string[];
+ allowCustomValue?: boolean;
+};
const STRING_OPERATORS = [
{ value: "equals", label: "=" },
@@ -83,8 +87,22 @@ function getOperatorsForDataType(dataType: string) {
return dataType === "number" ? NUMBER_OPERATORS : STRING_OPERATORS;
}
-function getDataTypeForField(fieldValue: string): string {
- return CONDITION_FIELDS().find((f) => f.value === fieldValue)?.dataType || "string";
+function getDataTypeForField(fieldValue: string, fields: ConditionFieldDefinition[]): string {
+ return fields.find((f) => f.value === fieldValue)?.dataType || "string";
+}
+
+function buildFieldValuesUrl(field: ConditionFieldDefinition) {
+ if (!field.valueSource) return "";
+ const separator = field.valueSource.includes("?") ? "&" : "?";
+ return `${field.valueSource}${separator}field=${encodeURIComponent(field.value)}`;
+}
+
+function parseMultiValue(value: string) {
+ return value.split(",").map((item) => item.trim()).filter(Boolean);
+}
+
+function serialiseMultiValue(values: string[]) {
+ return Array.from(new Set(values.map((item) => item.trim()).filter(Boolean))).join(",");
}
export type ConditionGroupState = {
@@ -113,45 +131,70 @@ function FieldInfo({ text }: { text: string }) {
// Combobox for string field values with dynamic loading and custom entry
function ConditionValueInput({
- field,
+ fieldDefinition,
+ operator,
value,
onChange,
}: {
- field: string;
+ fieldDefinition?: ConditionFieldDefinition;
+ operator: string;
value: string;
onChange: (v: string) => void;
}) {
const messages = getMessage();
const [open, setOpen] = useState(false);
- const [inputValue, setInputValue] = useState(value);
+ const [inputValue, setInputValue] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
const fieldValuesCache = useRootStore((s) => s.ruleEngine?.fieldValuesCache ?? {});
const fieldValuesLoading = useRootStore((s) => s.ruleEngine?.fieldValuesLoading ?? {});
+ const fieldLabelsCache = useRootStore((s) => s.ruleEngine?.fieldLabelsCache ?? {});
const setFieldValues = useRootStore((s) => s.ruleEngine?.setFieldValues ?? (() => {}));
const setFieldValuesLoading = useRootStore((s) => s.ruleEngine?.setFieldValuesLoading ?? (() => {}));
-
- const cached = fieldValuesCache[field] ?? null;
- const isLoading = fieldValuesLoading[field] ?? false;
+ const setFieldLabels = useRootStore((s) => s.ruleEngine?.setFieldLabels ?? (() => {}));
+
+ const field = fieldDefinition?.value || "";
+ const valueSourceUrl = fieldDefinition ? buildFieldValuesUrl(fieldDefinition) : "";
+ const staticOptions = fieldDefinition?.valueOptions;
+ const staticOptionValues = staticOptions || [];
+ const staticOptionsKey = staticOptionValues.join("|");
+ const cacheKey = valueSourceUrl || (staticOptionValues.length ? `static:${field}:${staticOptionsKey}` : "");
+ const cached = cacheKey ? fieldValuesCache[cacheKey] ?? null : null;
+ const labels = cacheKey ? fieldLabelsCache[cacheKey] ?? null : null;
+ const isLoading = cacheKey ? fieldValuesLoading[cacheKey] ?? false : false;
+ const isMultiValue = operator === "in" || operator === "not_in";
+ const selectedValues = isMultiValue ? parseMultiValue(value) : [];
+ const hasSuggestions = Boolean(fieldDefinition && fieldDefinition.dataType === "string" && (valueSourceUrl || staticOptionValues.length));
+ const allowCustomValue = fieldDefinition?.allowCustomValue !== false;
// Keep input in sync when value changes from outside (e.g. field change resets value)
useEffect(() => {
- setInputValue(value);
- }, [value]);
+ setInputValue(isMultiValue ? "" : (labels?.[value] ?? value));
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [value, isMultiValue, labels]);
// Load values from API when a supported field is selected and not yet cached
useEffect(() => {
- if (!field || !FIELDS_WITH_VALUES.has(field) || cached !== null) return;
- setFieldValuesLoading(field, true);
- fetch(`/api/rule-engine/field-values?field=${encodeURIComponent(field)}`)
+ if (!cacheKey || cached !== null) return;
+ if (!valueSourceUrl) {
+ setFieldValues(cacheKey, staticOptionValues);
+ return;
+ }
+ setFieldValuesLoading(cacheKey, true);
+ fetch(valueSourceUrl)
.then((r) => r.json())
- .then((d) => setFieldValues(field, d.values ?? []))
- .catch(() => setFieldValues(field, []))
- .finally(() => setFieldValuesLoading(field, false));
- }, [field]);
+ .then((d) => {
+ setFieldValues(cacheKey, d.values ?? []);
+ if (d.labels && typeof d.labels === "object" && !Array.isArray(d.labels)) {
+ setFieldLabels(cacheKey, d.labels as Record<string, string>);
+ }
+ })
+ .catch(() => setFieldValues(cacheKey, []))
+ .finally(() => setFieldValuesLoading(cacheKey, false));
+ }, [cacheKey, cached, setFieldValues, setFieldLabels, setFieldValuesLoading, staticOptionsKey, valueSourceUrl]);
// For number fields or fields without value lookup, plain input
- if (!FIELDS_WITH_VALUES.has(field)) {
+ if (!hasSuggestions) {
return (
<Input
className="h-7 flex-1 text-xs border-stone-200 dark:border-stone-700 min-w-0 bg-stone-50 dark:bg-stone-800/50"
@@ -162,17 +205,28 @@ function ConditionValueInput({
);
}
- const suggestions = (cached ?? []).filter((v) =>
- v.toLowerCase().includes(inputValue.toLowerCase())
- );
- const showCustomEntry = inputValue.trim() && !suggestions.includes(inputValue.trim());
+ const suggestions = (cached ?? []).filter((v) => {
+ const display = labels?.[v] ?? v;
+ return (display.toLowerCase().includes(inputValue.toLowerCase()) || v.toLowerCase().includes(inputValue.toLowerCase()))
+ && (!isMultiValue || !selectedValues.includes(v));
+ });
+ const showCustomEntry = allowCustomValue && inputValue.trim() && !suggestions.includes(inputValue.trim()) && (!isMultiValue || !selectedValues.includes(inputValue.trim()));
const handleSelect = (v: string) => {
+ if (isMultiValue) {
+ onChange(serialiseMultiValue([...selectedValues, v]));
+ setInputValue("");
+ return;
+ }
onChange(v);
- setInputValue(v);
+ setInputValue(labels?.[v] ?? v);
setOpen(false);
};
+ const handleRemoveSelected = (v: string) => {
+ onChange(serialiseMultiValue(selectedValues.filter((item) => item !== v)));
+ };
+
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
e.preventDefault();
@@ -186,15 +240,35 @@ function ConditionValueInput({
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<div
- className="h-7 flex-1 flex items-center min-w-0 border border-stone-200 dark:border-stone-700 rounded-md bg-stone-50 dark:bg-stone-800/50 px-2 cursor-text"
+ className="min-h-7 flex-1 flex items-center min-w-0 border border-stone-200 dark:border-stone-700 rounded-md bg-stone-50 dark:bg-stone-800/50 px-2 py-1 cursor-text"
onClick={() => { setOpen(true); setTimeout(() => inputRef.current?.focus(), 50); }}
>
- <span className="text-xs truncate flex-1">
- {value
- ? <span className="text-stone-700 dark:text-stone-300">{value}</span>
- : <span className="text-stone-400 dark:text-stone-500">{messages.RULE_VALUE_PLACEHOLDER}</span>
- }
- </span>
+ {isMultiValue && selectedValues.length > 0 ? (
+ <div className="flex flex-1 flex-wrap gap-1">
+ {selectedValues.map((item) => (
+ <Badge key={item} variant="secondary" className="h-5 max-w-[140px] gap-1 px-1.5 text-[10px]">
+ <span className="truncate">{labels?.[item] ?? item}</span>
+ <button
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ handleRemoveSelected(item);
+ }}
+ className="text-stone-400 hover:text-red-500 dark:hover:text-red-400"
+ >
+ <XIcon className="h-3 w-3" />
+ </button>
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ <span className="text-xs truncate flex-1">
+ {value
+ ? <span className="text-stone-700 dark:text-stone-300">{labels?.[value] ?? value}</span>
+ : <span className="text-stone-400 dark:text-stone-500">{messages.RULE_VALUE_PLACEHOLDER}</span>
+ }
+ </span>
+ )}
</div>
</PopoverTrigger>
<PopoverContent className="p-0 w-56" align="start" side="bottom">
@@ -203,7 +277,10 @@ function ConditionValueInput({
ref={inputRef}
placeholder={messages.RULE_FIELD_VALUES_SEARCH}
value={inputValue}
- onValueChange={(v) => { setInputValue(v); onChange(v); }}
+ onValueChange={(v) => {
+ setInputValue(v);
+ if (!isMultiValue && !labels) onChange(v);
+ }}
onKeyDown={handleKeyDown}
className="h-8 text-xs"
/>
@@ -246,7 +323,7 @@ function ConditionValueInput({
className="text-xs"
>
<CheckIcon className={`w-3 h-3 mr-1.5 flex-shrink-0 ${value === v ? "opacity-100 text-stone-700 dark:text-stone-200" : "opacity-0"}`} />
- <span className="truncate">{v}</span>
+ <span className="truncate">{labels?.[v] ?? v}</span>
</CommandItem>
))}
</CommandGroup>
@@ -264,13 +341,15 @@ export default function ConditionBuilder({
groups,
onChange,
groupOperator = "AND",
+ extraFields = [],
}: {
groups: ConditionGroupState[];
onChange: (groups: ConditionGroupState[]) => void;
groupOperator?: "AND" | "OR";
+ extraFields?: ConditionFieldDefinition[];
}) {
const messages = getMessage();
- const fields = CONDITION_FIELDS();
+ const fields = [...CONDITION_FIELDS(), ...extraFields];
const addGroup = () => {
onChange([
@@ -315,7 +394,7 @@ export default function ConditionBuilder({
const updateConditionField = (groupIdx: number, condIdx: number, fieldValue: string) => {
const updated = [...groups];
- const dataType = getDataTypeForField(fieldValue);
+ const dataType = getDataTypeForField(fieldValue, fields);
updated[groupIdx] = {
...updated[groupIdx],
conditions: updated[groupIdx].conditions.map((c, i) =>
@@ -471,7 +550,8 @@ export default function ConditionBuilder({
</Select>
<ConditionValueInput
- field={cond.field}
+ fieldDefinition={fields.find((f) => f.value === cond.field)}
+ operator={cond.operator}
value={cond.value}
onChange={(v) => updateConditionValue(groupIdx, condIdx, v)}
/>
diff --git a/src/client/src/components/(playground)/sidebar/user-actions.tsx b/src/client/src/components/(playground)/sidebar/user-actions.tsx
index d88b98bd..f111ee09 100644
--- a/src/client/src/components/(playground)/sidebar/user-actions.tsx
+++ b/src/client/src/components/(playground)/sidebar/user-actions.tsx
@@ -21,8 +21,8 @@ export default function UserActions() {
const resetUserFn = useRootStore(resetUser);
const onClickSignout = () => {
posthog?.reset();
- signOut();
resetUserFn();
+ signOut({ callbackUrl: "/login" });
};
useEffect(() => {
diff --git a/src/client/src/components/common/app-init.tsx b/src/client/src/components/common/app-init.tsx
index 64fdaa0a..a0392f3b 100644
--- a/src/client/src/components/common/app-init.tsx
+++ b/src/client/src/components/common/app-init.tsx
@@ -7,6 +7,7 @@ import {
fetchOrganisationList,
fetchPendingInvitations,
} from "@/helpers/client/organisation";
+import { fetchProjectList } from "@/helpers/client/project";
import { getIsUserFetched } from "@/selectors/user";
import {
getCurrentOrganisation,
@@ -35,6 +36,7 @@ export default function AppInit() {
useEffect(() => {
if (currentOrg?.id) {
onOrganisationChanged(currentOrg.id);
+ fetchProjectList(currentOrg.id);
}
}, [currentOrg?.id]);
diff --git a/src/client/src/features/alert-tools.ts b/src/client/src/features/alert-tools.ts
new file mode 100644
index 00000000..33af21c9
--- /dev/null
+++ b/src/client/src/features/alert-tools.ts
@@ -0,0 +1,47 @@
+export async function createAlertTool(_input: unknown) {
+ return { success: false, error: "Alerting is not available in this edition." };
+}
+
+export async function updateAlertTool(_id: string, _input: unknown) {
+ return { success: false, error: "Alerting is not available in this edition." };
+}
+
+export async function deleteAlertTool(_id: string) {
+ return { success: false, error: "Alerting is not available in this edition." };
+}
+
+export async function listAlertsTool() {
+ return { success: true, alerts: [] };
+}
+
+export async function getAlertTool(_id: string) {
+ return { success: false, error: "Alerting is not available in this edition." };
+}
+
+export async function createAlertDestinationTool(_input: unknown) {
+ return { success: false, error: "Alerting is not available in this edition." };
+}
+
+export async function updateAlertDestinationTool(_id: string, _input: unknown) {
+ return { success: false, error: "Alerting is not available in this edition." };
+}
+
+export async function deleteAlertDestinationTool(_id: string) {
+ return { success: false, error: "Alerting is not available in this edition." };
+}
+
+export async function listAlertDestinationsTool() {
+ return { success: true, destinations: [] };
+}
+
+export async function getAlertDestinationTool(_id: string) {
+ return { success: false, error: "Alerting is not available in this edition." };
+}
+
+export async function testAlertTool(_id: string) {
+ return { success: false, error: "Alerting is not available in this edition." };
+}
+
+export async function testAlertDestinationTool(_id: string) {
+ return { success: false, error: "Alerting is not available in this edition." };
+}
diff --git a/src/client/src/features/alerts.ts b/src/client/src/features/alerts.ts
new file mode 100644
index 00000000..d32a1616
--- /dev/null
+++ b/src/client/src/features/alerts.ts
@@ -0,0 +1,9 @@
+import type { AlertSignalInput } from "@/types/alerts";
+
+export async function emitAlertSignal(_input: AlertSignalInput) {
+ return [];
+}
+
+export function isAlertingEnabled() {
+ return false;
+}
diff --git a/src/client/src/helpers/client/user.ts b/src/client/src/helpers/client/user.ts
index 01e46f72..eed3c84b 100644
--- a/src/client/src/helpers/client/user.ts
+++ b/src/client/src/helpers/client/user.ts
@@ -12,7 +12,8 @@ export const fetchAndPopulateCurrentUserStore = async () => {
);
if (err) {
- signOut();
+ signOut({ callbackUrl: "/login" });
+ return;
}
useRootStore.getState().user.set(user);
diff --git a/src/client/src/helpers/server/rule-engine.ts b/src/client/src/helpers/server/rule-engine.ts
index 4144424e..575eae21 100644
--- a/src/client/src/helpers/server/rule-engine.ts
+++ b/src/client/src/helpers/server/rule-engine.ts
@@ -6,6 +6,7 @@ const VALID_ENTITY_TYPES: RuleEntityType[] = [
// "dataset",
// "meta_config",
"evaluation",
+ "alert",
];
const VALID_OPERATORS = [
"equals", "not_equals", "contains", "not_contains",
@@ -41,7 +42,10 @@ export function verifyConditionInput(input: Partial<RuleConditionInput>) {
return { success: true };
}
-export function verifyConditionGroupInput(input: { conditions?: RuleConditionInput[] }) {
+export function verifyConditionGroupInput(input: { condition_operator?: string; conditions?: RuleConditionInput[] }) {
+ if (input.condition_operator && !VALID_GROUP_OPERATORS.includes(input.condition_operator)) {
+ return { success: false, err: "condition_operator must be AND or OR!" };
+ }
if (!input.conditions || !Array.isArray(input.conditions) || input.conditions.length === 0) {
return { success: false, err: "At least one condition is required in each group!" };
}
diff --git a/src/client/src/lib/platform/alerts/signals.ts b/src/client/src/lib/platform/alerts/signals.ts
new file mode 100644
index 00000000..b13761bb
--- /dev/null
+++ b/src/client/src/lib/platform/alerts/signals.ts
@@ -0,0 +1,54 @@
+import { emitAlertSignal } from "@/features/alerts";
+import { getDBConfigByUser } from "@/lib/db-config";
+import { getCurrentOrganisation, getCurrentProjectForOrganisation } from "@/lib/organisation";
+import type { AlertSignalInput, AlertTriggerType } from "@/types/alerts";
+
+type ManagementAlertInput = {
+ triggerType: AlertTriggerType;
+ event: string;
+ message: string;
+ sourceId?: string | null;
+ fields?: Record<string, string | number | boolean | undefined | null>;
+ payloadSummary?: Record<string, unknown>;
+ databaseConfigId?: string | null;
+};
+
+function cleanFields(fields: ManagementAlertInput["fields"]) {
+ return Object.fromEntries(
+ Object.entries(fields || {}).filter((entry): entry is [string, string | number | boolean] => {
+ const value = entry[1];
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
+ })
+ );
+}
+
+export async function emitManagementAlertSignal(input: ManagementAlertInput) {
+ const organisation = await getCurrentOrganisation().catch(() => null);
+ if (!organisation?.id) return [];
+
+ const project = await getCurrentProjectForOrganisation(organisation.id).catch(() => null);
+ const rawDbConfig = await getDBConfigByUser(true).catch(() => null);
+ const databaseConfig = rawDbConfig && !Array.isArray(rawDbConfig) ? rawDbConfig : null;
+ const fields = {
+ event: input.event,
+ ...cleanFields(input.fields),
+ };
+ const payloadSummary = {
+ message: input.message,
+ ...input.payloadSummary,
+ };
+
+ return emitAlertSignal({
+ triggerType: input.triggerType,
+ organisationId: organisation.id,
+ projectId: project?.id ?? null,
+ databaseConfigId: input.databaseConfigId ?? databaseConfig?.id ?? null,
+ sourceId: input.sourceId ?? null,
+ fields,
+ payloadSummary,
+ } satisfies AlertSignalInput);
+}
+
+export function emitManagementAlertSignalSafe(input: ManagementAlertInput) {
+ emitManagementAlertSignal(input).catch(() => undefined);
+}
diff --git a/src/client/src/lib/platform/chat/schema-context.ts b/src/client/src/lib/platform/chat/schema-context.ts
index 7613185d..ff046dbe 100644
--- a/src/client/src/lib/platform/chat/schema-context.ts
+++ b/src/client/src/lib/platform/chat/schema-context.ts
@@ -2,13 +2,14 @@ export function getChatSystemPrompt(): string {
return `You are an AI assistant for OpenLIT, an OpenTelemetry-native observability platform. You have two capabilities:
1. **Data Queries**: Convert natural language questions into ClickHouse SQL queries to analyze observability data (traces, metrics, costs, tokens, etc.)
-2. **Platform Management**: Create and manage platform resources using the available tools — rules, contexts, prompts, vault secrets, custom models, and trace analysis.
+2. **Platform Management**: Create and manage platform resources using the available tools — rules, alerts, contexts, prompts, vault secrets, custom models, and trace analysis.
When the user asks a question about their data, generate a SQL query. When the user asks to create or manage a resource, use the appropriate tool. If unclear, ask for clarification.
## Available Tools (called automatically when needed)
**Rule Engine** — create_rule, update_rule, delete_rule, list_rules, get_rule, link_entity_to_rule, unlink_entity_from_rule, list_rule_entities
+**Alerts** — create_alert, update_alert, delete_alert, list_alerts, get_alert, create_alert_destination, list_alert_destinations, test_alert
**Context** — create_context, update_context, delete_context, list_contexts
**Prompt Hub** — create_prompt, get_prompt, update_prompt_version, delete_prompt, list_prompts
**Vault** — create_vault_secret, update_vault_secret, delete_vault_secret, list_vault_secrets
@@ -18,6 +19,7 @@ When the user asks a question about their data, generate a SQL query. When the u
Guidelines:
- When the user asks to create something (vault secret, rule, context, prompt, model), do it IMMEDIATELY by calling the tool. Do NOT ask for confirmation first — just create it and report what was created.
- When creating resources, confirm what was created with the key details (name, ID, status).
+- When creating alerts, prefer existing alert destinations when available. If none exist, create an alert destination first when the user provides connector details.
- When listing, summarize the results concisely.
- When a user asks to help improve, review, critique, or suggest edits for an existing prompt, first load it with get_prompt and then respond with suggested improvements. Do not call update_prompt_version unless the user explicitly asks to save, update, apply, publish, or create a new version.
- When the user asks to link a context or prompt to a rule, use link_entity_to_rule.
diff --git a/src/client/src/lib/platform/chat/tools.ts b/src/client/src/lib/platform/chat/tools.ts
index 0966e8c3..d37d05f5 100644
--- a/src/client/src/lib/platform/chat/tools.ts
+++ b/src/client/src/lib/platform/chat/tools.ts
@@ -39,6 +39,20 @@ import {
import { TRACE_ANALYSIS_DIMENSIONS } from "@/types/trace-analysis";
import { dataCollector } from "../common";
import Sanitizer from "@/utils/sanitizer";
+import {
+ createAlertDestinationTool,
+ createAlertTool,
+ deleteAlertDestinationTool,
+ deleteAlertTool,
+ getAlertDestinationTool,
+ getAlertTool,
+ listAlertDestinationsTool,
+ listAlertsTool,
+ testAlertDestinationTool,
+ testAlertTool,
+ updateAlertDestinationTool,
+ updateAlertTool,
+} from "@/features/alert-tools";
type OtterTraceAnalysisScope = "trace" | "span";
@@ -405,6 +419,181 @@ export function getChatTools(userId: string, databaseConfigId: string) {
},
}),
+ // ==================== ALERTS ====================
+
+ create_alert: tool<any, any>({
+ description: "Create an alert with trigger types, optional Rule Engine condition groups, and destination IDs.",
+ inputSchema: jsonSchema({
+ type: "object" as const,
+ properties: {
+ name: { type: "string" },
+ description: { type: "string" },
+ severity: { type: "string", enum: ["low", "medium", "high", "critical"] },
+ status: { type: "string", enum: ["active", "paused"] },
+ triggerTypes: {
+ type: "array",
+ items: {
+ type: "string",
+ enum: [
+ "access_update",
+ "invite",
+ "prompt_version_update",
+ "fleet_hub_config_update",
+ "vault_secret_change",
+ "context_change",
+ "rule_engine_change",
+ ],
+ },
+ },
+ destinationIds: { type: "array", items: { type: "string" } },
+ ruleId: { type: "string" },
+ conditionGroups: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ condition_operator: { type: "string", enum: ["AND", "OR"] },
+ conditions: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ field: { type: "string" },
+ operator: { type: "string" },
+ value: { type: "string" },
+ data_type: { type: "string", enum: ["string", "number", "boolean"] },
+ },
+ required: ["field", "operator", "value"],
+ },
+ },
+ },
+ },
+ },
+ },
+ required: ["name"],
+ }) as any,
+ execute: async (params: any) => createAlertTool(params),
+ }),
+
+ update_alert: tool<any, any>({
+ description: "Update an alert.",
+ inputSchema: jsonSchema({
+ type: "object" as const,
+ properties: {
+ id: { type: "string" },
+ name: { type: "string" },
+ description: { type: "string" },
+ severity: { type: "string", enum: ["low", "medium", "high", "critical"] },
+ status: { type: "string", enum: ["active", "paused"] },
+ triggerTypes: { type: "array", items: { type: "string" } },
+ destinationIds: { type: "array", items: { type: "string" } },
+ },
+ required: ["id"],
+ }) as any,
+ execute: async ({ id, ...params }: any) => updateAlertTool(id, params),
+ }),
+
+ delete_alert: tool<any, any>({
+ description: "Delete an alert.",
+ inputSchema: jsonSchema({
+ type: "object" as const,
+ properties: { id: { type: "string" } },
+ required: ["id"],
+ }) as any,
+ execute: async (params: any) => deleteAlertTool(params.id),
+ }),
+
+ list_alerts: tool<any, any>({
+ description: "List alerts.",
+ inputSchema: jsonSchema({ type: "object" as const, properties: {} }) as any,
+ execute: async () => listAlertsTool(),
+ }),
+
+ get_alert: tool<any, any>({
+ description: "Get an alert by ID.",
+ inputSchema: jsonSchema({
+ type: "object" as const,
+ properties: { id: { type: "string" } },
+ required: ["id"],
+ }) as any,
+ execute: async (params: any) => getAlertTool(params.id),
+ }),
+
+ create_alert_destination: tool<any, any>({
+ description: "Create a reusable alert destination such as Slack, email, webhook, Datadog Event, Microsoft Teams, PagerDuty, Opsgenie, or Discord.",
+ inputSchema: jsonSchema({
+ type: "object" as const,
+ properties: {
+ name: { type: "string" },
+ providerType: { type: "string", enum: ["slack", "email", "webhook", "datadog", "teams", "pagerduty", "opsgenie", "discord"] },
+ config: { type: "object" },
+ },
+ required: ["name", "providerType", "config"],
+ }) as any,
+ execute: async (params: any) => createAlertDestinationTool(params),
+ }),
+
+ update_alert_destination: tool<any, any>({
+ description: "Update an existing alert destination's name, status, or provider config.",
+ inputSchema: jsonSchema({
+ type: "object" as const,
+ properties: {
+ id: { type: "string" },
+ name: { type: "string" },
+ status: { type: "string", enum: ["active", "paused"] },
+ config: { type: "object" },
+ },
+ required: ["id"],
+ }) as any,
+ execute: async ({ id, ...params }: any) => updateAlertDestinationTool(id, params),
+ }),
+
+ delete_alert_destination: tool<any, any>({
+ description: "Delete an alert destination.",
+ inputSchema: jsonSchema({
+ type: "object" as const,
+ properties: { id: { type: "string" } },
+ required: ["id"],
+ }) as any,
+ execute: async (params: any) => deleteAlertDestinationTool(params.id),
+ }),
+
+ list_alert_destinations: tool<any, any>({
+ description: "List alert destinations.",
+ inputSchema: jsonSchema({ type: "object" as const, properties: {} }) as any,
+ execute: async () => listAlertDestinationsTool(),
+ }),
+
+ get_alert_destination: tool<any, any>({
+ description: "Get an alert destination by ID.",
+ inputSchema: jsonSchema({
+ type: "object" as const,
+ properties: { id: { type: "string" } },
+ required: ["id"],
+ }) as any,
+ execute: async (params: any) => getAlertDestinationTool(params.id),
+ }),
+
+ test_alert: tool<any, any>({
+ description: "Send a test notification for an alert.",
+ inputSchema: jsonSchema({
+ type: "object" as const,
+ properties: { id: { type: "string" } },
+ required: ["id"],
+ }) as any,
+ execute: async (params: any) => testAlertTool(params.id),
+ }),
+
+ test_alert_destination: tool<any, any>({
+ description: "Send a test notification directly to an alert destination.",
+ inputSchema: jsonSchema({
+ type: "object" as const,
+ properties: { id: { type: "string" } },
+ required: ["id"],
+ }) as any,
+ execute: async (params: any) => testAlertDestinationTool(params.id),
+ }),
+
// ==================== CONTEXT ====================
create_context: tool<any, any>({
diff --git a/src/client/src/lib/platform/context/index.ts b/src/client/src/lib/platform/context/index.ts
index dcdb1864..2eae7631 100644
--- a/src/client/src/lib/platform/context/index.ts
+++ b/src/client/src/lib/platform/context/index.ts
@@ -6,6 +6,7 @@ import { throwIfError } from "@/utils/error";
import Sanitizer from "@/utils/sanitizer";
import { OPENLIT_CONTEXTS_TABLE_NAME } from "./table-details";
import { dataCollector } from "../common";
+import { emitManagementAlertSignalSafe } from "@/lib/platform/alerts/signals";
export async function getContexts(databaseConfigId?: string) {
const user = await getCurrentUser();
@@ -69,6 +70,23 @@ export async function createContext(contextInputParams: Partial<ContextInput>) {
: (err as string) || getMessage().CONTEXT_NOT_CREATED
);
+ emitManagementAlertSignalSafe({
+ triggerType: "context_change",
+ event: "context_created",
+ message: `Context ${contextInput.name || contextId} was created.`,
+ sourceId: contextId,
+ fields: {
+ context_id: contextId,
+ name: contextInput.name || "",
+ status: contextInput.status || "ACTIVE",
+ },
+ payloadSummary: {
+ contextId,
+ name: contextInput.name,
+ status: contextInput.status || "ACTIVE",
+ },
+ });
+
return { message: getMessage().CONTEXT_CREATED, id: contextId };
}
@@ -106,6 +124,23 @@ export async function updateContext(id: string, contextInputParams: Partial<Cont
: (err as string) || getMessage().CONTEXT_NOT_UPDATED
);
+ emitManagementAlertSignalSafe({
+ triggerType: "context_change",
+ event: "context_updated",
+ message: `Context ${contextInput.name || safeId} was updated.`,
+ sourceId: safeId,
+ fields: {
+ context_id: safeId,
+ name: contextInput.name || "",
+ status: contextInput.status || "",
+ },
+ payloadSummary: {
+ contextId: safeId,
+ name: contextInput.name,
+ status: contextInput.status,
+ },
+ });
+
return { message: getMessage().CONTEXT_UPDATED };
}
@@ -124,5 +159,18 @@ export async function deleteContext(id: string) {
return [getMessage().CONTEXT_NOT_DELETED];
}
+ emitManagementAlertSignalSafe({
+ triggerType: "context_change",
+ event: "context_deleted",
+ message: `Context ${safeId} was deleted.`,
+ sourceId: safeId,
+ fields: {
+ context_id: safeId,
+ },
+ payloadSummary: {
+ contextId: safeId,
+ },
+ });
+
return [undefined, getMessage().CONTEXT_DELETED];
}
diff --git a/src/client/src/lib/platform/evaluation/sync-rule-entities.ts b/src/client/src/lib/platform/evaluation/sync-rule-entities.ts
index 45379d01..f56a69ce 100644
--- a/src/client/src/lib/platform/evaluation/sync-rule-entities.ts
+++ b/src/client/src/lib/platform/evaluation/sync-rule-entities.ts
@@ -94,7 +94,7 @@ export async function syncRuleEntitiesFromConfig() {
for (const e of entities) {
const key = `${e.rule_id}:${e.entity_id}`;
if (!desired.has(key)) {
- await deleteRuleEntity(e.id);
+ await deleteRuleEntity(e.id, { emitAlert: false });
}
}
@@ -110,7 +110,7 @@ export async function syncRuleEntitiesFromConfig() {
rule_id: r.ruleId,
entity_type: "evaluation",
entity_id: t.id,
- })
+ }, { emitAlert: false })
);
if (addErr) {
console.error("Failed to add rule entity:", addErr);
diff --git a/src/client/src/lib/platform/prompt/version.ts b/src/client/src/lib/platform/prompt/version.ts
index fb08ccd9..032340bc 100644
--- a/src/client/src/lib/platform/prompt/version.ts
+++ b/src/client/src/lib/platform/prompt/version.ts
@@ -10,6 +10,7 @@ import { jsonStringify } from "@/utils/json";
import getMessage from "@/constants/messages";
import Sanitizer from "@/utils/sanitizer";
import { throwIfError } from "@/utils/error";
+import { emitManagementAlertSignalSafe } from "@/lib/platform/alerts/signals";
export async function upsertPromptVersion(promptInputParams: PromptUpdate) {
const user = await getCurrentUser();
@@ -74,6 +75,23 @@ export async function upsertPromptVersion(promptInputParams: PromptUpdate) {
: (versionErr as string) || getMessage().VERSION_NOT_SAVED
);
+ emitManagementAlertSignalSafe({
+ triggerType: "prompt_version_update",
+ event: promptInput.versionId ? "prompt_version_updated" : "prompt_version_created",
+ message: `Prompt version ${promptInput.version || ""} was saved.`,
+ sourceId: promptInput.versionId || promptInput.promptId,
+ fields: {
+ prompt_id: promptInput.promptId || "",
+ version: promptInput.version || "",
+ status: promptInput.status || "",
+ },
+ payloadSummary: {
+ promptId: promptInput.promptId,
+ version: promptInput.version,
+ status: promptInput.status,
+ },
+ });
+
return getMessage().VERSION_SAVED;
}
diff --git a/src/client/src/lib/platform/rule-engine/evaluate.ts b/src/client/src/lib/platform/rule-engine/evaluate.ts
index 396c9724..306508fd 100644
--- a/src/client/src/lib/platform/rule-engine/evaluate.ts
+++ b/src/client/src/lib/platform/rule-engine/evaluate.ts
@@ -11,6 +11,8 @@ import { OPENLIT_CONTEXTS_TABLE_NAME } from "../context/table-details";
import { getCompiledPromptByDbConfig } from "../prompt/compiled";
import Sanitizer from "@/utils/sanitizer";
+const VALID_EVALUATE_ENTITY_TYPES = new Set(["context", "prompt", "evaluation", "alert"]);
+
export async function evaluateRules(
{ fields, entity_type, include_entity_data, entity_inputs }: EvaluateInput,
databaseConfigId?: string
@@ -18,6 +20,9 @@ export async function evaluateRules(
if (!fields || Object.keys(fields).length === 0) {
return { matchingRuleIds: [], entities: [] };
}
+ if (!VALID_EVALUATE_ENTITY_TYPES.has(entity_type)) {
+ return { matchingRuleIds: [], entities: [] };
+ }
// Build input_values CTE using UNION ALL — reliable in ClickHouse.
// Use sqlString.escape() so backslashes, single-quotes, null bytes and all
@@ -30,6 +35,8 @@ export async function evaluateRules(
})
.join("\n UNION ALL\n ");
+ const safeEntityType = sqlString.escape(entity_type);
+
const query = `
WITH
input_values AS (
@@ -96,7 +103,7 @@ SELECT
FROM rule_matches rm
INNER JOIN ${OPENLIT_RULE_ENTITIES_TABLE_NAME} re ON re.rule_id = rm.rule_id
WHERE rm.rule_match = 1
- AND re.entity_type = '${entity_type}'
+ AND re.entity_type = ${safeEntityType}
ORDER BY rm.rule_id, re.entity_type;
`;
diff --git a/src/client/src/lib/platform/rule-engine/index.ts b/src/client/src/lib/platform/rule-engine/index.ts
index 15eecfb9..2336ae00 100644
--- a/src/client/src/lib/platform/rule-engine/index.ts
+++ b/src/client/src/lib/platform/rule-engine/index.ts
@@ -19,6 +19,15 @@ import {
OPENLIT_RULES_TABLE_NAME,
} from "./table-details";
import { dataCollector } from "../common";
+import { emitManagementAlertSignalSafe } from "@/lib/platform/alerts/signals";
+
+type RuleMutationOptions = {
+ emitAlert?: boolean;
+};
+
+function shouldEmitAlert(options?: RuleMutationOptions) {
+ return options?.emitAlert !== false;
+}
export async function getRules(databaseConfigId?: string) {
const user = await getCurrentUser();
@@ -79,7 +88,7 @@ export async function getRuleById(id: string, databaseConfigId?: string) {
};
}
-export async function createRule(ruleInputParams: Partial<RuleInput>) {
+export async function createRule(ruleInputParams: Partial<RuleInput>, options?: RuleMutationOptions) {
const user = await getCurrentUser();
throwIfError(!user, getMessage().UNAUTHORIZED_USER);
@@ -103,10 +112,29 @@ export async function createRule(ruleInputParams: Partial<RuleInput>) {
typeof err?.toString === "function" ? err.toString() : (err as string) || getMessage().RULE_NOT_CREATED
);
+ if (shouldEmitAlert(options)) {
+ emitManagementAlertSignalSafe({
+ triggerType: "rule_engine_change",
+ event: "rule_created",
+ message: `Rule ${ruleInput.name || ruleId} was created.`,
+ sourceId: ruleId,
+ fields: {
+ rule_id: ruleId,
+ name: ruleInput.name || "",
+ status: ruleInput.status || "ACTIVE",
+ },
+ payloadSummary: {
+ ruleId,
+ name: ruleInput.name,
+ status: ruleInput.status || "ACTIVE",
+ },
+ });
+ }
+
return { message: getMessage().RULE_CREATED, id: ruleId };
}
-export async function updateRule(id: string, ruleInputParams: Partial<RuleInput>) {
+export async function updateRule(id: string, ruleInputParams: Partial<RuleInput>, options?: RuleMutationOptions) {
const user = await getCurrentUser();
throwIfError(!user, getMessage().UNAUTHORIZED_USER);
@@ -138,10 +166,29 @@ export async function updateRule(id: string, ruleInputParams: Partial<RuleInput>
: (err as string) || getMessage().RULE_NOT_UPDATED
);
+ if (shouldEmitAlert(options)) {
+ emitManagementAlertSignalSafe({
+ triggerType: "rule_engine_change",
+ event: "rule_updated",
+ message: `Rule ${ruleInput.name || safeId} was updated.`,
+ sourceId: safeId,
+ fields: {
+ rule_id: safeId,
+ name: ruleInput.name || "",
+ status: ruleInput.status || "",
+ },
+ payloadSummary: {
+ ruleId: safeId,
+ name: ruleInput.name,
+ status: ruleInput.status,
+ },
+ });
+ }
+
return { message: getMessage().RULE_UPDATED };
}
-export async function deleteRule(id: string) {
+export async function deleteRule(id: string, options?: RuleMutationOptions) {
const user = await getCurrentUser();
throwIfError(!user, getMessage().UNAUTHORIZED_USER);
@@ -171,12 +218,28 @@ export async function deleteRule(id: string) {
return [getMessage().RULE_NOT_DELETED];
}
+ if (shouldEmitAlert(options)) {
+ emitManagementAlertSignalSafe({
+ triggerType: "rule_engine_change",
+ event: "rule_deleted",
+ message: `Rule ${safeId} was deleted.`,
+ sourceId: safeId,
+ fields: {
+ rule_id: safeId,
+ },
+ payloadSummary: {
+ ruleId: safeId,
+ },
+ });
+ }
+
return [undefined, getMessage().RULE_DELETED];
}
export async function addConditionGroupsToRule(
ruleId: string,
- conditionGroups: RuleConditionGroupInput[]
+ conditionGroups: RuleConditionGroupInput[],
+ options?: RuleMutationOptions
) {
const user = await getCurrentUser();
throwIfError(!user, getMessage().UNAUTHORIZED_USER);
@@ -248,10 +311,27 @@ export async function addConditionGroupsToRule(
}
}
+ if (shouldEmitAlert(options)) {
+ emitManagementAlertSignalSafe({
+ triggerType: "rule_engine_change",
+ event: "rule_conditions_updated",
+ message: `Rule conditions for ${safeRuleId} were updated.`,
+ sourceId: safeRuleId,
+ fields: {
+ rule_id: safeRuleId,
+ condition_group_count: conditionGroups.length,
+ },
+ payloadSummary: {
+ ruleId: safeRuleId,
+ conditionGroupCount: conditionGroups.length,
+ },
+ });
+ }
+
return { message: getMessage().RULE_CONDITION_GROUP_ADDED };
}
-export async function addRuleEntity(entityInputParams: Partial<RuleEntityInput>) {
+export async function addRuleEntity(entityInputParams: Partial<RuleEntityInput>, options?: RuleMutationOptions) {
const user = await getCurrentUser();
throwIfError(!user, getMessage().UNAUTHORIZED_USER);
@@ -281,10 +361,29 @@ export async function addRuleEntity(entityInputParams: Partial<RuleEntityInput>)
: (err as string) || getMessage().RULE_ENTITY_NOT_ASSOCIATED
);
+ if (shouldEmitAlert(options)) {
+ emitManagementAlertSignalSafe({
+ triggerType: "rule_engine_change",
+ event: "rule_entity_created",
+ message: `Rule entity ${entityInput.entity_type || "entity"} was associated.`,
+ sourceId: entityInput.rule_id || null,
+ fields: {
+ rule_id: entityInput.rule_id || "",
+ entity_type: entityInput.entity_type || "",
+ entity_id: entityInput.entity_id || "",
+ },
+ payloadSummary: {
+ ruleId: entityInput.rule_id,
+ entityType: entityInput.entity_type,
+ entityId: entityInput.entity_id,
+ },
+ });
+ }
+
return { message: getMessage().RULE_ENTITY_ASSOCIATED };
}
-export async function deleteRuleEntity(id: string) {
+export async function deleteRuleEntity(id: string, options?: RuleMutationOptions) {
const user = await getCurrentUser();
throwIfError(!user, getMessage().UNAUTHORIZED_USER);
@@ -299,6 +398,21 @@ export async function deleteRuleEntity(id: string) {
return [getMessage().RULE_ENTITY_NOT_DELETED];
}
+ if (shouldEmitAlert(options)) {
+ emitManagementAlertSignalSafe({
+ triggerType: "rule_engine_change",
+ event: "rule_entity_deleted",
+ message: `Rule entity ${safeId} was deleted.`,
+ sourceId: safeId,
+ fields: {
+ entity_id: safeId,
+ },
+ payloadSummary: {
+ entityId: safeId,
+ },
+ });
+ }
+
return [undefined, getMessage().RULE_ENTITY_DELETED];
}
diff --git a/src/client/src/lib/platform/vault/index.ts b/src/client/src/lib/platform/vault/index.ts
index f9e52f9f..a2cee43f 100644
--- a/src/client/src/lib/platform/vault/index.ts
+++ b/src/client/src/lib/platform/vault/index.ts
@@ -14,6 +14,7 @@ import { dataCollector } from "../common";
import { jsonStringify } from "@/utils/json";
import { getAPIKeyInfo } from "../api-keys";
import { decryptValue, encryptValue } from "@/utils/crypto";
+import { emitManagementAlertSignalSafe } from "@/lib/platform/alerts/signals";
function escapeClickHouseString(value: string) {
return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
@@ -129,6 +130,21 @@ export async function upsertSecret(secretInputParams: Partial<SecretInput>) {
: (err as string) || getMessage().SECRET_NOT_SAVED
);
+ emitManagementAlertSignalSafe({
+ triggerType: "vault_secret_change",
+ event: "vault_secret_updated",
+ message: `Vault key ${secretInput.key || secretInput.id || ""} was updated.`,
+ sourceId: secretInput.id || null,
+ fields: {
+ secret_id: secretInput.id || "",
+ key: secretInput.key || "",
+ },
+ payloadSummary: {
+ secretId: secretInput.id,
+ key: secretInput.key,
+ },
+ });
+
return getMessage().SECRET_SAVED;
} else {
createdSecretId = randomUUID();
@@ -154,6 +170,21 @@ export async function upsertSecret(secretInputParams: Partial<SecretInput>) {
);
}
+ emitManagementAlertSignalSafe({
+ triggerType: "vault_secret_change",
+ event: "vault_secret_created",
+ message: `Vault key ${secretInput.key || ""} was created.`,
+ sourceId: createdSecretId || null,
+ fields: {
+ secret_id: createdSecretId || "",
+ key: secretInput.key || "",
+ },
+ payloadSummary: {
+ secretId: createdSecretId,
+ key: secretInput.key,
+ },
+ });
+
return {
data: createdSecretId ? { id: createdSecretId } : {},
id: createdSecretId,
@@ -179,6 +210,19 @@ export async function deleteSecret(secretIdParam: string) {
return [getMessage().SECRET_NOT_DELETED];
}
+ emitManagementAlertSignalSafe({
+ triggerType: "vault_secret_change",
+ event: "vault_secret_deleted",
+ message: `Vault key ${secretId} was deleted.`,
+ sourceId: secretId,
+ fields: {
+ secret_id: secretId,
+ },
+ payloadSummary: {
+ secretId,
+ },
+ });
+
return [undefined, getMessage().SECRET_DELETED];
}
diff --git a/src/client/src/lib/rbac/routes/api/alert-destinations/[id]/route.ts b/src/client/src/lib/rbac/routes/api/alert-destinations/[id]/route.ts
new file mode 100644
index 00000000..1b4804cd
--- /dev/null
+++ b/src/client/src/lib/rbac/routes/api/alert-destinations/[id]/route.ts
@@ -0,0 +1,5 @@
+import { alertingUnavailable } from "../../alerts/unavailable";
+
+export const GET = alertingUnavailable;
+export const PATCH = alertingUnavailable;
+export const DELETE = alertingUnavailable;
diff --git a/src/client/src/lib/rbac/routes/api/alert-destinations/[id]/test/route.ts b/src/client/src/lib/rbac/routes/api/alert-destinations/[id]/test/route.ts
new file mode 100644
index 00000000..3d0cbfa3
--- /dev/null
+++ b/src/client/src/lib/rbac/routes/api/alert-destinations/[id]/test/route.ts
@@ -0,0 +1,3 @@
+import { alertingUnavailable } from "../../../alerts/unavailable";
+
+export const POST = alertingUnavailable;
diff --git a/src/client/src/lib/rbac/routes/api/alert-destinations/route.ts b/src/client/src/lib/rbac/routes/api/alert-destinations/route.ts
new file mode 100644
index 00000000..380e794d
--- /dev/null
+++ b/src/client/src/lib/rbac/routes/api/alert-destinations/route.ts
@@ -0,0 +1,4 @@
+import { alertingUnavailable } from "../alerts/unavailable";
+
+export const GET = alertingUnavailable;
+export const POST = alertingUnavailable;
diff --git a/src/client/src/lib/rbac/routes/api/alert-providers/route.ts b/src/client/src/lib/rbac/routes/api/alert-providers/route.ts
new file mode 100644
index 00000000..719c37f6
--- /dev/null
+++ b/src/client/src/lib/rbac/routes/api/alert-providers/route.ts
@@ -0,0 +1,3 @@
+import { alertingUnavailable } from "../alerts/unavailable";
+
+export const GET = alertingUnavailable;
diff --git a/src/client/src/lib/rbac/routes/api/alerts/[id]/route.ts b/src/client/src/lib/rbac/routes/api/alerts/[id]/route.ts
new file mode 100644
index 00000000..cad4ff29
--- /dev/null
+++ b/src/client/src/lib/rbac/routes/api/alerts/[id]/route.ts
@@ -0,0 +1,5 @@
+import { alertingUnavailable } from "../unavailable";
+
+export const GET = alertingUnavailable;
+export const PATCH = alertingUnavailable;
+export const DELETE = alertingUnavailable;
diff --git a/src/client/src/lib/rbac/routes/api/alerts/[id]/test/route.ts b/src/client/src/lib/rbac/routes/api/alerts/[id]/test/route.ts
new file mode 100644
index 00000000..95c8dd92
--- /dev/null
+++ b/src/client/src/lib/rbac/routes/api/alerts/[id]/test/route.ts
@@ -0,0 +1,3 @@
+import { alertingUnavailable } from "../../unavailable";
+
+export const POST = alertingUnavailable;
diff --git a/src/client/src/lib/rbac/routes/api/alerts/events/route.ts b/src/client/src/lib/rbac/routes/api/alerts/events/route.ts
new file mode 100644
index 00000000..c603ca49
--- /dev/null
+++ b/src/client/src/lib/rbac/routes/api/alerts/events/route.ts
@@ -0,0 +1,3 @@
+import { alertingUnavailable } from "../unavailable";
+
+export const GET = alertingUnavailable;
diff --git a/src/client/src/lib/rbac/routes/api/alerts/route.ts b/src/client/src/lib/rbac/routes/api/alerts/route.ts
new file mode 100644
index 00000000..c56b6599
--- /dev/null
+++ b/src/client/src/lib/rbac/routes/api/alerts/route.ts
@@ -0,0 +1,4 @@
+import { alertingUnavailable } from "./unavailable";
+
+export const GET = alertingUnavailable;
+export const POST = alertingUnavailable;
diff --git a/src/client/src/lib/rbac/routes/api/alerts/spec/route.ts b/src/client/src/lib/rbac/routes/api/alerts/spec/route.ts
new file mode 100644
index 00000000..c603ca49
--- /dev/null
+++ b/src/client/src/lib/rbac/routes/api/alerts/spec/route.ts
@@ -0,0 +1,3 @@
+import { alertingUnavailable } from "../unavailable";
+
+export const GET = alertingUnavailable;
diff --git a/src/client/src/lib/rbac/routes/api/alerts/unavailable.ts b/src/client/src/lib/rbac/routes/api/alerts/unavailable.ts
new file mode 100644
index 00000000..c2c17c40
--- /dev/null
+++ b/src/client/src/lib/rbac/routes/api/alerts/unavailable.ts
@@ -0,0 +1,6 @@
+export function alertingUnavailable() {
+ return Response.json(
+ { error: "Alerting is not available in this edition." },
+ { status: 402 }
+ );
+}
diff --git a/src/client/src/middleware/check-auth.ts b/src/client/src/middleware/check-auth.ts
index 1678208d..e546be22 100644
--- a/src/client/src/middleware/check-auth.ts
+++ b/src/client/src/middleware/check-auth.ts
@@ -16,6 +16,69 @@ import {
ONBOARDING_WHITELIST_API_ROUTES,
} from "@/constants/route";
+function isValidCronJobRequest(request: NextRequest) {
+ const expectedToken = process.env.CRON_JOB_SECRET;
+ const cronJobToken =
+ request.headers.get("X-CRON-JOB") ?? request.headers.get("x-cron-job");
+
+ return Boolean(expectedToken && cronJobToken === expectedToken);
+}
+
+const rateLimitWindows = new Map<string, { count: number; resetAt: number }>();
+const SENSITIVE_API_RATE_LIMIT = 120;
+const SENSITIVE_API_RATE_LIMIT_WINDOW_MS = 60_000;
+const SENSITIVE_API_RATE_LIMIT_CLEANUP_MS = 60_000;
+const RATE_LIMITED_API_PREFIXES = [
+ "/api/organisation",
+ "/api/metrics",
+ "/api/telemetry",
+ "/api/observability",
+ "/api/prompt",
+ "/api/evaluation",
+ "/api/agents",
+ "/api/alerts",
+ "/api/vault",
+ "/api/context",
+ "/api/manage-dashboard",
+];
+let nextRateLimitCleanupAt = 0;
+
+function shouldRateLimitApi(pathname: string) {
+ return RATE_LIMITED_API_PREFIXES.some((prefix) => pathname.startsWith(prefix));
+}
+
+function getClientRateLimitKey(request: NextRequest) {
+ return (
+ request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
+ request.headers.get("x-real-ip") ||
+ "unknown"
+ );
+}
+
+function isRateLimited(request: NextRequest) {
+ const now = Date.now();
+ if (now >= nextRateLimitCleanupAt) {
+ rateLimitWindows.forEach((window, key) => {
+ if (window.resetAt <= now) rateLimitWindows.delete(key);
+ });
+ nextRateLimitCleanupAt = now + SENSITIVE_API_RATE_LIMIT_CLEANUP_MS;
+ }
+
+ const key = getClientRateLimitKey(request);
+ const window = rateLimitWindows.get(key);
+
+ if (!window || window.resetAt <= now) {
+ rateLimitWindows.set(key, {
+ count: 1,
+ resetAt: now + SENSITIVE_API_RATE_LIMIT_WINDOW_MS,
+ });
+ return false;
+ }
+
+ window.count += 1;
+ return window.count > SENSITIVE_API_RATE_LIMIT;
+}
+
export default function checkAuth(next: NextMiddleware) {
return withAuth(
async function middleware(request: NextRequest, _next: NextFetchEvent) {
@@ -40,6 +103,7 @@ export default function checkAuth(next: NextMiddleware) {
const isAuthPage =
pathname.startsWith("/login") || pathname.startsWith("/register");
const isApiPage = pathname.startsWith("/api");
+ const isRateLimitedApi = shouldRateLimitApi(pathname);
const method = request.method.toUpperCase();
const isOnboardingWhitelistedPage = ONBOARDING_WHITELIST_ROUTES.includes(
pathname
@@ -83,12 +147,22 @@ export default function checkAuth(next: NextMiddleware) {
}
if (isApiPage) {
+ if (isRateLimitedApi && isRateLimited(request)) {
+ return NextResponse.json(
+ { error: "Too many requests" },
+ { status: 429 }
+ );
+ }
+
if (isAuth || isAllowedRequestWithoutToken || isCronJobRoute) {
if (isCronJobRoute) {
- const cronJobToken = request.headers.get("X-CRON-JOB");
- if (cronJobToken) {
+ if (isValidCronJobRequest(request)) {
return NextResponse.next();
}
+ return NextResponse.json(
+ { error: "Forbidden" },
+ { status: 403 }
+ );
}
// Enforce onboarding restrictions for authenticated API calls.
// Only explicitly whitelisted API routes should work before onboarding.
diff --git a/src/client/src/store/rule-engine.ts b/src/client/src/store/rule-engine.ts
index 8aa89b05..fbf68c4c 100644
--- a/src/client/src/store/rule-engine.ts
+++ b/src/client/src/store/rule-engine.ts
@@ -4,6 +4,7 @@ import { RuleEngineStore } from "@/types/store/rule-engine";
export const ruleEngineStoreSlice: RuleEngineStore = lens((setStore, getStore) => ({
fieldValuesCache: {},
fieldValuesLoading: {},
+ fieldLabelsCache: {},
setFieldValues: (field: string, values: string[]) => {
setStore(() => ({
...getStore(),
@@ -22,4 +23,13 @@ export const ruleEngineStoreSlice: RuleEngineStore = lens((setStore, getStore) =
},
}));
},
+ setFieldLabels: (field: string, labels: Record<string, string>) => {
+ setStore(() => ({
+ ...getStore(),
+ fieldLabelsCache: {
+ ...getStore().fieldLabelsCache,
+ [field]: labels,
+ },
+ }));
+ },
}));
diff --git a/src/client/src/types/alerts.ts b/src/client/src/types/alerts.ts
new file mode 100644
index 00000000..db5b6da0
--- /dev/null
+++ b/src/client/src/types/alerts.ts
@@ -0,0 +1,127 @@
+export type AlertStatus = "active" | "paused";
+export type AlertSeverity = "low" | "medium" | "high" | "critical";
+export type AlertTriggerType =
+ | "access_update"
+ | "invite"
+ | "prompt_version_update"
+ | "fleet_hub_config_update"
+ | "vault_secret_change"
+ | "context_change"
+ | "rule_engine_change";
+
+export type AlertProviderType =
+ | "slack"
+ | "email"
+ | "webhook"
+ | "datadog"
+ | "teams"
+ | "pagerduty"
+ | "opsgenie"
+ | "discord";
+
+export type AlertEventStatus = "pending" | "success" | "partial_failure" | "failure";
+export type AlertDeliveryStatus = "pending" | "success" | "failure" | "skipped";
+
+export type AlertConditionInput = {
+ field: string;
+ operator: string;
+ value: string;
+ data_type?: "string" | "number" | "boolean";
+};
+
+export type AlertConditionGroupInput = {
+ condition_operator?: "AND" | "OR";
+ conditions: AlertConditionInput[];
+};
+
+export type AlertDestinationBindingInput = {
+ destinationId: string;
+ overrides?: Record<string, unknown>;
+};
+
+export type AlertInput = {
+ name: string;
+ description?: string;
+ status?: AlertStatus;
+ severity?: AlertSeverity;
+ triggerType?: AlertTriggerType;
+ triggerTypes?: AlertTriggerType[];
+ triggerConfig?: Record<string, unknown>;
+ ruleId?: string | null;
+ conditionGroups?: AlertConditionGroupInput[];
+ destinationIds?: string[];
+ destinations?: AlertDestinationBindingInput[];
+ projectId?: string | null;
+ databaseConfigId?: string | null;
+ cooldownSeconds?: number;
+ dedupeKey?: string | null;
+};
+
+export type AlertDestinationInput = {
+ name: string;
+ providerType: AlertProviderType;
+ status?: AlertStatus;
+ config?: Record<string, unknown>;
+ metadata?: Record<string, unknown>;
+};
+
+export type AlertSignalInput = {
+ triggerType: AlertTriggerType;
+ fields: Record<string, string | number | boolean>;
+ organisationId?: string;
+ projectId?: string | null;
+ databaseConfigId?: string | null;
+ sourceId?: string | null;
+ payloadSummary?: Record<string, unknown>;
+};
+
+export type ProviderFieldDefinition = {
+ key: string;
+ label: string;
+ type: "string" | "number" | "boolean" | "password" | "url" | "email" | "string[]";
+ required?: boolean;
+ secret?: boolean;
+ description?: string;
+ placeholder?: string;
+};
+
+export type AlertProviderCapability =
+ | "notify"
+ | "test"
+ | "webhook"
+ | "metadata";
+
+export type AlertProviderMetadata = {
+ type: AlertProviderType;
+ name: string;
+ description: string;
+ category: "chat" | "email" | "incident" | "observability" | "webhook";
+ tags: string[];
+ capabilities: AlertProviderCapability[];
+ configSchema: ProviderFieldDefinition[];
+ credentialSchema?: ProviderFieldDefinition[];
+};
+
+export type AlertProviderPayload = {
+ title: string;
+ message: string;
+ severity: AlertSeverity;
+ alertId?: string;
+ alertName?: string;
+ eventId?: string;
+ triggerType?: AlertTriggerType;
+ fields?: Record<string, unknown>;
+ url?: string;
+ presentation?: {
+ style?: "default" | "compact" | "detailed" | "incident";
+ accentColor?: string;
+ includeFields?: boolean;
+ };
+};
+
+export type AlertProviderSendResult = {
+ success: boolean;
+ statusCode?: number;
+ response?: Record<string, unknown>;
+ error?: string;
+};
diff --git a/src/client/src/types/rule-engine.ts b/src/client/src/types/rule-engine.ts
index 6f3647c3..18a11a4b 100644
--- a/src/client/src/types/rule-engine.ts
+++ b/src/client/src/types/rule-engine.ts
@@ -21,7 +21,8 @@ export type RuleEntityType =
| "prompt"
// | "dataset"
// | "meta_config"
- | "evaluation";
+ | "evaluation"
+ | "alert";
export interface Rule {
id: string;
diff --git a/src/client/src/types/store/rule-engine.ts b/src/client/src/types/store/rule-engine.ts
index 1b506755..0223ba12 100644
--- a/src/client/src/types/store/rule-engine.ts
+++ b/src/client/src/types/store/rule-engine.ts
@@ -1,6 +1,8 @@
export type RuleEngineStore = {
fieldValuesCache: Record<string, string[]>;
fieldValuesLoading: Record<string, boolean>;
+ fieldLabelsCache: Record<string, Record<string, string>>;
setFieldValues: (field: string, values: string[]) => void;
setFieldValuesLoading: (field: string, loading: boolean) => void;
+ setFieldLabels: (field: string, labels: Record<string, string>) => void;
};