Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(webhooks): optional payload field filter for webhook triggers
AdityaUmale46859b3276ae
diff --git a/server/cloud-send-kinds.ts b/server/cloud-send-kinds.tsindex abd32b3b60..dad79d7046 100644--- a/server/cloud-send-kinds.ts+++ b/server/cloud-send-kinds.ts@@ -39,7 +39,7 @@ const KIND_BODY_MAX = 8 * 1024 * 1024;const ROUTINE_FIELDS = ["name", "prompt", "target", "botId", "groupId", "runOn", "schedule", "durationMinutes", "timeoutMinutes", "attachments", "continuity", "modelSelection","overlap", "runOnStartup", "sourceThreadId", "resultsThreadId", "createdAt", "checks", "access", "deliver"] as const;const CALL_FIELDS = ["name", "description", "botIds", "schedule", "durationMinutes", "attachments", "roomId", "createdAt"] as const;-const WEBHOOK_FIELDS = ["name", "prompt", "botId", "runOn", "delivery", "groupId", "eventTypes", "maxPendingRuns", "sameConversation", "resultsThreadId", "createdAt"] as const;+const WEBHOOK_FIELDS = ["name", "prompt", "botId", "runOn", "delivery", "groupId", "eventTypes", "payloadFilter", "maxPendingRuns", "sameConversation", "resultsThreadId", "createdAt"] as const;const APP_EVENT_FIELDS = ["name", "prompt", "botId", "runOn", "app", "event", "accountId", "config", "filter", "sourceThreadId", "sameConversation"] as const;/** Prose that may name this computer's data folder. */const TEXTS = ["prompt", "description", "output", "error"] as const;diff --git a/server/drivers/agents-call-triggers.ts b/server/drivers/agents-call-triggers.tsindex dbba24a86e..b6f7a45d51 100644--- a/server/drivers/agents-call-triggers.ts+++ b/server/drivers/agents-call-triggers.ts@@ -305,6 +305,16 @@ function triggerFields(args: Json): { fields: Json; error?: string } {}fields.eventTypes = eventTypes.map((value) => String(value).trim()).filter(Boolean);}+ const payloadFilter = args.webhook_payload_filter;+ if (payloadFilter !== undefined && payloadFilter !== null) {+ const entries = jsonRecord(payloadFilter) ? Object.entries(payloadFilter) : null;+ if (!entries || entries.some(([field, value]) => !field.trim() || field.length > 200+ || !(typeof value === "string" || typeof value === "number" || typeof value === "boolean") || String(value).length > 200)) {+ return { fields, error: 'webhook_payload_filter must be an object of field paths and the text each must have, e.g. {"action":"opened","pull_request.base.ref":"main"}.' };+ }+ if (entries.length > 10) return { fields, error: "webhook_payload_filter takes at most 10 fields." };+ fields.payloadFilter = Object.fromEntries(entries.map(([field, value]) => [field.trim(), String(value).trim()]));+ }if (args.same_conversation !== undefined && args.same_conversation !== null) {if (typeof args.same_conversation !== "boolean") return { fields, error: "same_conversation must be true or false." };fields.sameConversation = args.same_conversation;@@ -444,7 +454,7 @@ async function createTrigger(args: Json, forBotId: string | undefined, context:}if (fields.sameConversation !== undefined && when !== "app_event" && when !== "webhook") return { text: SAME_CONVERSATION_ONLY, isError: true };if (when === "app_event") {- const misplaced = [...SCHEDULE_ONLY, "webhook_event_types"].find((key) => args[key] !== undefined && args[key] !== null);+ const misplaced = [...SCHEDULE_ONLY, "webhook_event_types", "webhook_payload_filter"].find((key) => args[key] !== undefined && args[key] !== null);if (misplaced) return { text: `An app-event trigger fires when the app's event happens, so it takes no ${misplaced}.`, isError: true };const app = typeof args.app === "string" ? args.app.trim().toLowerCase() : "";const event = typeof args.event === "string" ? args.event.trim() : "";@@ -458,11 +468,11 @@ async function createTrigger(args: Json, forBotId: string | undefined, context:return request({ action: "create", kind: "app", trigger, ...(forBotId ? { forBotId } : {}) }, context, `Created the app-event trigger “${String(fields.name)}”`);}if (when === "limit_reset") {- const misplaced = ["schedule", "webhook_event_types", "run_on_startup", "runOnStartup"].find((key) => args[key] !== undefined && args[key] !== null);+ const misplaced = ["schedule", "webhook_event_types", "webhook_payload_filter", "run_on_startup", "runOnStartup"].find((key) => args[key] !== undefined && args[key] !== null);if (misplaced) return { text: `A limit-reset trigger runs when the engine's limit resets, so it takes no ${misplaced}.`, isError: true };const timing = limitResetSchedule(args.engine, args.repeat);if (timing.error) return { text: timing.error, isError: true };- const { eventTypes: _unused, ...routine } = fields;+ const { eventTypes: _unused, payloadFilter: _unusedFilter, ...routine } = fields;return request({ action: "create", kind: "schedule", routine: { ...routine, schedule: timing.schedule }, ...(forBotId ? { forBotId } : {}) }, context,`Created the trigger “${String(fields.name)}” for when the limit resets`);}@@ -470,12 +480,14 @@ async function createTrigger(args: Json, forBotId: string | undefined, context:if (when === "schedule") {if (!fields.schedule) return { text: "A schedule trigger needs schedule.", isError: true };if (fields.eventTypes) return { text: "webhook_event_types applies only to when=webhook.", isError: true };- const { eventTypes: _unused, ...routine } = fields;+ if (fields.payloadFilter) return { text: "webhook_payload_filter applies only to when=webhook.", isError: true };+ const { eventTypes: _unused, payloadFilter: _unusedFilter, ...routine } = fields;return request({ action: "create", kind: "schedule", routine, ...(forBotId ? { forBotId } : {}) }, context, `Created ${label}`);}const misplaced = SCHEDULE_ONLY.find((key) => args[key] !== undefined && args[key] !== null);if (misplaced) return { text: `A webhook trigger fires when its link is called, so it takes no ${misplaced}.`, isError: true };const webhook = { name: fields.name, instructions: fields.instructions, ...(fields.runOn ? { runOn: fields.runOn } : {}), ...(fields.eventTypes ? { eventTypes: fields.eventTypes } : {}),+ ...(fields.payloadFilter ? { payloadFilter: fields.payloadFilter } : {}),...(fields.sameConversation !== undefined ? { sameConversation: fields.sameConversation } : {}) };return request({ action: "create", kind: "webhook", webhook, ...(forBotId ? { forBotId } : {}) }, context, `Created ${label}`);}diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.tsindex 06e9ffe750..3d8bbd268f 100644--- a/server/drivers/agents-catalog.ts+++ b/server/drivers/agents-catalog.ts@@ -118,6 +118,12 @@ const TRIGGER_FIELDS_SCHEMA = {items: { type: "string", maxLength: 200 },description: "Only for when=webhook: optional event names to accept (from the caller's event-type header, e.g. push). Omit to accept every call.",},+ webhook_payload_filter: {+ type: "object",+ maxProperties: 10,+ additionalProperties: { type: "string", maxLength: 200 },+ description: "Only for when=webhook: optional fields the call's JSON must have before any run starts, path to text, e.g. {\"action\":\"opened\",\"pull_request.base.ref\":\"main\"}. All must match (case-insensitive); other calls are ignored without a run. Use it instead of instructions like \"if it is not X, stop\" when the sender's data says X. {} in an update removes it.",+ },filter: {type: "object",additionalProperties: false,diff --git a/server/index.ts b/server/index.tsindex 1f408e6c8b..e2c2fc1b2d 100644--- a/server/index.ts+++ b/server/index.ts@@ -1248,7 +1248,7 @@ onConfigSaved((before, after) => {for (const row of configChangeRows(before, after)) appendAdminAction(DATA_DIR, { ...row, actor: scope.actor });});-const WEBHOOK_AUDIT_FIELDS = ["name", "prompt", "botId", "runOn", "enabled", "eventTypes"] as const;+const WEBHOOK_AUDIT_FIELDS = ["name", "prompt", "botId", "runOn", "enabled", "eventTypes", "payloadFilter"] as const;const BOT_AUDITED = CLOUD_TEAM ? TEAM_BOT_AUDIT_FIELDS : BOT_AUDIT_FIELDS;const auditBot = (id: string | undefined) => (id ? botAuditSnapshot(store.bot(id) as unknown as Record<string, unknown> | null, BOT_AUDITED) : null);const auditHook = (id: string | undefined) => (id ? webhooks.list().find((hook) => hook.id === id) : undefined);diff --git a/server/trigger-tools.ts b/server/trigger-tools.tsindex 483939443a..84706a6276 100644--- a/server/trigger-tools.ts+++ b/server/trigger-tools.ts@@ -88,6 +88,7 @@ export function agentWebhook(webhook: WebhookTrigger, latestRun?: RoutineRun) {enabled: webhook.enabled,runOn: webhook.runOn,eventTypes: webhook.eventTypes ?? [],+ ...(webhook.payloadFilter ? { payloadFilter: webhook.payloadFilter } : {}),calls: webhook.deliveryCount,lastCalledAt: timestamp(webhook.lastReceivedAt),latestRun: latestRun ? agentRun(latestRun) : null,@@ -177,7 +178,7 @@ const triggerRequestSchema = z.union([z.object({ ...source, action: z.enum(["pause", "resume", "run_now", "delete"]), triggerId: z.string().min(1).max(200) }).strict(),]);-const WEBHOOK_FIELDS = new Set(["name", "instructions", "runOn", "eventTypes", "sameConversation"]);+const WEBHOOK_FIELDS = new Set(["name", "instructions", "runOn", "eventTypes", "payloadFilter", "sameConversation"]);const APP_FIELDS = new Set(["name", "instructions", "runOn", "filter", "config", "sameConversation"]);export type ParsedTriggerRequest =@@ -206,12 +207,13 @@ export function parseTriggerRequest(body: unknown, kindOf: (id: string) => "sche}if (kind === "schedule") {if (changes && "eventTypes" in changes) return { ok: false, error: "webhook_event_types applies only to webhook triggers" };+ if (changes && "payloadFilter" in changes) return { ok: false, error: "webhook_payload_filter applies only to webhook triggers" };if (changes && ("filter" in changes || "config" in changes)) return { ok: false, error: "filter and event_config apply only to app-event triggers" };if (changes && "sameConversation" in changes) return { ok: false, error: "same_conversation applies only to app-event and webhook triggers" };return { ok: true, kind: "schedule", forBotId: request.forBotId, proposal: { action: request.action, routineId: request.triggerId, ...(changes ? { changes } : {}) } };}const misplaced = changes && Object.keys(changes).find((key) => !WEBHOOK_FIELDS.has(key));- if (misplaced) return { ok: false, error: `A webhook trigger has no ${misplaced}; it fires when its link is called. Change name, instructions, run_on, webhook_event_types or same_conversation.` };+ if (misplaced) return { ok: false, error: `A webhook trigger has no ${misplaced}; it fires when its link is called. Change name, instructions, run_on, webhook_event_types, webhook_payload_filter or same_conversation.` };return { ok: true, kind: "webhook", forBotId: request.forBotId, operation: { action: request.action, webhookId: request.triggerId, ...(changes ? { changes } : {}) } };}diff --git a/server/webhook-payload-filter.test.ts b/server/webhook-payload-filter.test.tsnew file mode 100644index 0000000000..743a9adf7e--- /dev/null+++ b/server/webhook-payload-filter.test.ts@@ -0,0 +1,117 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { callTool, type ToolCallContext } from "./drivers/agents-call.ts";+import { parseTriggerRequest } from "./trigger-tools.ts";+import { unmatchedPayloadField, WebhookManager, type WebhookManagerOptions } from "./webhooks.ts";++const dirs: string[] = [];+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function harness() {+ const dir = mkdtempSync(join(tmpdir(), "omb-webhook-filter-"));+ dirs.push(dir);+ const queued: Array<Record<string, unknown>> = [];+ let run = 0;+ const options: WebhookManagerOptions = {+ file: join(dir, "webhooks.json"),+ botState: () => "ready",+ enqueue: (input) => {+ queued.push(input);+ return { id: `run-${++run}` };+ },+ };+ return { manager: new WebhookManager(options), options, queued };+}++describe("webhook payload filter", () => {+ it("matches dotted fields case-insensitively, searches lists, and names the first field that misses", () => {+ const payload = { action: "Opened", pull_request: { base: { ref: "main" }, draft: false, number: 7 }, labels: [{ name: "bug" }, { name: "ui" }], tags: ["a", "b"] };+ expect(unmatchedPayloadField(undefined, payload)).toBeNull();+ expect(unmatchedPayloadField({ action: "opened", "pull_request.base.ref": "MAIN" }, payload)).toBeNull();+ expect(unmatchedPayloadField({ "pull_request.draft": "false", "pull_request.number": "7" }, payload)).toBeNull();+ expect(unmatchedPayloadField({ "labels.name": "ui", tags: "b", "labels.0.name": "bug" }, payload)).toBeNull();+ expect(unmatchedPayloadField({ action: "opened", "labels.1.name": "bug" }, payload)).toBe("labels.1.name");+ expect(unmatchedPayloadField({ "pull_request.base": "main" }, payload)).toBe("pull_request.base");+ expect(unmatchedPayloadField({ missing: "x" }, payload)).toBe("missing");+ expect(unmatchedPayloadField({ action: "opened" }, "action=opened")).toBe("action");+ expect(unmatchedPayloadField({ toString: "x" }, {})).toBe("toString");+ });++ it("records a call that does not match as ignored and starts no run; a matching call runs", () => {+ const h = harness();+ const { webhook, secret } = h.manager.create({ name: "Doorbell", prompt: "Answer it", botId: "maus-1", payloadFilter: { " status ": " ring ", "visitor.known": "" } });+ expect(webhook.payloadFilter).toEqual({ status: "ring" });++ expect(h.manager.receive(webhook.endpointId, secret, { payload: { status: "idle" }, deliveryId: "d-1" })).toMatchObject({ ignored: true });+ expect(h.queued).toHaveLength(0);+ expect(h.manager.listAttempts().find((attempt) => attempt.outcome === "ignored")).toMatchObject({ outcome: "ignored", reason: "Field “status” does not match the payload filter" });++ expect(h.manager.receive(webhook.endpointId, secret, { payload: { status: "RING" }, deliveryId: "d-2" })).toMatchObject({ duplicate: false });+ expect(h.queued).toHaveLength(1);+ });++ it("keeps the filter across a restart and an unrelated edit, removes it with null or {}, and lets Run now through", () => {+ const h = harness();+ const { webhook, secret } = h.manager.create({ name: "Doorbell", prompt: "Answer it", botId: "maus-1", payloadFilter: { status: "ring" } });+ const reloaded = new WebhookManager(h.options);+ expect(reloaded.list()[0]!.payloadFilter).toEqual({ status: "ring" });+ expect(reloaded.update(webhook.id, { name: "Front door" })!.payloadFilter).toEqual({ status: "ring" });++ expect(reloaded.test(webhook.id)).toMatchObject({ duplicate: false });+ expect(h.queued).toHaveLength(1);++ expect(reloaded.update(webhook.id, { payloadFilter: {} })!.payloadFilter).toBeUndefined();+ expect(reloaded.receive(webhook.endpointId, secret, { payload: { status: "idle" }, deliveryId: "d-3" })).not.toMatchObject({ ignored: true });+ expect(reloaded.update(webhook.id, { payloadFilter: { status: "ring" } })!.payloadFilter).toEqual({ status: "ring" });+ expect(reloaded.update(webhook.id, { payloadFilter: null })!.payloadFilter).toBeUndefined();+ });++ it("refuses more than 10 fields", () => {+ const h = harness();+ const payloadFilter = Object.fromEntries(Array.from({ length: 11 }, (_, index) => [`f${index}`, "x"]));+ expect(() => h.manager.create({ name: "Too many", prompt: "x", botId: "maus-1", payloadFilter })).toThrow();+ });+});++describe("webhook_payload_filter in the trigger tool", () => {+ function context() {+ const calls: Array<{ path: string; body?: unknown }> = [];+ const client = {+ api: async (path: string) => { calls.push({ path }); return {}; },+ apiResponse: async (path: string, init: RequestInit) => {+ calls.push({ path, body: JSON.parse(String(init.body)) });+ return { ok: true, status: 201, body: { resultId: "t-1", summary: "When another app sends something, Scout follows: Answer." } };+ },+ };+ return { calls, context: { botId: "scout", threadId: "thread-1", depth: 0, externalRuntime: false, sharedComputers: false, client } as unknown as ToolCallContext };+ }++ it("sends the filter on a webhook create and update", async () => {+ const { calls, context: ctx } = context();+ const created = await callTool("trigger", { action: "create", when: "webhook", name: "Doorbell", instructions: "Answer.", webhook_payload_filter: { " status ": "ring", count: 2 } }, ctx);+ expect(created.isError).toBeUndefined();+ expect(calls[0]!.body).toMatchObject({ action: "create", kind: "webhook", webhook: { name: "Doorbell", payloadFilter: { status: "ring", count: "2" } } });+ await callTool("trigger", { action: "update", trigger_id: "t-1", webhook_payload_filter: {} }, ctx);+ expect(calls[1]!.body).toMatchObject({ action: "update", triggerId: "t-1", changes: { payloadFilter: {} } });+ });++ it("refuses it on other kinds and refuses a malformed filter before anything is sent", async () => {+ const { calls, context: ctx } = context();+ expect((await callTool("trigger", { action: "create", when: "schedule", name: "A", instructions: "B", schedule: { type: "daily", time: "09:00" }, webhook_payload_filter: { a: "b" } }, ctx)).text)+ .toBe("webhook_payload_filter applies only to when=webhook.");+ expect((await callTool("trigger", { action: "create", when: "app_event", name: "A", instructions: "B", app: "gmail", event: "X", webhook_payload_filter: { a: "b" } }, ctx)).text)+ .toContain("takes no webhook_payload_filter");+ expect((await callTool("trigger", { action: "create", when: "webhook", name: "A", instructions: "B", webhook_payload_filter: ["a"] }, ctx)).text)+ .toContain("webhook_payload_filter must be an object");+ expect((await callTool("trigger", { action: "create", when: "webhook", name: "A", instructions: "B", webhook_payload_filter: { a: { b: 1 } } }, ctx)).text)+ .toContain("webhook_payload_filter must be an object");+ expect(calls).toEqual([]);+ expect(parseTriggerRequest({ fromBotId: "b", fromThreadId: "t", action: "update", triggerId: "r-1", changes: { payloadFilter: { a: "b" } } }, () => "schedule"))+ .toEqual({ ok: false, error: "webhook_payload_filter applies only to webhook triggers" });+ });+});diff --git a/server/webhook-requests.ts b/server/webhook-requests.tsindex 47197e9f22..45dec2cccd 100644--- a/server/webhook-requests.ts+++ b/server/webhook-requests.ts@@ -46,6 +46,7 @@ const definitionSchema = z.object({instructions: z.string().trim().max(INSTRUCTIONS_MAX).default(""),runOn: z.enum(["maus", "cloud"]).default("maus"),eventTypes: z.array(z.string().trim().min(1).max(200)).max(20).optional(),+ payloadFilter: z.record(z.string().trim().min(1).max(200), z.string().trim().max(200)).optional(),sameConversation: z.boolean().optional(),}).strict();const changesSchema = definitionSchema.partial().strict()@@ -82,6 +83,7 @@ function snapshot(webhook: WebhookTrigger): WebhookRequestSnapshot {runOn: webhook.runOn,enabled: webhook.enabled,...(webhook.eventTypes?.length ? { eventTypes: [...webhook.eventTypes] } : {}),+ ...(webhook.payloadFilter ? { payloadFilter: { ...webhook.payloadFilter } } : {}),...(webhook.sameConversation ? { sameConversation: true } : {}),};}@@ -92,14 +94,17 @@ function managerInput(definition: Partial<WebhookRequestDefinition>) {...(definition.instructions !== undefined ? { prompt: definition.instructions } : {}),...(definition.runOn !== undefined ? { runOn: definition.runOn } : {}),...(definition.eventTypes !== undefined ? { eventTypes: definition.eventTypes } : {}),+ ...(definition.payloadFilter !== undefined ? { payloadFilter: definition.payloadFilter } : {}),...(definition.sameConversation !== undefined ? { sameConversation: definition.sameConversation } : {}),};}/** What the card and the tool result say the trigger does, credential-scrubbed. */-export function webhookTriggerSentence(webhook: Pick<WebhookTrigger, "prompt" | "eventTypes">, botName: string): string {+export function webhookTriggerSentence(webhook: Pick<WebhookTrigger, "prompt" | "eventTypes" | "payloadFilter">, botName: string): string {const instructions = redactSecretsInText(webhook.prompt).trim();- const events = webhook.eventTypes?.length ? ` (only ${webhook.eventTypes.join(", ")})` : "";+ const fields = Object.entries(webhook.payloadFilter ?? {}).map(([field, value]) => `${field} is ${redactSecretsInText(value)}`);+ const only = [...(webhook.eventTypes ?? []), ...fields];+ const events = only.length ? ` (only ${only.join(", ")})` : "";return `When another app sends something${events}, ${botName} ${instructions ? `follows: ${instructions.slice(0, 400)}` : "does what it is asked"}`;}@@ -246,7 +251,7 @@ export class WebhookRequestService {const before = payload.undo?.before;if (!current || current.updatedAt !== payload.undo?.appliedUpdatedAt) return stale;const patch = operation.action === "update"- ? before ? { ...managerInput(before), eventTypes: before.eventTypes ?? [], sameConversation: before.sameConversation === true, enabled: before.enabled } : undefined+ ? before ? { ...managerInput(before), eventTypes: before.eventTypes ?? [], payloadFilter: before.payloadFilter ?? null, sameConversation: before.sameConversation === true, enabled: before.enabled } : undefined: { enabled: operation.action === "pause" };if (!patch || !webhooks.update(webhookId, patch)) return stale;break;diff --git a/server/webhooks.ts b/server/webhooks.tsindex a181d915d8..3910d1e3b8 100644--- a/server/webhooks.ts+++ b/server/webhooks.ts@@ -107,6 +107,9 @@ const maxPendingRunsSchema = z.number().int().min(1).max(MAX_PENDING_RUNS_LIMIT)const runOnSchema = z.enum(["maus", "cloud"]);const deliverySchema = z.enum(["run", "post"]);const eventTypesSchema = z.array(z.string()).max(20).optional();+export const PAYLOAD_FILTER_MAX_FIELDS = 10;+const payloadFilterSchema = z.record(z.string().max(200), z.string().max(200))+ .refine((filter) => Object.keys(filter).length <= PAYLOAD_FILTER_MAX_FIELDS, `A payload filter takes at most ${PAYLOAD_FILTER_MAX_FIELDS} fields`);const triggerInputSchema = z.object({name: z.string(),prompt: z.string(),@@ -117,6 +120,7 @@ const triggerInputSchema = z.object({enabled: z.boolean().optional(),verificationPending: z.boolean().optional(),eventTypes: eventTypesSchema,+ payloadFilter: payloadFilterSchema.nullable().optional(),maxPendingRuns: maxPendingRunsSchema.nullable().optional(),sameConversation: z.boolean().optional(),});@@ -147,6 +151,7 @@ const storedWebhookSchema = z.object({verifiedAt: z.number().finite().nonnegative().optional(),verificationSample: verificationSampleSchema.optional(),eventTypes: eventTypesSchema,+ payloadFilter: payloadFilterSchema.optional().catch(undefined),// A hand-edited value out of range falls back to the default instead of making the file unreadable.maxPendingRuns: maxPendingRunsSchema.optional().catch(undefined),sameConversation: z.boolean().optional().catch(undefined),@@ -216,6 +221,41 @@ function newSecret(): string {return `whsec_${randomBytes(32).toString("base64url")}`;}+/** Trimmed fields with a value; none left means no filter. */+function cleanPayloadFilter(filter: Record<string, string> | null | undefined): Record<string, string> | undefined {+ if (!filter) return undefined;+ const entries = Object.entries(filter)+ .map(([field, value]) => [field.trim().slice(0, 200), String(value).trim().slice(0, 200)] as const)+ .filter(([field, value]) => field && value);+ if (entries.length > PAYLOAD_FILTER_MAX_FIELDS) fail(400, `A payload filter takes at most ${PAYLOAD_FILTER_MAX_FIELDS} fields`);+ return entries.length ? Object.fromEntries(entries) : undefined;+}++/** Every value at a dotted path; a list along the way is searched item by item unless the step is its index. */+function valuesAt(node: unknown, path: readonly string[]): unknown[] {+ if (!path.length) return Array.isArray(node) ? node : [node];+ const [step, ...rest] = path;+ if (Array.isArray(node)) {+ return /^\d+$/.test(step) ? valuesAt(node[Number(step)], rest) : node.flatMap((item) => valuesAt(item, path));+ }+ if (node && typeof node === "object" && Object.prototype.hasOwnProperty.call(node, step)) {+ return valuesAt((node as Record<string, unknown>)[step], rest);+ }+ return [];+}++/** The first filter field the payload does not match, or null when every field matches (or there is no filter). */+export function unmatchedPayloadField(filter: Record<string, string> | undefined, payload: unknown): string | null {+ for (const [field, expected] of Object.entries(filter ?? {})) {+ const want = expected.trim().toLowerCase();+ const found = valuesAt(payload, field.split(".")).some((value) =>+ (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null)+ && String(value).trim().toLowerCase() === want);+ if (!found) return field;+ }+ return null;+}+function cleanInput(input: WebhookTriggerInput): CleanWebhookInput {const name = input.name.trim().slice(0, 80);const prompt = input.prompt.trim().slice(0, 20_000);@@ -239,6 +279,8 @@ function cleanInput(input: WebhookTriggerInput): CleanWebhookInput {verificationPending: enabled ? false : input.verificationPending === true,};if (eventTypes.length) clean.eventTypes = eventTypes;+ const payloadFilter = cleanPayloadFilter(input.payloadFilter);+ if (payloadFilter) clean.payloadFilter = payloadFilter;if (input.delivery) clean.delivery = input.delivery;const groupId = typeof input.groupId === "string" ? input.groupId.trim() : "";if (groupId && clean.delivery !== "post") fail(400, "a webhook room is only for delivery \"post\" webhooks");@@ -443,14 +485,14 @@ export class WebhookManager {this.assertWritable();const held = this.webhooks.find((candidate) => candidate.id === record.id);const clean = cleanInput({ name: record.name, prompt: record.prompt, botId: record.botId, runOn: record.runOn, delivery: record.delivery,- groupId: record.groupId ?? null, enabled: held?.enabled ?? false, eventTypes: record.eventTypes, maxPendingRuns: record.maxPendingRuns ?? null,+ groupId: record.groupId ?? null, enabled: held?.enabled ?? false, eventTypes: record.eventTypes, payloadFilter: record.payloadFilter, maxPendingRuns: record.maxPendingRuns ?? null,sameConversation: record.sameConversation });if (this.options.botState(clean.botId) === "missing") fail(409, "Its bot is not on this server yet");if (clean.groupId) this.assertRoomMember(clean.botId, clean.groupId);const definition = { ...clean, ...(record.resultsThreadId ? { resultsThreadId: record.resultsThreadId } : {}) };let trigger: StoredWebhookTrigger;if (held) {- for (const key of ["delivery", "groupId", "eventTypes", "maxPendingRuns", "sameConversation", "resultsThreadId"] as const) delete held[key];+ for (const key of ["delivery", "groupId", "eventTypes", "payloadFilter", "maxPendingRuns", "sameConversation", "resultsThreadId"] as const) delete held[key];trigger = Object.assign(held, definition, { verificationPending: held.verificationPending, updatedAt: this.now() });} else {const secret = newSecret();@@ -479,6 +521,7 @@ export class WebhookManager {enabled: patch.enabled ?? trigger.enabled,verificationPending: patch.verificationPending ?? trigger.verificationPending,eventTypes: patch.eventTypes ?? trigger.eventTypes,+ payloadFilter: patch.payloadFilter === undefined ? trigger.payloadFilter : patch.payloadFilter,maxPendingRuns: patch.maxPendingRuns === undefined ? trigger.maxPendingRuns : patch.maxPendingRuns,sameConversation: patch.sameConversation ?? trigger.sameConversation,});@@ -486,6 +529,7 @@ export class WebhookManager {if (clean.groupId) this.assertRoomMember(clean.botId, clean.groupId);Object.assign(trigger, clean, { updatedAt: this.now() });if (!clean.eventTypes?.length) delete trigger.eventTypes;+ if (!clean.payloadFilter) delete trigger.payloadFilter;if (!clean.groupId) delete trigger.groupId;if (clean.maxPendingRuns === undefined) delete trigger.maxPendingRuns;if (!clean.sameConversation) delete trigger.sameConversation;@@ -632,18 +676,19 @@ export class WebhookManager {if (!trigger.enabled && !byPerson) fail(409, "This webhook is paused");if (this.options.botState(trigger.botId) === "missing") fail(410, "The assigned MAUS no longer exists");- const allowed = trigger.eventTypes ?? [];- if (allowed.length > 0 && (!event.eventName || !allowed.includes(event.eventName))) {+ const ignore = (reason: string) => {const deliveryId = String(event.deliveryId ?? "").trim().slice(0, 200) || randomUUID();- this.appendAttempt(trigger, event, {- outcome: "ignored",- statusCode: 202,- deliveryId,- reason: event.eventName ? `Event type “${event.eventName}” is not enabled` : "Event type is missing",- });+ this.appendAttempt(trigger, event, { outcome: "ignored", statusCode: 202, deliveryId, reason });this.save();return { receipt: { deliveryId, duplicate: false, ignored: true } };+ };+ const allowed = trigger.eventTypes ?? [];+ if (allowed.length > 0 && (!event.eventName || !allowed.includes(event.eventName))) {+ return ignore(event.eventName ? `Event type “${event.eventName}” is not enabled` : "Event type is missing");}+ // The person's own Run now test runs whatever it sends, like a paused webhook's.+ const unmatched = byPerson ? null : unmatchedPayloadField(trigger.payloadFilter, event.payload);+ if (unmatched !== null) return ignore(`Field “${unmatched}” does not match the payload filter`);const requestedDeliveryId = String(event.deliveryId ?? "").trim().slice(0, 200);if (requestedDeliveryId) {diff --git a/shared/webhook-request.ts b/shared/webhook-request.tsindex 4adfd1c4b4..8e5162cd69 100644--- a/shared/webhook-request.ts+++ b/shared/webhook-request.ts@@ -9,6 +9,8 @@ export interface WebhookRequestDefinition {instructions: string;runOn: "maus" | "cloud";eventTypes?: string[];+ /** Field path -> text it must have; all must match before a run starts. Empty removes it on an update. */+ payloadFilter?: Record<string, string>;/** Each run continues the webhook's previous run conversation. */sameConversation?: boolean;}diff --git a/shared/webhooks.ts b/shared/webhooks.tsindex 7c521da368..7871008830 100644--- a/shared/webhooks.ts+++ b/shared/webhooks.ts@@ -30,6 +30,9 @@ export interface WebhookTrigger {verifiedAt?: number;verificationSample?: WebhookVerificationSample;eventTypes?: string[];+ /** Field path in the call's JSON (dots for nesting, e.g. "pull_request.state") -> the text it must have. Every field must+ * match (case-insensitive; a list matches when any item does), else the call is recorded as ignored and starts no run. */+ payloadFilter?: Record<string, string>;/** Unfinished runs this webhook may hold before new deliveries get 429.* Absent means the default (3). */maxPendingRuns?: number;@@ -48,6 +51,8 @@ export interface WebhookTriggerInput {enabled?: boolean;verificationPending?: boolean;eventTypes?: string[];+ /** `null` or `{}` on an edit removes the filter. */+ payloadFilter?: Record<string, string> | null;/** 1–50; `null` goes back to the default. */maxPendingRuns?: number | null;sameConversation?: boolean;