From fdd587d6af4d8878eeaf5e5f2a72696feefe8b13 Mon Sep 17 00:00:00 2001 From: Waleed Date: Thu, 12 Mar 2026 14:08:48 -0700 Subject: [PATCH 1/5] fix(jira): remove unnecessary projectId dependency from manualIssueKey (#3547) Issue keys are self-sufficient identifiers in Jira (e.g., PROJ-123). The manualIssueKey field is a text input where users type the key directly, so it should not depend on projectId/manualProjectId. This dependency caused the field to clear unnecessarily when the project selection changed. --- apps/sim/blocks/blocks/jira.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/sim/blocks/blocks/jira.ts b/apps/sim/blocks/blocks/jira.ts index a75b7c7b85..82f118cf21 100644 --- a/apps/sim/blocks/blocks/jira.ts +++ b/apps/sim/blocks/blocks/jira.ts @@ -165,7 +165,7 @@ export const JiraBlock: BlockConfig = { type: 'short-input', canonicalParamId: 'issueKey', placeholder: 'Enter Jira issue key', - dependsOn: ['credential', 'domain', 'projectId', 'manualProjectId'], + dependsOn: ['credential', 'domain'], condition: { field: 'operation', value: [ From 4cb0f4a2b072740bb89395a93818541176d80da8 Mon Sep 17 00:00:00 2001 From: Waleed Date: Thu, 12 Mar 2026 15:43:56 -0700 Subject: [PATCH 2/5] feat(ashby): add webhook triggers with automatic lifecycle management (#3548) * feat(ashby): add webhook triggers with automatic lifecycle management * fix(ashby): address PR review comments - Restore mode: 'advanced' on updateName sub-block - Move action after spread in formatWebhookInput to prevent override - Remove generic webhook trigger (Ashby requires webhookType) * fix(ashby): throw on unknown triggerId, always include webhookType * fix(ashby): address PR review feedback - paramVisibility, stageType, json catch - Add paramVisibility: 'user-only' to apiKey extra field - Remove stageType from candidateStageChange/candidateHire outputs (TriggerOutput type conflict with 'type' field) - Add .catch() fallback to .json() parse in createAshbyWebhookSubscription - Fix candidateStageChange outputs to match actual Ashby application payload structure * fix(ashby): add missing applicationSubmit outputs, fix delete log branches - Add candidate, currentInterviewStage, job to applicationSubmit outputs - Split delete webhook log into ok/404/error branches for accurate logging * fix(ashby): drain response body on delete, clarify decidedAt description - Cancel unconsumed response body in ok/404 delete branches to free connections - Update decidedAt description to note it's typically null at offer creation * fix(ashby): eliminate double-logging, fix hiringTeam JSDoc - Remove pre-throw warn/error logs; catch block is single logging point - Remove hiringTeam from candidateHire JSDoc (TriggerOutput doesn't support arrays) --- apps/docs/content/docs/en/tools/ashby.mdx | 2 + apps/docs/content/docs/en/tools/evernote.mdx | 15 ++ apps/docs/content/docs/en/tools/fathom.mdx | 15 ++ apps/docs/content/docs/en/tools/obsidian.mdx | 16 ++ apps/sim/blocks/blocks/ashby.ts | 21 ++ .../lib/webhooks/provider-subscriptions.ts | 171 ++++++++++++- apps/sim/lib/webhooks/utils.server.ts | 8 + apps/sim/triggers/ashby/application_submit.ts | 41 +++ apps/sim/triggers/ashby/candidate_delete.ts | 39 +++ apps/sim/triggers/ashby/candidate_hire.ts | 40 +++ .../triggers/ashby/candidate_stage_change.ts | 40 +++ apps/sim/triggers/ashby/index.ts | 6 + apps/sim/triggers/ashby/job_create.ts | 39 +++ apps/sim/triggers/ashby/offer_create.ts | 39 +++ apps/sim/triggers/ashby/utils.ts | 237 ++++++++++++++++++ apps/sim/triggers/registry.ts | 14 ++ 16 files changed, 741 insertions(+), 2 deletions(-) create mode 100644 apps/sim/triggers/ashby/application_submit.ts create mode 100644 apps/sim/triggers/ashby/candidate_delete.ts create mode 100644 apps/sim/triggers/ashby/candidate_hire.ts create mode 100644 apps/sim/triggers/ashby/candidate_stage_change.ts create mode 100644 apps/sim/triggers/ashby/index.ts create mode 100644 apps/sim/triggers/ashby/job_create.ts create mode 100644 apps/sim/triggers/ashby/offer_create.ts create mode 100644 apps/sim/triggers/ashby/utils.ts diff --git a/apps/docs/content/docs/en/tools/ashby.mdx b/apps/docs/content/docs/en/tools/ashby.mdx index 72c050beac..ac9c39d19a 100644 --- a/apps/docs/content/docs/en/tools/ashby.mdx +++ b/apps/docs/content/docs/en/tools/ashby.mdx @@ -22,6 +22,8 @@ With Ashby, you can: - **List and view jobs**: Browse all open, closed, and archived job postings with location and department info - **List applications**: View all applications across your organization with candidate and job details, status tracking, and pagination +The Ashby block also supports **webhook triggers** that automatically start workflows in response to Ashby events. Available triggers include Application Submitted, Candidate Stage Change, Candidate Hired, Candidate Deleted, Job Created, and Offer Created. Webhooks are fully managed — Sim automatically creates the webhook in Ashby when you save the trigger and deletes it when you remove it, so there's no manual webhook configuration needed. Just provide your Ashby API key (with `apiKeysWrite` permission) and select the event type. + In Sim, the Ashby integration enables your agents to programmatically manage your recruiting pipeline. Agents can search for candidates, create new candidate records, add notes after interviews, and monitor applications across jobs. This allows you to automate recruiting workflows like candidate intake, interview follow-ups, pipeline reporting, and cross-referencing candidates across roles. {/* MANUAL-CONTENT-END */} diff --git a/apps/docs/content/docs/en/tools/evernote.mdx b/apps/docs/content/docs/en/tools/evernote.mdx index 4c024edea3..a54840288f 100644 --- a/apps/docs/content/docs/en/tools/evernote.mdx +++ b/apps/docs/content/docs/en/tools/evernote.mdx @@ -10,6 +10,21 @@ import { BlockInfoCard } from "@/components/ui/block-info-card" color="#E0E0E0" /> +{/* MANUAL-CONTENT-START:intro */} +[Evernote](https://evernote.com/) is a note-taking and organization platform that helps individuals and teams capture ideas, manage projects, and store information across devices. With notebooks, tags, and powerful search, Evernote serves as a central hub for knowledge management. + +With the Sim Evernote integration, you can: + +- **Create and update notes**: Programmatically create new notes with content and tags, or update existing notes in any notebook. +- **Search and retrieve notes**: Use Evernote's search grammar to find notes by keyword, tag, notebook, or other criteria, and retrieve full note content. +- **Organize with notebooks and tags**: Create notebooks and tags, list existing ones, and move or copy notes between notebooks. +- **Delete and manage notes**: Move notes to trash or copy them to different notebooks as part of automated workflows. + +**How it works in Sim:** +Add an Evernote block to your workflow and select an operation (e.g., create note, search notes, list notebooks). Provide your Evernote developer token and any required parameters. The block calls the Evernote API and returns structured data you can pass to downstream blocks — for example, searching for meeting notes and sending summaries to Slack, or creating notes from AI-generated content. +{/* MANUAL-CONTENT-END */} + + ## Usage Instructions Integrate with Evernote to manage notes, notebooks, and tags. Create, read, update, copy, search, and delete notes. Create and list notebooks and tags. diff --git a/apps/docs/content/docs/en/tools/fathom.mdx b/apps/docs/content/docs/en/tools/fathom.mdx index 31b4988663..28984cb9c1 100644 --- a/apps/docs/content/docs/en/tools/fathom.mdx +++ b/apps/docs/content/docs/en/tools/fathom.mdx @@ -10,6 +10,21 @@ import { BlockInfoCard } from "@/components/ui/block-info-card" color="#181C1E" /> +{/* MANUAL-CONTENT-START:intro */} +[Fathom](https://fathom.video/) is an AI meeting assistant that automatically records, transcribes, and summarizes your video calls. It works across platforms like Zoom, Google Meet, and Microsoft Teams, generating highlights and action items so your team can stay focused during meetings and catch up quickly afterward. + +With the Sim Fathom integration, you can: + +- **List and filter meetings**: Retrieve recent meetings recorded by you or shared with your team, with optional filters by date range, recorder, or team. +- **Get meeting summaries**: Pull structured, markdown-formatted summaries for any recorded meeting to quickly review key discussion points. +- **Access full transcripts**: Retrieve complete transcripts with speaker attribution and timestamps for detailed review or downstream processing. +- **Manage teams and members**: List teams in your Fathom organization and view team member details to coordinate meeting workflows. + +**How it works in Sim:** +Add a Fathom block to your workflow and select an operation. Provide your Fathom API key and any required parameters (such as a recording ID for summaries and transcripts). The block calls the Fathom API and returns structured data you can pass to downstream blocks — for example, sending a summary to Slack or extracting action items with an AI agent. +{/* MANUAL-CONTENT-END */} + + ## Usage Instructions Integrate Fathom AI Notetaker into your workflow. List meetings, get transcripts and summaries, and manage team members and teams. Can also trigger workflows when new meeting content is ready. diff --git a/apps/docs/content/docs/en/tools/obsidian.mdx b/apps/docs/content/docs/en/tools/obsidian.mdx index c2b28f74cb..e15f6f9f9f 100644 --- a/apps/docs/content/docs/en/tools/obsidian.mdx +++ b/apps/docs/content/docs/en/tools/obsidian.mdx @@ -10,6 +10,22 @@ import { BlockInfoCard } from "@/components/ui/block-info-card" color="#0F0F0F" /> +{/* MANUAL-CONTENT-START:intro */} +[Obsidian](https://obsidian.md/) is a powerful knowledge base and note-taking application that works on top of a local folder of plain-text Markdown files. With features like bidirectional linking, graph views, and a rich plugin ecosystem, Obsidian is widely used for personal knowledge management, research, and documentation. + +With the Sim Obsidian integration, you can: + +- **Read and create notes**: Retrieve note content from your vault or create new notes programmatically as part of automated workflows. +- **Update and patch notes**: Modify existing notes in full or patch content at specific locations within a note. +- **Search your vault**: Find notes by keyword or content across your entire Obsidian vault. +- **Manage periodic notes**: Access and create daily or other periodic notes for journaling and task tracking. +- **Execute commands**: Trigger Obsidian commands remotely to automate vault operations. + +**How it works in Sim:** +Add an Obsidian block to your workflow and select an operation. This integration requires the [Obsidian Local REST API](https://github.com/coddingtonbear/obsidian-local-rest-api) plugin to be installed and running in your vault. Provide your API key and vault URL, along with any required parameters. The block communicates with your local Obsidian instance and returns structured data you can pass to downstream blocks — for example, searching your vault for research notes and feeding them into an AI agent for summarization. +{/* MANUAL-CONTENT-END */} + + ## Usage Instructions Read, create, update, search, and delete notes in your Obsidian vault. Manage periodic notes, execute commands, and patch content at specific locations. Requires the Obsidian Local REST API plugin. diff --git a/apps/sim/blocks/blocks/ashby.ts b/apps/sim/blocks/blocks/ashby.ts index 642ffc866d..409c453603 100644 --- a/apps/sim/blocks/blocks/ashby.ts +++ b/apps/sim/blocks/blocks/ashby.ts @@ -1,5 +1,6 @@ import { AshbyIcon } from '@/components/icons' import { AuthMode, type BlockConfig } from '@/blocks/types' +import { getTrigger } from '@/triggers' export const AshbyBlock: BlockConfig = { type: 'ashby', @@ -13,6 +14,18 @@ export const AshbyBlock: BlockConfig = { icon: AshbyIcon, authMode: AuthMode.ApiKey, + triggers: { + enabled: true, + available: [ + 'ashby_application_submit', + 'ashby_candidate_stage_change', + 'ashby_candidate_hire', + 'ashby_candidate_delete', + 'ashby_job_create', + 'ashby_offer_create', + ], + }, + subBlocks: [ { id: 'operation', @@ -366,6 +379,14 @@ Output only the ISO 8601 timestamp string, nothing else.`, }, mode: 'advanced', }, + + // Trigger subBlocks + ...getTrigger('ashby_application_submit').subBlocks, + ...getTrigger('ashby_candidate_stage_change').subBlocks, + ...getTrigger('ashby_candidate_hire').subBlocks, + ...getTrigger('ashby_candidate_delete').subBlocks, + ...getTrigger('ashby_job_create').subBlocks, + ...getTrigger('ashby_offer_create').subBlocks, ], tools: { diff --git a/apps/sim/lib/webhooks/provider-subscriptions.ts b/apps/sim/lib/webhooks/provider-subscriptions.ts index f220f33220..dbab9c6646 100644 --- a/apps/sim/lib/webhooks/provider-subscriptions.ts +++ b/apps/sim/lib/webhooks/provider-subscriptions.ts @@ -16,6 +16,7 @@ const telegramLogger = createLogger('TelegramWebhook') const airtableLogger = createLogger('AirtableWebhook') const typeformLogger = createLogger('TypeformWebhook') const calendlyLogger = createLogger('CalendlyWebhook') +const ashbyLogger = createLogger('AshbyWebhook') const grainLogger = createLogger('GrainWebhook') const fathomLogger = createLogger('FathomWebhook') const lemlistLogger = createLogger('LemlistWebhook') @@ -1974,6 +1975,7 @@ type RecreateCheckInput = { /** Providers that create external webhook subscriptions */ const PROVIDERS_WITH_EXTERNAL_SUBSCRIPTIONS = new Set([ 'airtable', + 'ashby', 'attio', 'calendly', 'fathom', @@ -2046,7 +2048,13 @@ export async function createExternalWebhookSubscription( let updatedProviderConfig = providerConfig let externalSubscriptionCreated = false - if (provider === 'airtable') { + if (provider === 'ashby') { + const result = await createAshbyWebhookSubscription(webhookData, requestId) + if (result) { + updatedProviderConfig = { ...updatedProviderConfig, externalId: result.id } + externalSubscriptionCreated = true + } + } else if (provider === 'airtable') { const externalId = await createAirtableWebhookSubscription(userId, webhookData, requestId) if (externalId) { updatedProviderConfig = { ...updatedProviderConfig, externalId } @@ -2126,7 +2134,9 @@ export async function cleanupExternalWebhook( workflow: any, requestId: string ): Promise { - if (webhook.provider === 'airtable') { + if (webhook.provider === 'ashby') { + await deleteAshbyWebhook(webhook, requestId) + } else if (webhook.provider === 'airtable') { await deleteAirtableWebhook(webhook, workflow, requestId) } else if (webhook.provider === 'attio') { await deleteAttioWebhook(webhook, workflow, requestId) @@ -2148,3 +2158,160 @@ export async function cleanupExternalWebhook( await deleteLemlistWebhook(webhook, requestId) } } + +/** + * Creates a webhook subscription in Ashby via webhook.create API. + * Ashby uses Basic Auth and one webhook per event type (webhookType). + */ +export async function createAshbyWebhookSubscription( + webhookData: any, + requestId: string +): Promise<{ id: string } | undefined> { + try { + const { path, providerConfig } = webhookData + const { apiKey, triggerId } = providerConfig || {} + + if (!apiKey) { + throw new Error( + 'Ashby API Key is required. Please provide your API Key with apiKeysWrite permission in the trigger configuration.' + ) + } + + if (!triggerId) { + throw new Error('Trigger ID is required to create Ashby webhook.') + } + + const webhookTypeMap: Record = { + ashby_application_submit: 'applicationSubmit', + ashby_candidate_stage_change: 'candidateStageChange', + ashby_candidate_hire: 'candidateHire', + ashby_candidate_delete: 'candidateDelete', + ashby_job_create: 'jobCreate', + ashby_offer_create: 'offerCreate', + } + + const webhookType = webhookTypeMap[triggerId] + if (!webhookType) { + throw new Error(`Unknown Ashby triggerId: ${triggerId}. Add it to webhookTypeMap.`) + } + + const notificationUrl = `${getBaseUrl()}/api/webhooks/trigger/${path}` + const authString = Buffer.from(`${apiKey}:`).toString('base64') + + ashbyLogger.info(`[${requestId}] Creating Ashby webhook`, { + triggerId, + webhookType, + webhookId: webhookData.id, + }) + + const requestBody: Record = { + requestUrl: notificationUrl, + webhookType, + } + + const ashbyResponse = await fetch('https://api.ashbyhq.com/webhook.create', { + method: 'POST', + headers: { + Authorization: `Basic ${authString}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(requestBody), + }) + + const responseBody = await ashbyResponse.json().catch(() => ({})) + + if (!ashbyResponse.ok || !responseBody.success) { + const errorMessage = + responseBody.errorInfo?.message || responseBody.message || 'Unknown Ashby API error' + + let userFriendlyMessage = 'Failed to create webhook subscription in Ashby' + if (ashbyResponse.status === 401) { + userFriendlyMessage = + 'Invalid Ashby API Key. Please verify your API Key is correct and has apiKeysWrite permission.' + } else if (ashbyResponse.status === 403) { + userFriendlyMessage = + 'Access denied. Please ensure your Ashby API Key has the apiKeysWrite permission.' + } else if (errorMessage && errorMessage !== 'Unknown Ashby API error') { + userFriendlyMessage = `Ashby error: ${errorMessage}` + } + + throw new Error(userFriendlyMessage) + } + + const externalId = responseBody.results?.id + if (!externalId) { + throw new Error('Ashby webhook creation succeeded but no webhook ID was returned') + } + + ashbyLogger.info( + `[${requestId}] Successfully created Ashby webhook subscription ${externalId} for webhook ${webhookData.id}` + ) + return { id: externalId } + } catch (error: any) { + ashbyLogger.error( + `[${requestId}] Exception during Ashby webhook creation for webhook ${webhookData.id}.`, + { + message: error.message, + stack: error.stack, + } + ) + throw error + } +} + +/** + * Deletes an Ashby webhook subscription via webhook.delete API. + * Ashby uses POST with webhookId in the body (not DELETE method). + */ +export async function deleteAshbyWebhook(webhook: any, requestId: string): Promise { + try { + const config = getProviderConfig(webhook) + const apiKey = config.apiKey as string | undefined + const externalId = config.externalId as string | undefined + + if (!apiKey) { + ashbyLogger.warn( + `[${requestId}] Missing apiKey for Ashby webhook deletion ${webhook.id}, skipping cleanup` + ) + return + } + + if (!externalId) { + ashbyLogger.warn( + `[${requestId}] Missing externalId for Ashby webhook deletion ${webhook.id}, skipping cleanup` + ) + return + } + + const authString = Buffer.from(`${apiKey}:`).toString('base64') + + const ashbyResponse = await fetch('https://api.ashbyhq.com/webhook.delete', { + method: 'POST', + headers: { + Authorization: `Basic ${authString}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ webhookId: externalId }), + }) + + if (ashbyResponse.ok) { + await ashbyResponse.body?.cancel() + ashbyLogger.info( + `[${requestId}] Successfully deleted Ashby webhook subscription ${externalId}` + ) + } else if (ashbyResponse.status === 404) { + await ashbyResponse.body?.cancel() + ashbyLogger.info( + `[${requestId}] Ashby webhook ${externalId} not found during deletion (already removed)` + ) + } else { + const responseBody = await ashbyResponse.json().catch(() => ({})) + ashbyLogger.warn( + `[${requestId}] Failed to delete Ashby webhook (non-fatal): ${ashbyResponse.status}`, + { response: responseBody } + ) + } + } catch (error) { + ashbyLogger.warn(`[${requestId}] Error deleting Ashby webhook (non-fatal)`, error) + } +} diff --git a/apps/sim/lib/webhooks/utils.server.ts b/apps/sim/lib/webhooks/utils.server.ts index 76068e451f..6a1a00ddbf 100644 --- a/apps/sim/lib/webhooks/utils.server.ts +++ b/apps/sim/lib/webhooks/utils.server.ts @@ -1244,6 +1244,14 @@ export async function formatWebhookInput( return extractPageData(body) } + if (foundWebhook.provider === 'ashby') { + return { + ...(body.data || {}), + action: body.action, + data: body.data || {}, + } + } + if (foundWebhook.provider === 'stripe') { return body } diff --git a/apps/sim/triggers/ashby/application_submit.ts b/apps/sim/triggers/ashby/application_submit.ts new file mode 100644 index 0000000000..1c5500cbd3 --- /dev/null +++ b/apps/sim/triggers/ashby/application_submit.ts @@ -0,0 +1,41 @@ +import { AshbyIcon } from '@/components/icons' +import { buildTriggerSubBlocks } from '@/triggers' +import { + ashbySetupInstructions, + ashbyTriggerOptions, + buildApplicationSubmitOutputs, + buildAshbyExtraFields, +} from '@/triggers/ashby/utils' +import type { TriggerConfig } from '@/triggers/types' + +/** + * Ashby Application Submitted Trigger + * + * This is the PRIMARY trigger - it includes the dropdown for selecting trigger type. + * Fires when a candidate submits an application or is manually added. + */ +export const ashbyApplicationSubmitTrigger: TriggerConfig = { + id: 'ashby_application_submit', + name: 'Ashby Application Submitted', + provider: 'ashby', + description: 'Trigger workflow when a new application is submitted', + version: '1.0.0', + icon: AshbyIcon, + + subBlocks: buildTriggerSubBlocks({ + triggerId: 'ashby_application_submit', + triggerOptions: ashbyTriggerOptions, + includeDropdown: true, + setupInstructions: ashbySetupInstructions('Application Submitted'), + extraFields: buildAshbyExtraFields('ashby_application_submit'), + }), + + outputs: buildApplicationSubmitOutputs(), + + webhook: { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + }, +} diff --git a/apps/sim/triggers/ashby/candidate_delete.ts b/apps/sim/triggers/ashby/candidate_delete.ts new file mode 100644 index 0000000000..e70d26971b --- /dev/null +++ b/apps/sim/triggers/ashby/candidate_delete.ts @@ -0,0 +1,39 @@ +import { AshbyIcon } from '@/components/icons' +import { buildTriggerSubBlocks } from '@/triggers' +import { + ashbySetupInstructions, + ashbyTriggerOptions, + buildAshbyExtraFields, + buildCandidateDeleteOutputs, +} from '@/triggers/ashby/utils' +import type { TriggerConfig } from '@/triggers/types' + +/** + * Ashby Candidate Deleted Trigger + * + * Fires when a candidate record is deleted from Ashby. + */ +export const ashbyCandidateDeleteTrigger: TriggerConfig = { + id: 'ashby_candidate_delete', + name: 'Ashby Candidate Deleted', + provider: 'ashby', + description: 'Trigger workflow when a candidate is deleted', + version: '1.0.0', + icon: AshbyIcon, + + subBlocks: buildTriggerSubBlocks({ + triggerId: 'ashby_candidate_delete', + triggerOptions: ashbyTriggerOptions, + setupInstructions: ashbySetupInstructions('Candidate Deleted'), + extraFields: buildAshbyExtraFields('ashby_candidate_delete'), + }), + + outputs: buildCandidateDeleteOutputs(), + + webhook: { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + }, +} diff --git a/apps/sim/triggers/ashby/candidate_hire.ts b/apps/sim/triggers/ashby/candidate_hire.ts new file mode 100644 index 0000000000..529b15e7f2 --- /dev/null +++ b/apps/sim/triggers/ashby/candidate_hire.ts @@ -0,0 +1,40 @@ +import { AshbyIcon } from '@/components/icons' +import { buildTriggerSubBlocks } from '@/triggers' +import { + ashbySetupInstructions, + ashbyTriggerOptions, + buildAshbyExtraFields, + buildCandidateHireOutputs, +} from '@/triggers/ashby/utils' +import type { TriggerConfig } from '@/triggers/types' + +/** + * Ashby Candidate Hired Trigger + * + * Fires when a candidate is hired. Also triggers applicationUpdate + * and candidateStageChange webhooks. + */ +export const ashbyCandidateHireTrigger: TriggerConfig = { + id: 'ashby_candidate_hire', + name: 'Ashby Candidate Hired', + provider: 'ashby', + description: 'Trigger workflow when a candidate is hired', + version: '1.0.0', + icon: AshbyIcon, + + subBlocks: buildTriggerSubBlocks({ + triggerId: 'ashby_candidate_hire', + triggerOptions: ashbyTriggerOptions, + setupInstructions: ashbySetupInstructions('Candidate Hired'), + extraFields: buildAshbyExtraFields('ashby_candidate_hire'), + }), + + outputs: buildCandidateHireOutputs(), + + webhook: { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + }, +} diff --git a/apps/sim/triggers/ashby/candidate_stage_change.ts b/apps/sim/triggers/ashby/candidate_stage_change.ts new file mode 100644 index 0000000000..a1a43a6302 --- /dev/null +++ b/apps/sim/triggers/ashby/candidate_stage_change.ts @@ -0,0 +1,40 @@ +import { AshbyIcon } from '@/components/icons' +import { buildTriggerSubBlocks } from '@/triggers' +import { + ashbySetupInstructions, + ashbyTriggerOptions, + buildAshbyExtraFields, + buildCandidateStageChangeOutputs, +} from '@/triggers/ashby/utils' +import type { TriggerConfig } from '@/triggers/types' + +/** + * Ashby Candidate Stage Change Trigger + * + * Fires when a candidate moves to a different interview stage. + * Also triggered by candidateHire events. + */ +export const ashbyCandidateStageChangeTrigger: TriggerConfig = { + id: 'ashby_candidate_stage_change', + name: 'Ashby Candidate Stage Change', + provider: 'ashby', + description: 'Trigger workflow when a candidate changes interview stages', + version: '1.0.0', + icon: AshbyIcon, + + subBlocks: buildTriggerSubBlocks({ + triggerId: 'ashby_candidate_stage_change', + triggerOptions: ashbyTriggerOptions, + setupInstructions: ashbySetupInstructions('Candidate Stage Change'), + extraFields: buildAshbyExtraFields('ashby_candidate_stage_change'), + }), + + outputs: buildCandidateStageChangeOutputs(), + + webhook: { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + }, +} diff --git a/apps/sim/triggers/ashby/index.ts b/apps/sim/triggers/ashby/index.ts new file mode 100644 index 0000000000..8b2570569b --- /dev/null +++ b/apps/sim/triggers/ashby/index.ts @@ -0,0 +1,6 @@ +export { ashbyApplicationSubmitTrigger } from './application_submit' +export { ashbyCandidateDeleteTrigger } from './candidate_delete' +export { ashbyCandidateHireTrigger } from './candidate_hire' +export { ashbyCandidateStageChangeTrigger } from './candidate_stage_change' +export { ashbyJobCreateTrigger } from './job_create' +export { ashbyOfferCreateTrigger } from './offer_create' diff --git a/apps/sim/triggers/ashby/job_create.ts b/apps/sim/triggers/ashby/job_create.ts new file mode 100644 index 0000000000..88d60e13c2 --- /dev/null +++ b/apps/sim/triggers/ashby/job_create.ts @@ -0,0 +1,39 @@ +import { AshbyIcon } from '@/components/icons' +import { buildTriggerSubBlocks } from '@/triggers' +import { + ashbySetupInstructions, + ashbyTriggerOptions, + buildAshbyExtraFields, + buildJobCreateOutputs, +} from '@/triggers/ashby/utils' +import type { TriggerConfig } from '@/triggers/types' + +/** + * Ashby Job Created Trigger + * + * Fires when a new job posting is created in Ashby. + */ +export const ashbyJobCreateTrigger: TriggerConfig = { + id: 'ashby_job_create', + name: 'Ashby Job Created', + provider: 'ashby', + description: 'Trigger workflow when a new job is created', + version: '1.0.0', + icon: AshbyIcon, + + subBlocks: buildTriggerSubBlocks({ + triggerId: 'ashby_job_create', + triggerOptions: ashbyTriggerOptions, + setupInstructions: ashbySetupInstructions('Job Created'), + extraFields: buildAshbyExtraFields('ashby_job_create'), + }), + + outputs: buildJobCreateOutputs(), + + webhook: { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + }, +} diff --git a/apps/sim/triggers/ashby/offer_create.ts b/apps/sim/triggers/ashby/offer_create.ts new file mode 100644 index 0000000000..3b952b65b7 --- /dev/null +++ b/apps/sim/triggers/ashby/offer_create.ts @@ -0,0 +1,39 @@ +import { AshbyIcon } from '@/components/icons' +import { buildTriggerSubBlocks } from '@/triggers' +import { + ashbySetupInstructions, + ashbyTriggerOptions, + buildAshbyExtraFields, + buildOfferCreateOutputs, +} from '@/triggers/ashby/utils' +import type { TriggerConfig } from '@/triggers/types' + +/** + * Ashby Offer Created Trigger + * + * Fires when a new offer is created for a candidate. + */ +export const ashbyOfferCreateTrigger: TriggerConfig = { + id: 'ashby_offer_create', + name: 'Ashby Offer Created', + provider: 'ashby', + description: 'Trigger workflow when a new offer is created', + version: '1.0.0', + icon: AshbyIcon, + + subBlocks: buildTriggerSubBlocks({ + triggerId: 'ashby_offer_create', + triggerOptions: ashbyTriggerOptions, + setupInstructions: ashbySetupInstructions('Offer Created'), + extraFields: buildAshbyExtraFields('ashby_offer_create'), + }), + + outputs: buildOfferCreateOutputs(), + + webhook: { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + }, +} diff --git a/apps/sim/triggers/ashby/utils.ts b/apps/sim/triggers/ashby/utils.ts new file mode 100644 index 0000000000..ff25fcd5f8 --- /dev/null +++ b/apps/sim/triggers/ashby/utils.ts @@ -0,0 +1,237 @@ +import type { SubBlockConfig } from '@/blocks/types' +import type { TriggerOutput } from '@/triggers/types' + +/** + * Dropdown options for the Ashby trigger type selector. + */ +export const ashbyTriggerOptions = [ + { label: 'Application Submitted', id: 'ashby_application_submit' }, + { label: 'Candidate Stage Change', id: 'ashby_candidate_stage_change' }, + { label: 'Candidate Hired', id: 'ashby_candidate_hire' }, + { label: 'Candidate Deleted', id: 'ashby_candidate_delete' }, + { label: 'Job Created', id: 'ashby_job_create' }, + { label: 'Offer Created', id: 'ashby_offer_create' }, +] + +/** + * Generates setup instructions for Ashby webhooks. + * Webhooks are automatically created/deleted via the Ashby API. + */ +export function ashbySetupInstructions(eventType: string): string { + const instructions = [ + 'Enter your Ashby API Key above.', + 'You can find your API key in Ashby at Settings > API Keys. The key must have the apiKeysWrite permission.', + `Click "Save Configuration" to automatically create the webhook in Ashby for ${eventType} events.`, + 'The webhook will be automatically deleted when you remove this trigger.', + ] + + return instructions + .map( + (instruction, index) => + `
${index + 1}. ${instruction}
` + ) + .join('') +} + +/** + * Ashby-specific extra fields for triggers. + * Includes API key (required for automatic webhook creation). + */ +export function buildAshbyExtraFields(triggerId: string): SubBlockConfig[] { + return [ + { + id: 'apiKey', + title: 'API Key', + type: 'short-input', + placeholder: 'Enter your Ashby API key', + description: 'Required to create the webhook in Ashby. Must have apiKeysWrite permission.', + password: true, + required: true, + paramVisibility: 'user-only', + mode: 'trigger', + condition: { field: 'selectedTriggerId', value: triggerId }, + }, + ] +} + +/** + * Core fields present in all Ashby webhook payloads. + */ +const coreOutputs = { + action: { + type: 'string', + description: 'The webhook event type (e.g., applicationSubmit, candidateHire)', + }, +} as const + +/** + * Build outputs for applicationSubmit events. + * Payload: { action, data: { application: { id, createdAt, updatedAt, status, + * candidate: { id, name }, currentInterviewStage: { id, title }, + * job: { id, title } } } } + */ +export function buildApplicationSubmitOutputs(): Record { + return { + ...coreOutputs, + application: { + id: { type: 'string', description: 'Application UUID' }, + createdAt: { type: 'string', description: 'Application creation timestamp (ISO 8601)' }, + updatedAt: { + type: 'string', + description: 'Application last update timestamp (ISO 8601)', + }, + status: { + type: 'string', + description: 'Application status (Active, Hired, Archived, Lead)', + }, + candidate: { + id: { type: 'string', description: 'Candidate UUID' }, + name: { type: 'string', description: 'Candidate name' }, + }, + currentInterviewStage: { + id: { type: 'string', description: 'Current interview stage UUID' }, + title: { type: 'string', description: 'Current interview stage title' }, + }, + job: { + id: { type: 'string', description: 'Job UUID' }, + title: { type: 'string', description: 'Job title' }, + }, + }, + } as Record +} + +/** + * Build outputs for candidateStageChange events. + * Payload matches the application object structure (same as applicationUpdate). + * Payload: { action, data: { application: { id, createdAt, updatedAt, status, + * candidate: { id, name }, currentInterviewStage: { id, title, type }, + * job: { id, title } } } } + */ +export function buildCandidateStageChangeOutputs(): Record { + return { + ...coreOutputs, + application: { + id: { type: 'string', description: 'Application UUID' }, + createdAt: { type: 'string', description: 'Application creation timestamp (ISO 8601)' }, + updatedAt: { + type: 'string', + description: 'Application last update timestamp (ISO 8601)', + }, + status: { + type: 'string', + description: 'Application status (Active, Hired, Archived, Lead)', + }, + candidate: { + id: { type: 'string', description: 'Candidate UUID' }, + name: { type: 'string', description: 'Candidate name' }, + }, + currentInterviewStage: { + id: { type: 'string', description: 'Current interview stage UUID' }, + title: { type: 'string', description: 'Current interview stage title' }, + }, + job: { + id: { type: 'string', description: 'Job UUID' }, + title: { type: 'string', description: 'Job title' }, + }, + }, + } as Record +} + +/** + * Build outputs for candidateHire events. + * Payload: { action, data: { application: { id, createdAt, updatedAt, status, + * candidate: { id, name }, currentInterviewStage: { id, title }, + * job: { id, title } } } } + */ +export function buildCandidateHireOutputs(): Record { + return { + ...coreOutputs, + application: { + id: { type: 'string', description: 'Application UUID' }, + createdAt: { type: 'string', description: 'Application creation timestamp (ISO 8601)' }, + updatedAt: { + type: 'string', + description: 'Application last update timestamp (ISO 8601)', + }, + status: { type: 'string', description: 'Application status (Hired)' }, + candidate: { + id: { type: 'string', description: 'Candidate UUID' }, + name: { type: 'string', description: 'Candidate name' }, + }, + currentInterviewStage: { + id: { type: 'string', description: 'Current interview stage UUID' }, + title: { type: 'string', description: 'Current interview stage title' }, + }, + job: { + id: { type: 'string', description: 'Job UUID' }, + title: { type: 'string', description: 'Job title' }, + }, + }, + } as Record +} + +/** + * Build outputs for candidateDelete events. + * Payload: { action, data: { candidate: { id } } } + */ +export function buildCandidateDeleteOutputs(): Record { + return { + ...coreOutputs, + candidate: { + id: { type: 'string', description: 'Deleted candidate UUID' }, + }, + } as Record +} + +/** + * Build outputs for jobCreate events. + * Payload: { action, data: { job: { id, title, confidential, status, employmentType } } } + */ +export function buildJobCreateOutputs(): Record { + return { + ...coreOutputs, + job: { + id: { type: 'string', description: 'Job UUID' }, + title: { type: 'string', description: 'Job title' }, + confidential: { type: 'boolean', description: 'Whether the job is confidential' }, + status: { type: 'string', description: 'Job status (Open, Closed, Draft, Archived)' }, + employmentType: { + type: 'string', + description: 'Employment type (Full-time, Part-time, etc.)', + }, + }, + } as Record +} + +/** + * Build outputs for offerCreate events. + * Payload: { action, data: { offer: { id, decidedAt, applicationId, acceptanceStatus, + * offerStatus, latestVersion: { id } } } } + */ +export function buildOfferCreateOutputs(): Record { + return { + ...coreOutputs, + offer: { + id: { type: 'string', description: 'Offer UUID' }, + applicationId: { type: 'string', description: 'Associated application UUID' }, + acceptanceStatus: { + type: 'string', + description: + 'Offer acceptance status (Accepted, Declined, Pending, Created, Cancelled, WaitingOnResponse)', + }, + offerStatus: { + type: 'string', + description: + 'Offer process status (WaitingOnApprovalStart, WaitingOnOfferApproval, WaitingOnCandidateResponse, CandidateAccepted, CandidateRejected, OfferCancelled)', + }, + decidedAt: { + type: 'string', + description: + 'Offer decision timestamp (ISO 8601). Typically null at creation; populated after candidate responds.', + }, + latestVersion: { + id: { type: 'string', description: 'Latest offer version UUID' }, + }, + }, + } as Record +} diff --git a/apps/sim/triggers/registry.ts b/apps/sim/triggers/registry.ts index 9ce20abaff..90171736d9 100644 --- a/apps/sim/triggers/registry.ts +++ b/apps/sim/triggers/registry.ts @@ -1,4 +1,12 @@ import { airtableWebhookTrigger } from '@/triggers/airtable' +import { + ashbyApplicationSubmitTrigger, + ashbyCandidateDeleteTrigger, + ashbyCandidateHireTrigger, + ashbyCandidateStageChangeTrigger, + ashbyJobCreateTrigger, + ashbyOfferCreateTrigger, +} from '@/triggers/ashby' import { attioCommentCreatedTrigger, attioCommentDeletedTrigger, @@ -166,6 +174,12 @@ import { whatsappWebhookTrigger } from '@/triggers/whatsapp' export const TRIGGER_REGISTRY: TriggerRegistry = { slack_webhook: slackWebhookTrigger, airtable_webhook: airtableWebhookTrigger, + ashby_application_submit: ashbyApplicationSubmitTrigger, + ashby_candidate_stage_change: ashbyCandidateStageChangeTrigger, + ashby_candidate_hire: ashbyCandidateHireTrigger, + ashby_candidate_delete: ashbyCandidateDeleteTrigger, + ashby_job_create: ashbyJobCreateTrigger, + ashby_offer_create: ashbyOfferCreateTrigger, attio_webhook: attioWebhookTrigger, attio_record_created: attioRecordCreatedTrigger, attio_record_updated: attioRecordUpdatedTrigger, From 72bb7e6945c53fb61173e0bc3017984e562240ce Mon Sep 17 00:00:00 2001 From: Waleed Date: Thu, 12 Mar 2026 16:56:02 -0700 Subject: [PATCH 3/5] fix(executor): skip Response block formatting for internal JWT callers (#3551) * fix(executor): skip Response block formatting for internal JWT callers The workflow executor tool received `{error: true}` despite successful child workflow execution when the child had a Response block. This happened because `createHttpResponseFromBlock()` hijacked the response with raw user-defined data, and the executor's `transformResponse` expected the standard `{success, executionId, output, metadata}` wrapper. Fix: skip Response block formatting when `authType === INTERNAL_JWT` since Response blocks are designed for external API consumers, not internal workflow-to-workflow calls. Also extract `AuthType` constants from magic strings across all auth type comparisons in the codebase. Co-Authored-By: Claude Opus 4.6 * test(executor): add route-level tests for Response block auth gating Verify that internal JWT callers receive standard format while external callers (API key, session) get Response block formatting. Tests the server-side condition directly using workflowHasResponseBlock and createHttpResponseFromBlock with AuthType constants. Co-Authored-By: Claude Opus 4.6 * fix(testing): add AuthType to all hybrid auth test mocks Route code now imports AuthType from @/lib/auth/hybrid, so test mocks must export it too. Added AuthTypeMock to @sim/testing and included it in all 15 test files that mock the hybrid auth module. Co-Authored-By: Claude Opus 4.6 --------- Co-authored-by: Claude Opus 4.6 --- apps/sim/app/api/a2a/serve/[agentId]/route.ts | 6 +- .../api/auth/oauth/credentials/route.test.ts | 1 + .../app/api/auth/oauth/token/route.test.ts | 1 + apps/sim/app/api/auth/oauth/token/route.ts | 6 +- apps/sim/app/api/files/delete/route.test.ts | 1 + apps/sim/app/api/files/parse/route.test.ts | 1 + .../api/files/serve/[...path]/route.test.ts | 1 + apps/sim/app/api/files/upload/route.test.ts | 1 + .../app/api/function/execute/route.test.ts | 1 + .../knowledge/[id]/tag-definitions/route.ts | 6 +- .../app/api/knowledge/search/route.test.ts | 1 + .../api/mcp/serve/[serverId]/route.test.ts | 1 + .../sim/app/api/mcp/serve/[serverId]/route.ts | 6 +- .../[executionId]/[contextId]/route.ts | 3 +- apps/sim/app/api/tools/custom/route.test.ts | 1 + .../app/api/users/me/usage-limits/route.ts | 4 +- .../workflows/[id]/chat/status/route.test.ts | 1 + .../[id]/execute/response-block.test.ts | 115 ++++++++++++++++++ .../app/api/workflows/[id]/execute/route.ts | 16 +-- .../workflows/[id]/form/status/route.test.ts | 1 + apps/sim/app/api/workflows/[id]/route.test.ts | 1 + apps/sim/app/api/workflows/[id]/route.ts | 4 +- .../workflows/[id]/variables/route.test.ts | 1 + apps/sim/app/api/workflows/route.test.ts | 1 + apps/sim/lib/auth/credential-access.ts | 8 +- apps/sim/lib/auth/hybrid.ts | 20 ++- apps/sim/tools/workflow/executor.test.ts | 95 +++++++++++++++ packages/testing/src/index.ts | 1 + .../testing/src/mocks/hybrid-auth.mock.ts | 13 +- packages/testing/src/mocks/index.ts | 2 +- 30 files changed, 284 insertions(+), 36 deletions(-) create mode 100644 apps/sim/app/api/workflows/[id]/execute/response-block.test.ts diff --git a/apps/sim/app/api/a2a/serve/[agentId]/route.ts b/apps/sim/app/api/a2a/serve/[agentId]/route.ts index 20cb4879e3..5ac5ac4ae3 100644 --- a/apps/sim/app/api/a2a/serve/[agentId]/route.ts +++ b/apps/sim/app/api/a2a/serve/[agentId]/route.ts @@ -13,7 +13,7 @@ import { isTerminalState, parseWorkflowSSEChunk, } from '@/lib/a2a/utils' -import { type AuthResult, checkHybridAuth } from '@/lib/auth/hybrid' +import { type AuthResult, AuthType, checkHybridAuth } from '@/lib/auth/hybrid' import { acquireLock, getRedisClient, releaseLock } from '@/lib/core/config/redis' import { validateUrlWithDNS } from '@/lib/core/security/input-validation.server' import { SSE_HEADERS } from '@/lib/core/utils/sse' @@ -242,9 +242,9 @@ export async function POST(request: NextRequest, { params }: { params: Promise { }) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth, })) diff --git a/apps/sim/app/api/auth/oauth/token/route.test.ts b/apps/sim/app/api/auth/oauth/token/route.test.ts index 7054576c3c..4f3d06d3a5 100644 --- a/apps/sim/app/api/auth/oauth/token/route.test.ts +++ b/apps/sim/app/api/auth/oauth/token/route.test.ts @@ -51,6 +51,7 @@ vi.mock('@/lib/auth/credential-access', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkHybridAuth: vi.fn(), checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth, checkInternalAuth: vi.fn(), diff --git a/apps/sim/app/api/auth/oauth/token/route.ts b/apps/sim/app/api/auth/oauth/token/route.ts index d8b1b45741..fcc6f12870 100644 --- a/apps/sim/app/api/auth/oauth/token/route.ts +++ b/apps/sim/app/api/auth/oauth/token/route.ts @@ -2,7 +2,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { authorizeCredentialUse } from '@/lib/auth/credential-access' -import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' +import { AuthType, checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' import { getCredential, getOAuthToken, refreshTokenIfNeeded } from '@/app/api/auth/oauth/utils' @@ -72,7 +72,7 @@ export async function POST(request: NextRequest) { }) const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) - if (!auth.success || auth.authType !== 'session' || !auth.userId) { + if (!auth.success || auth.authType !== AuthType.SESSION || !auth.userId) { logger.warn(`[${requestId}] Unauthorized request for credentialAccountUserId path`, { success: auth.success, authType: auth.authType, @@ -202,7 +202,7 @@ export async function GET(request: NextRequest) { credentialId, requireWorkflowIdForInternal: false, }) - if (!authz.ok || authz.authType !== 'session' || !authz.credentialOwnerUserId) { + if (!authz.ok || authz.authType !== AuthType.SESSION || !authz.credentialOwnerUserId) { return NextResponse.json({ error: authz.error || 'Unauthorized' }, { status: 403 }) } diff --git a/apps/sim/app/api/files/delete/route.test.ts b/apps/sim/app/api/files/delete/route.test.ts index e63955015d..60149483de 100644 --- a/apps/sim/app/api/files/delete/route.test.ts +++ b/apps/sim/app/api/files/delete/route.test.ts @@ -91,6 +91,7 @@ vi.mock('@/lib/auth', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkHybridAuth: mocks.mockCheckHybridAuth, checkSessionOrInternalAuth: mocks.mockCheckSessionOrInternalAuth, checkInternalAuth: mocks.mockCheckInternalAuth, diff --git a/apps/sim/app/api/files/parse/route.test.ts b/apps/sim/app/api/files/parse/route.test.ts index 51aeecf3ee..02baaffb6c 100644 --- a/apps/sim/app/api/files/parse/route.test.ts +++ b/apps/sim/app/api/files/parse/route.test.ts @@ -106,6 +106,7 @@ vi.mock('@/lib/auth', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkInternalAuth: mockCheckInternalAuth, checkHybridAuth: mockCheckHybridAuth, checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth, diff --git a/apps/sim/app/api/files/serve/[...path]/route.test.ts b/apps/sim/app/api/files/serve/[...path]/route.test.ts index 390348c4c0..bc5b35647c 100644 --- a/apps/sim/app/api/files/serve/[...path]/route.test.ts +++ b/apps/sim/app/api/files/serve/[...path]/route.test.ts @@ -49,6 +49,7 @@ vi.mock('fs/promises', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth, })) diff --git a/apps/sim/app/api/files/upload/route.test.ts b/apps/sim/app/api/files/upload/route.test.ts index a2361fd506..75c06b429f 100644 --- a/apps/sim/app/api/files/upload/route.test.ts +++ b/apps/sim/app/api/files/upload/route.test.ts @@ -100,6 +100,7 @@ vi.mock('@/lib/auth', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkHybridAuth: mocks.mockCheckHybridAuth, checkSessionOrInternalAuth: mocks.mockCheckSessionOrInternalAuth, checkInternalAuth: mocks.mockCheckInternalAuth, diff --git a/apps/sim/app/api/function/execute/route.test.ts b/apps/sim/app/api/function/execute/route.test.ts index 70a56b06b1..b57c8fdb77 100644 --- a/apps/sim/app/api/function/execute/route.test.ts +++ b/apps/sim/app/api/function/execute/route.test.ts @@ -18,6 +18,7 @@ vi.mock('@/lib/execution/isolated-vm', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkInternalAuth: mockCheckInternalAuth, })) diff --git a/apps/sim/app/api/knowledge/[id]/tag-definitions/route.ts b/apps/sim/app/api/knowledge/[id]/tag-definitions/route.ts index cbc5ac90e6..ad1c7f4ddd 100644 --- a/apps/sim/app/api/knowledge/[id]/tag-definitions/route.ts +++ b/apps/sim/app/api/knowledge/[id]/tag-definitions/route.ts @@ -2,7 +2,7 @@ import { randomUUID } from 'crypto' import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' -import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' +import { AuthType, checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { SUPPORTED_FIELD_TYPES } from '@/lib/knowledge/constants' import { createTagDefinition, getTagDefinitions } from '@/lib/knowledge/tags/service' import { checkKnowledgeBaseAccess } from '@/app/api/knowledge/utils' @@ -25,7 +25,7 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ id: } // For session auth, verify KB access. Internal JWT is trusted. - if (auth.authType === 'session' && auth.userId) { + if (auth.authType === AuthType.SESSION && auth.userId) { const accessCheck = await checkKnowledgeBaseAccess(knowledgeBaseId, auth.userId) if (!accessCheck.hasAccess) { return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) @@ -62,7 +62,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id: } // For session auth, verify KB access. Internal JWT is trusted. - if (auth.authType === 'session' && auth.userId) { + if (auth.authType === AuthType.SESSION && auth.userId) { const accessCheck = await checkKnowledgeBaseAccess(knowledgeBaseId, auth.userId) if (!accessCheck.hasAccess) { return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) diff --git a/apps/sim/app/api/knowledge/search/route.test.ts b/apps/sim/app/api/knowledge/search/route.test.ts index d257bb7165..d736edc44e 100644 --- a/apps/sim/app/api/knowledge/search/route.test.ts +++ b/apps/sim/app/api/knowledge/search/route.test.ts @@ -68,6 +68,7 @@ vi.mock('@sim/db', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth, })) diff --git a/apps/sim/app/api/mcp/serve/[serverId]/route.test.ts b/apps/sim/app/api/mcp/serve/[serverId]/route.test.ts index 97f887e955..77dd1adebf 100644 --- a/apps/sim/app/api/mcp/serve/[serverId]/route.test.ts +++ b/apps/sim/app/api/mcp/serve/[serverId]/route.test.ts @@ -59,6 +59,7 @@ vi.mock('@sim/db/schema', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkHybridAuth: mockCheckHybridAuth, checkSessionOrInternalAuth: vi.fn(), checkInternalAuth: vi.fn(), diff --git a/apps/sim/app/api/mcp/serve/[serverId]/route.ts b/apps/sim/app/api/mcp/serve/[serverId]/route.ts index 99f2a83089..29c7012097 100644 --- a/apps/sim/app/api/mcp/serve/[serverId]/route.ts +++ b/apps/sim/app/api/mcp/serve/[serverId]/route.ts @@ -19,7 +19,7 @@ import { workflow, workflowMcpServer, workflowMcpTool } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { and, eq } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' -import { type AuthResult, checkHybridAuth } from '@/lib/auth/hybrid' +import { type AuthResult, AuthType, checkHybridAuth } from '@/lib/auth/hybrid' import { generateInternalToken } from '@/lib/auth/internal' import { getMaxExecutionTimeout } from '@/lib/core/execution-limits' import { getInternalApiBaseUrl } from '@/lib/core/utils/urls' @@ -137,7 +137,7 @@ export async function POST(request: NextRequest, { params }: { params: Promise ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkSessionOrInternalAuth: (...args: unknown[]) => mockCheckSessionOrInternalAuth(...args), })) diff --git a/apps/sim/app/api/users/me/usage-limits/route.ts b/apps/sim/app/api/users/me/usage-limits/route.ts index 26db257efc..19e3403da0 100644 --- a/apps/sim/app/api/users/me/usage-limits/route.ts +++ b/apps/sim/app/api/users/me/usage-limits/route.ts @@ -1,6 +1,6 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { AuthType, checkHybridAuth } from '@/lib/auth/hybrid' import { checkServerSideUsageLimits } from '@/lib/billing' import { getHighestPrioritySubscription } from '@/lib/billing/core/subscription' import { getEffectiveCurrentPeriodCost } from '@/lib/billing/core/usage' @@ -20,7 +20,7 @@ export async function GET(request: NextRequest) { const userSubscription = await getHighestPrioritySubscription(authenticatedUserId) const rateLimiter = new RateLimiter() - const triggerType = auth.authType === 'api_key' ? 'api' : 'manual' + const triggerType = auth.authType === AuthType.API_KEY ? 'api' : 'manual' const [syncStatus, asyncStatus] = await Promise.all([ rateLimiter.getRateLimitStatusWithSubscription( authenticatedUserId, diff --git a/apps/sim/app/api/workflows/[id]/chat/status/route.test.ts b/apps/sim/app/api/workflows/[id]/chat/status/route.test.ts index 3456e372e8..3be0cba6e2 100644 --- a/apps/sim/app/api/workflows/[id]/chat/status/route.test.ts +++ b/apps/sim/app/api/workflows/[id]/chat/status/route.test.ts @@ -49,6 +49,7 @@ vi.mock('@sim/db/schema', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth, })) diff --git a/apps/sim/app/api/workflows/[id]/execute/response-block.test.ts b/apps/sim/app/api/workflows/[id]/execute/response-block.test.ts new file mode 100644 index 0000000000..16808cca6f --- /dev/null +++ b/apps/sim/app/api/workflows/[id]/execute/response-block.test.ts @@ -0,0 +1,115 @@ +/** + * Tests that internal JWT callers receive the standard response format + * even when the child workflow has a Response block. + * + * @vitest-environment node + */ + +import { beforeEach, describe, expect, it } from 'vitest' +import { AuthType } from '@/lib/auth/hybrid' +import type { ExecutionResult } from '@/lib/workflows/types' +import { createHttpResponseFromBlock, workflowHasResponseBlock } from '@/lib/workflows/utils' + +function buildExecutionResult(overrides: Partial = {}): ExecutionResult { + return { + success: true, + output: { data: { issues: [] }, status: 200, headers: {} }, + logs: [ + { + blockId: 'response-1', + blockType: 'response', + blockName: 'Response', + success: true, + output: { data: { issues: [] }, status: 200, headers: {} }, + startedAt: '2026-01-01T00:00:00Z', + endedAt: '2026-01-01T00:00:01Z', + }, + ], + metadata: { + duration: 500, + startTime: '2026-01-01T00:00:00Z', + endTime: '2026-01-01T00:00:01Z', + }, + ...overrides, + } +} + +describe('Response block gating by auth type', () => { + let resultWithResponseBlock: ExecutionResult + + beforeEach(() => { + resultWithResponseBlock = buildExecutionResult() + }) + + it('should detect a Response block in execution result', () => { + expect(workflowHasResponseBlock(resultWithResponseBlock)).toBe(true) + }) + + it('should not detect a Response block when none exists', () => { + const resultWithoutResponseBlock = buildExecutionResult({ + output: { result: 'hello' }, + logs: [ + { + blockId: 'agent-1', + blockType: 'agent', + blockName: 'Agent', + success: true, + output: { result: 'hello' }, + startedAt: '2026-01-01T00:00:00Z', + endedAt: '2026-01-01T00:00:01Z', + }, + ], + }) + expect(workflowHasResponseBlock(resultWithoutResponseBlock)).toBe(false) + }) + + it('should skip Response block formatting for internal JWT callers', () => { + const authType = AuthType.INTERNAL_JWT + const hasResponseBlock = workflowHasResponseBlock(resultWithResponseBlock) + + expect(hasResponseBlock).toBe(true) + + // This mirrors the route.ts condition: + // if (auth.authType !== AuthType.INTERNAL_JWT && workflowHasResponseBlock(...)) + const shouldFormatAsResponseBlock = authType !== AuthType.INTERNAL_JWT && hasResponseBlock + expect(shouldFormatAsResponseBlock).toBe(false) + }) + + it('should apply Response block formatting for API key callers', () => { + const authType = AuthType.API_KEY + const hasResponseBlock = workflowHasResponseBlock(resultWithResponseBlock) + + const shouldFormatAsResponseBlock = authType !== AuthType.INTERNAL_JWT && hasResponseBlock + expect(shouldFormatAsResponseBlock).toBe(true) + + const response = createHttpResponseFromBlock(resultWithResponseBlock) + expect(response.status).toBe(200) + }) + + it('should apply Response block formatting for session callers', () => { + const authType = AuthType.SESSION + const hasResponseBlock = workflowHasResponseBlock(resultWithResponseBlock) + + const shouldFormatAsResponseBlock = authType !== AuthType.INTERNAL_JWT && hasResponseBlock + expect(shouldFormatAsResponseBlock).toBe(true) + }) + + it('should return raw user data via createHttpResponseFromBlock', async () => { + const response = createHttpResponseFromBlock(resultWithResponseBlock) + const body = await response.json() + + // Response block returns the user-defined data directly (no success/executionId wrapper) + expect(body).toEqual({ issues: [] }) + expect(body.success).toBeUndefined() + expect(body.executionId).toBeUndefined() + }) + + it('should respect custom status codes from Response block', () => { + const result = buildExecutionResult({ + output: { data: { error: 'Not found' }, status: 404, headers: {} }, + }) + + const response = createHttpResponseFromBlock(result) + expect(response.status).toBe(404) + }) +}) diff --git a/apps/sim/app/api/workflows/[id]/execute/route.ts b/apps/sim/app/api/workflows/[id]/execute/route.ts index 3c1e27080e..6f469e2486 100644 --- a/apps/sim/app/api/workflows/[id]/execute/route.ts +++ b/apps/sim/app/api/workflows/[id]/execute/route.ts @@ -2,7 +2,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { validate as uuidValidate, v4 as uuidv4 } from 'uuid' import { z } from 'zod' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { AuthType, checkHybridAuth } from '@/lib/auth/hybrid' import { getJobQueue, shouldExecuteInline } from '@/lib/core/async-jobs' import { createTimeoutAbortController, @@ -322,7 +322,8 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id: ) } - const defaultTriggerType = isPublicApiAccess || auth.authType === 'api_key' ? 'api' : 'manual' + const defaultTriggerType = + isPublicApiAccess || auth.authType === AuthType.API_KEY ? 'api' : 'manual' const { selectedOutputs, @@ -381,7 +382,9 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id: // For API key and internal JWT auth, the entire body is the input (except for our control fields) // For session auth, the input is explicitly provided in the input field const input = - isPublicApiAccess || auth.authType === 'api_key' || auth.authType === 'internal_jwt' + isPublicApiAccess || + auth.authType === AuthType.API_KEY || + auth.authType === AuthType.INTERNAL_JWT ? (() => { const { selectedOutputs, @@ -407,7 +410,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id: // Public API callers always execute the deployed state, never the draft. const shouldUseDraftState = isPublicApiAccess ? false - : (useDraftState ?? auth.authType === 'session') + : (useDraftState ?? auth.authType === AuthType.SESSION) const streamHeader = req.headers.get('X-Stream-Response') === 'true' const enableSSE = streamHeader || streamParam === true const executionModeHeader = req.headers.get('X-Execution-Mode') @@ -440,7 +443,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id: // Client-side sessions and personal API keys bill/permission-check the // authenticated user, not the workspace billed account. const useAuthenticatedUserAsActor = - isClientSession || (auth.authType === 'api_key' && auth.apiKeyType === 'personal') + isClientSession || (auth.authType === AuthType.API_KEY && auth.apiKeyType === 'personal') // Authorization fetches the full workflow record and checks workspace permissions. // Run it first so we can pass the record to preprocessing (eliminates a duplicate DB query). @@ -670,8 +673,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id: const resultWithBase64 = { ...result, output: outputWithBase64 } - const hasResponseBlock = workflowHasResponseBlock(resultWithBase64) - if (hasResponseBlock) { + if (auth.authType !== AuthType.INTERNAL_JWT && workflowHasResponseBlock(resultWithBase64)) { return createHttpResponseFromBlock(resultWithBase64) } diff --git a/apps/sim/app/api/workflows/[id]/form/status/route.test.ts b/apps/sim/app/api/workflows/[id]/form/status/route.test.ts index 8099d2d844..4e16e491fd 100644 --- a/apps/sim/app/api/workflows/[id]/form/status/route.test.ts +++ b/apps/sim/app/api/workflows/[id]/form/status/route.test.ts @@ -44,6 +44,7 @@ vi.mock('@sim/db/schema', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth, })) diff --git a/apps/sim/app/api/workflows/[id]/route.test.ts b/apps/sim/app/api/workflows/[id]/route.test.ts index fba05c92c9..d886e27d46 100644 --- a/apps/sim/app/api/workflows/[id]/route.test.ts +++ b/apps/sim/app/api/workflows/[id]/route.test.ts @@ -43,6 +43,7 @@ vi.mock('@/lib/auth', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkHybridAuth: (...args: unknown[]) => mockCheckHybridAuth(...args), checkSessionOrInternalAuth: (...args: unknown[]) => mockCheckSessionOrInternalAuth(...args), })) diff --git a/apps/sim/app/api/workflows/[id]/route.ts b/apps/sim/app/api/workflows/[id]/route.ts index 140cc8ef53..19d89e8eeb 100644 --- a/apps/sim/app/api/workflows/[id]/route.ts +++ b/apps/sim/app/api/workflows/[id]/route.ts @@ -5,7 +5,7 @@ import { and, eq, isNull, ne } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { AuditAction, AuditResourceType, recordAudit } from '@/lib/audit/log' -import { checkHybridAuth, checkSessionOrInternalAuth } from '@/lib/auth/hybrid' +import { AuthType, checkHybridAuth, checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { env } from '@/lib/core/config/env' import { PlatformEvents } from '@/lib/core/telemetry' import { generateRequestId } from '@/lib/core/utils/request' @@ -39,7 +39,7 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } - const isInternalCall = auth.authType === 'internal_jwt' + const isInternalCall = auth.authType === AuthType.INTERNAL_JWT const userId = auth.userId || null let workflowData = await getWorkflowById(workflowId) diff --git a/apps/sim/app/api/workflows/[id]/variables/route.test.ts b/apps/sim/app/api/workflows/[id]/variables/route.test.ts index 68c863502a..99a07d6f12 100644 --- a/apps/sim/app/api/workflows/[id]/variables/route.test.ts +++ b/apps/sim/app/api/workflows/[id]/variables/route.test.ts @@ -18,6 +18,7 @@ const { mockCheckSessionOrInternalAuth, mockAuthorizeWorkflowByWorkspacePermissi vi.mock('@/lib/audit/log', () => auditMock) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth, })) diff --git a/apps/sim/app/api/workflows/route.test.ts b/apps/sim/app/api/workflows/route.test.ts index e1b83bdb0e..bff62acfc8 100644 --- a/apps/sim/app/api/workflows/route.test.ts +++ b/apps/sim/app/api/workflows/route.test.ts @@ -64,6 +64,7 @@ vi.mock('@/lib/audit/log', () => ({ })) vi.mock('@/lib/auth/hybrid', () => ({ + AuthType: { SESSION: 'session', API_KEY: 'api_key', INTERNAL_JWT: 'internal_jwt' }, checkHybridAuth: vi.fn(), checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth, checkInternalAuth: vi.fn(), diff --git a/apps/sim/lib/auth/credential-access.ts b/apps/sim/lib/auth/credential-access.ts index b4ecc18476..5b4ba2edd1 100644 --- a/apps/sim/lib/auth/credential-access.ts +++ b/apps/sim/lib/auth/credential-access.ts @@ -2,13 +2,13 @@ import { db } from '@sim/db' import { account, credential, credentialMember, workflow as workflowTable } from '@sim/db/schema' import { and, eq } from 'drizzle-orm' import type { NextRequest } from 'next/server' -import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' +import { AuthType, checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils' export interface CredentialAccessResult { ok: boolean error?: string - authType?: 'session' | 'internal_jwt' + authType?: typeof AuthType.SESSION | typeof AuthType.INTERNAL_JWT requesterUserId?: string credentialOwnerUserId?: string workspaceId?: string @@ -39,7 +39,7 @@ export async function authorizeCredentialUse( return { ok: false, error: auth.error || 'Authentication required' } } - const actingUserId = auth.authType === 'internal_jwt' ? callerUserId : auth.userId + const actingUserId = auth.authType === AuthType.INTERNAL_JWT ? callerUserId : auth.userId const [workflowContext] = workflowId ? await db @@ -217,7 +217,7 @@ export async function authorizeCredentialUse( return { ok: false, error: 'Credential not found' } } - if (auth.authType === 'internal_jwt') { + if (auth.authType === AuthType.INTERNAL_JWT) { return { ok: false, error: 'workflowId is required' } } diff --git a/apps/sim/lib/auth/hybrid.ts b/apps/sim/lib/auth/hybrid.ts index 0cc00e72e9..c3c03acb87 100644 --- a/apps/sim/lib/auth/hybrid.ts +++ b/apps/sim/lib/auth/hybrid.ts @@ -6,12 +6,20 @@ import { verifyInternalToken } from '@/lib/auth/internal' const logger = createLogger('HybridAuth') +export const AuthType = { + SESSION: 'session', + API_KEY: 'api_key', + INTERNAL_JWT: 'internal_jwt', +} as const + +export type AuthTypeValue = (typeof AuthType)[keyof typeof AuthType] + export interface AuthResult { success: boolean userId?: string userName?: string | null userEmail?: string | null - authType?: 'session' | 'api_key' | 'internal_jwt' + authType?: AuthTypeValue apiKeyType?: 'personal' | 'workspace' error?: string } @@ -46,14 +54,14 @@ async function resolveUserFromJwt( } if (userId) { - return { success: true, userId, authType: 'internal_jwt' } + return { success: true, userId, authType: AuthType.INTERNAL_JWT } } if (options.requireWorkflowId !== false) { return { success: false, error: 'userId required for internal JWT calls' } } - return { success: true, authType: 'internal_jwt' } + return { success: true, authType: AuthType.INTERNAL_JWT } } /** @@ -146,7 +154,7 @@ export async function checkSessionOrInternalAuth( userId: session.user.id, userName: session.user.name, userEmail: session.user.email, - authType: 'session', + authType: AuthType.SESSION, } } @@ -195,7 +203,7 @@ export async function checkHybridAuth( userId: session.user.id, userName: session.user.name, userEmail: session.user.email, - authType: 'session', + authType: AuthType.SESSION, } } @@ -208,7 +216,7 @@ export async function checkHybridAuth( return { success: true, userId: result.userId!, - authType: 'api_key', + authType: AuthType.API_KEY, apiKeyType: result.keyType, } } diff --git a/apps/sim/tools/workflow/executor.test.ts b/apps/sim/tools/workflow/executor.test.ts index 14b4261904..e49020ef0c 100644 --- a/apps/sim/tools/workflow/executor.test.ts +++ b/apps/sim/tools/workflow/executor.test.ts @@ -242,6 +242,101 @@ describe('workflowExecutorTool', () => { }) }) + describe('transformResponse', () => { + const transformResponse = workflowExecutorTool.transformResponse! + + function mockResponse(body: any, status = 200): Response { + return { + ok: status >= 200 && status < 300, + status, + json: async () => body, + } as unknown as Response + } + + it.concurrent('should parse standard format response', async () => { + const body = { + success: true, + executionId: '550e8400-e29b-41d4-a716-446655440000', + output: { result: 'hello' }, + metadata: { duration: 500 }, + } + + const result = await transformResponse(mockResponse(body)) + + expect(result.success).toBe(true) + expect(result.output).toEqual({ result: 'hello' }) + expect(result.duration).toBe(500) + expect(result.error).toBeUndefined() + }) + + it.concurrent('should parse standard format failure', async () => { + const body = { + success: false, + executionId: '550e8400-e29b-41d4-a716-446655440000', + output: {}, + error: 'Something went wrong', + } + + const result = await transformResponse(mockResponse(body)) + + expect(result.success).toBe(false) + expect(result.error).toBe('Something went wrong') + }) + + it.concurrent('should default success to false when missing', async () => { + const body = { output: { data: 'test' } } + + const result = await transformResponse(mockResponse(body)) + + expect(result.success).toBe(false) + expect(result.output).toEqual({ data: 'test' }) + }) + + it.concurrent('should default output to empty object when missing', async () => { + const body = { success: true } + + const result = await transformResponse(mockResponse(body)) + + expect(result.success).toBe(true) + expect(result.output).toEqual({}) + expect(result.result).toEqual({}) + }) + + it.concurrent('should extract metadata duration', async () => { + const body = { + success: true, + output: {}, + metadata: { duration: 1234 }, + } + + const result = await transformResponse(mockResponse(body)) + + expect(result.duration).toBe(1234) + }) + + it.concurrent('should default duration to 0 when metadata is missing', async () => { + const body = { success: true, output: {} } + + const result = await transformResponse(mockResponse(body)) + + expect(result.duration).toBe(0) + }) + + it.concurrent('should extract workflowId and workflowName', async () => { + const body = { + success: true, + output: {}, + workflowId: 'wf-123', + workflowName: 'My Workflow', + } + + const result = await transformResponse(mockResponse(body)) + + expect(result.childWorkflowId).toBe('wf-123') + expect(result.childWorkflowName).toBe('My Workflow') + }) + }) + describe('tool metadata', () => { it.concurrent('should have correct id', () => { expect(workflowExecutorTool.id).toBe('workflow_executor') diff --git a/packages/testing/src/index.ts b/packages/testing/src/index.ts index 48881879ac..ce84686a15 100644 --- a/packages/testing/src/index.ts +++ b/packages/testing/src/index.ts @@ -45,6 +45,7 @@ export * from './assertions' export * from './builders' export * from './factories' export { + AuthTypeMock, auditMock, clearRedisMocks, createEnvMock, diff --git a/packages/testing/src/mocks/hybrid-auth.mock.ts b/packages/testing/src/mocks/hybrid-auth.mock.ts index 7ddb2ecb1e..add5babbcc 100644 --- a/packages/testing/src/mocks/hybrid-auth.mock.ts +++ b/packages/testing/src/mocks/hybrid-auth.mock.ts @@ -6,12 +6,22 @@ import { vi } from 'vitest' import type { MockUser } from './auth.mock' import { defaultMockUser } from './auth.mock' +/** + * Auth type constants matching @/lib/auth/hybrid AuthType. + * Include this in vi.mock() factories so route code can reference AuthType.*. + */ +export const AuthTypeMock = { + SESSION: 'session', + API_KEY: 'api_key', + INTERNAL_JWT: 'internal_jwt', +} as const + interface HybridAuthResponse { success: boolean userId?: string userName?: string | null userEmail?: string | null - authType?: 'session' | 'api_key' | 'internal_jwt' + authType?: (typeof AuthTypeMock)[keyof typeof AuthTypeMock] error?: string } @@ -46,6 +56,7 @@ export function mockHybridAuth(user: MockUser = defaultMockUser): MockHybridAuth const mockCheckInternalAuth = vi.fn<() => Promise>() vi.doMock('@/lib/auth/hybrid', () => ({ + AuthType: AuthTypeMock, checkHybridAuth: mockCheckHybridAuth, checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth, checkInternalAuth: mockCheckInternalAuth, diff --git a/packages/testing/src/mocks/index.ts b/packages/testing/src/mocks/index.ts index f2c3fc6730..69a2e5984d 100644 --- a/packages/testing/src/mocks/index.ts +++ b/packages/testing/src/mocks/index.ts @@ -64,7 +64,7 @@ export { setupGlobalFetchMock, } from './fetch.mock' // Hybrid auth mocks -export { type MockHybridAuthResult, mockHybridAuth } from './hybrid-auth.mock' +export { AuthTypeMock, type MockHybridAuthResult, mockHybridAuth } from './hybrid-auth.mock' // Logger mocks export { clearLoggerMocks, createMockLogger, getLoggerCalls, loggerMock } from './logger.mock' // Redis mocks From a8bbab2d21fe552030340201919bfde11440b1e8 Mon Sep 17 00:00:00 2001 From: Waleed Date: Thu, 12 Mar 2026 21:08:58 -0700 Subject: [PATCH 4/5] feat(google-ads): add google ads integration for campaign and ad performance queries (#3360) * feat(google-ads): add google ads integration for campaign and ad performance queries * fix(google-ads): add input validation for GAQL query parameters * fix(google-ads): remove deprecated pageSize param, fix searchSettings nesting, add missing date ranges * fix(google-ads): validate managerCustomerId before use in login-customer-id header * chore(docs): regenerate docs after google ads integration * fix(google-ads): use centralized scope utilities and add type re-export - Replace hardcoded scopes in auth.ts with getCanonicalScopesForProvider('google-ads') - Replace hardcoded requiredScopes in block with getScopesForService('google-ads') - Add type re-export from index.ts barrel Co-Authored-By: Claude Opus 4.6 * fix(google-ads): add userinfo scopes to oauth provider config Align google-ads with all other Google services by including userinfo.email and userinfo.profile scopes in the centralized OAUTH_PROVIDERS config. Co-Authored-By: Claude Opus 4.6 * lint --------- Co-authored-by: Claude Opus 4.6 --- apps/docs/components/icons.tsx | 21 ++ apps/docs/components/ui/icon-mapping.ts | 2 + .../docs/content/docs/en/tools/google_ads.mdx | 192 ++++++++++++ apps/docs/content/docs/en/tools/meta.json | 1 + apps/sim/blocks/blocks/google_ads.ts | 294 ++++++++++++++++++ apps/sim/blocks/registry.ts | 2 + apps/sim/components/icons.tsx | 21 ++ apps/sim/lib/auth/auth.ts | 36 +++ apps/sim/lib/oauth/oauth.ts | 13 + apps/sim/lib/oauth/types.ts | 2 + apps/sim/lib/oauth/utils.ts | 1 + apps/sim/tools/google_ads/ad_performance.ts | 211 +++++++++++++ .../tools/google_ads/campaign_performance.ts | 182 +++++++++++ apps/sim/tools/google_ads/index.ts | 17 + apps/sim/tools/google_ads/list_ad_groups.ts | 167 ++++++++++ apps/sim/tools/google_ads/list_campaigns.ts | 168 ++++++++++ apps/sim/tools/google_ads/list_customers.ts | 84 +++++ apps/sim/tools/google_ads/search.ts | 130 ++++++++ apps/sim/tools/google_ads/types.ts | 187 +++++++++++ apps/sim/tools/registry.ts | 14 + 20 files changed, 1745 insertions(+) create mode 100644 apps/docs/content/docs/en/tools/google_ads.mdx create mode 100644 apps/sim/blocks/blocks/google_ads.ts create mode 100644 apps/sim/tools/google_ads/ad_performance.ts create mode 100644 apps/sim/tools/google_ads/campaign_performance.ts create mode 100644 apps/sim/tools/google_ads/index.ts create mode 100644 apps/sim/tools/google_ads/list_ad_groups.ts create mode 100644 apps/sim/tools/google_ads/list_campaigns.ts create mode 100644 apps/sim/tools/google_ads/list_customers.ts create mode 100644 apps/sim/tools/google_ads/search.ts create mode 100644 apps/sim/tools/google_ads/types.ts diff --git a/apps/docs/components/icons.tsx b/apps/docs/components/icons.tsx index 2f7be8184b..0db577837d 100644 --- a/apps/docs/components/icons.tsx +++ b/apps/docs/components/icons.tsx @@ -3572,6 +3572,27 @@ export const ResendIcon = (props: SVGProps) => ( ) +export const GoogleAdsIcon = (props: SVGProps) => ( + + + + + + + + + +) + export const GoogleBigQueryIcon = (props: SVGProps) => ( = { gitlab: GitLabIcon, gmail_v2: GmailIcon, gong: GongIcon, + google_ads: GoogleAdsIcon, google_bigquery: GoogleBigQueryIcon, google_books: GoogleBooksIcon, google_calendar_v2: GoogleCalendarIcon, diff --git a/apps/docs/content/docs/en/tools/google_ads.mdx b/apps/docs/content/docs/en/tools/google_ads.mdx new file mode 100644 index 0000000000..cadc9af6fe --- /dev/null +++ b/apps/docs/content/docs/en/tools/google_ads.mdx @@ -0,0 +1,192 @@ +--- +title: Google Ads +description: Query campaigns, ad groups, and performance metrics +--- + +import { BlockInfoCard } from "@/components/ui/block-info-card" + + + +{/* MANUAL-CONTENT-START:intro */} +[Google Ads](https://ads.google.com) is Google's online advertising platform that lets businesses create ads to reach customers across Google Search, YouTube, Gmail, and millions of partner websites. It supports campaign types including Search, Display, Video, Shopping, and Performance Max, with detailed targeting, bidding strategies, and performance analytics. + +In Sim, the Google Ads integration enables your agents to query campaign data, monitor ad group performance, and pull detailed metrics using the Google Ads Query Language (GAQL). This supports use cases such as automated performance reporting, budget monitoring, campaign health checks, and data-driven optimization workflows. By connecting Sim with Google Ads, your agents can retrieve real-time advertising data and act on insights without manual dashboard navigation. +{/* MANUAL-CONTENT-END */} + + +## Usage Instructions + +Connect to Google Ads to list accessible accounts, list campaigns, view ad group details, get performance metrics, and run custom GAQL queries. + + + +## Tools + +### `google_ads_list_customers` + +List all Google Ads customer accounts accessible by the authenticated user + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `developerToken` | string | Yes | Google Ads API developer token | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `customerIds` | array | List of accessible customer IDs | +| `totalCount` | number | Total number of accessible customer accounts | + +### `google_ads_search` + +Run a custom Google Ads Query Language (GAQL) query + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `customerId` | string | Yes | Google Ads customer ID \(numeric, no dashes\) | +| `developerToken` | string | Yes | Google Ads API developer token | +| `managerCustomerId` | string | No | Manager account customer ID \(if accessing via manager account\) | +| `query` | string | Yes | GAQL query to execute | +| `pageToken` | string | No | Page token for pagination | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `results` | json | Array of result objects from the GAQL query | +| `totalResultsCount` | number | Total number of matching results | +| `nextPageToken` | string | Token for the next page of results | + +### `google_ads_list_campaigns` + +List campaigns in a Google Ads account with optional status filtering + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `customerId` | string | Yes | Google Ads customer ID \(numeric, no dashes\) | +| `developerToken` | string | Yes | Google Ads API developer token | +| `managerCustomerId` | string | No | Manager account customer ID \(if accessing via manager account\) | +| `status` | string | No | Filter by campaign status \(ENABLED, PAUSED, REMOVED\) | +| `limit` | number | No | Maximum number of campaigns to return | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `campaigns` | array | List of campaigns in the account | +| ↳ `id` | string | Campaign ID | +| ↳ `name` | string | Campaign name | +| ↳ `status` | string | Campaign status \(ENABLED, PAUSED, REMOVED\) | +| ↳ `channelType` | string | Advertising channel type \(SEARCH, DISPLAY, SHOPPING, VIDEO, PERFORMANCE_MAX\) | +| ↳ `startDate` | string | Campaign start date \(YYYY-MM-DD\) | +| ↳ `endDate` | string | Campaign end date \(YYYY-MM-DD\) | +| ↳ `budgetAmountMicros` | string | Daily budget in micros \(divide by 1,000,000 for currency value\) | +| `totalCount` | number | Total number of campaigns returned | + +### `google_ads_campaign_performance` + +Get performance metrics for Google Ads campaigns over a date range + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `customerId` | string | Yes | Google Ads customer ID \(numeric, no dashes\) | +| `developerToken` | string | Yes | Google Ads API developer token | +| `managerCustomerId` | string | No | Manager account customer ID \(if accessing via manager account\) | +| `campaignId` | string | No | Filter by specific campaign ID | +| `dateRange` | string | No | Predefined date range \(LAST_7_DAYS, LAST_30_DAYS, THIS_MONTH, LAST_MONTH, TODAY, YESTERDAY\) | +| `startDate` | string | No | Custom start date in YYYY-MM-DD format | +| `endDate` | string | No | Custom end date in YYYY-MM-DD format | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `campaigns` | array | Campaign performance data broken down by date | +| ↳ `id` | string | Campaign ID | +| ↳ `name` | string | Campaign name | +| ↳ `status` | string | Campaign status | +| ↳ `impressions` | string | Number of impressions | +| ↳ `clicks` | string | Number of clicks | +| ↳ `costMicros` | string | Cost in micros \(divide by 1,000,000 for currency value\) | +| ↳ `ctr` | number | Click-through rate \(0.0 to 1.0\) | +| ↳ `conversions` | number | Number of conversions | +| ↳ `date` | string | Date for this row \(YYYY-MM-DD\) | +| `totalCount` | number | Total number of result rows | + +### `google_ads_list_ad_groups` + +List ad groups in a Google Ads campaign + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `customerId` | string | Yes | Google Ads customer ID \(numeric, no dashes\) | +| `developerToken` | string | Yes | Google Ads API developer token | +| `managerCustomerId` | string | No | Manager account customer ID \(if accessing via manager account\) | +| `campaignId` | string | Yes | Campaign ID to list ad groups for | +| `status` | string | No | Filter by ad group status \(ENABLED, PAUSED, REMOVED\) | +| `limit` | number | No | Maximum number of ad groups to return | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `adGroups` | array | List of ad groups in the campaign | +| ↳ `id` | string | Ad group ID | +| ↳ `name` | string | Ad group name | +| ↳ `status` | string | Ad group status \(ENABLED, PAUSED, REMOVED\) | +| ↳ `type` | string | Ad group type \(SEARCH_STANDARD, DISPLAY_STANDARD, SHOPPING_PRODUCT_ADS\) | +| ↳ `campaignId` | string | Parent campaign ID | +| ↳ `campaignName` | string | Parent campaign name | +| `totalCount` | number | Total number of ad groups returned | + +### `google_ads_ad_performance` + +Get performance metrics for individual ads over a date range + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `customerId` | string | Yes | Google Ads customer ID \(numeric, no dashes\) | +| `developerToken` | string | Yes | Google Ads API developer token | +| `managerCustomerId` | string | No | Manager account customer ID \(if accessing via manager account\) | +| `campaignId` | string | No | Filter by campaign ID | +| `adGroupId` | string | No | Filter by ad group ID | +| `dateRange` | string | No | Predefined date range \(LAST_7_DAYS, LAST_30_DAYS, THIS_MONTH, LAST_MONTH, TODAY, YESTERDAY\) | +| `startDate` | string | No | Custom start date in YYYY-MM-DD format | +| `endDate` | string | No | Custom end date in YYYY-MM-DD format | +| `limit` | number | No | Maximum number of results to return | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `ads` | array | Ad performance data broken down by date | +| ↳ `adId` | string | Ad ID | +| ↳ `adGroupId` | string | Parent ad group ID | +| ↳ `adGroupName` | string | Parent ad group name | +| ↳ `campaignId` | string | Parent campaign ID | +| ↳ `campaignName` | string | Parent campaign name | +| ↳ `adType` | string | Ad type \(RESPONSIVE_SEARCH_AD, EXPANDED_TEXT_AD, etc.\) | +| ↳ `impressions` | string | Number of impressions | +| ↳ `clicks` | string | Number of clicks | +| ↳ `costMicros` | string | Cost in micros \(divide by 1,000,000 for currency value\) | +| ↳ `ctr` | number | Click-through rate \(0.0 to 1.0\) | +| ↳ `conversions` | number | Number of conversions | +| ↳ `date` | string | Date for this row \(YYYY-MM-DD\) | +| `totalCount` | number | Total number of result rows | + + diff --git a/apps/docs/content/docs/en/tools/meta.json b/apps/docs/content/docs/en/tools/meta.json index 6b9712663a..6f25b64ffe 100644 --- a/apps/docs/content/docs/en/tools/meta.json +++ b/apps/docs/content/docs/en/tools/meta.json @@ -46,6 +46,7 @@ "gitlab", "gmail", "gong", + "google_ads", "google_bigquery", "google_books", "google_calendar", diff --git a/apps/sim/blocks/blocks/google_ads.ts b/apps/sim/blocks/blocks/google_ads.ts new file mode 100644 index 0000000000..d482c72fed --- /dev/null +++ b/apps/sim/blocks/blocks/google_ads.ts @@ -0,0 +1,294 @@ +import { GoogleAdsIcon } from '@/components/icons' +import { getScopesForService } from '@/lib/oauth/utils' +import type { BlockConfig } from '@/blocks/types' +import { AuthMode } from '@/blocks/types' + +export const GoogleAdsBlock: BlockConfig = { + type: 'google_ads', + name: 'Google Ads', + description: 'Query campaigns, ad groups, and performance metrics', + longDescription: + 'Connect to Google Ads to list accessible accounts, list campaigns, view ad group details, get performance metrics, and run custom GAQL queries.', + docsLink: 'https://docs.sim.ai/tools/google_ads', + category: 'tools', + bgColor: '#E0E0E0', + icon: GoogleAdsIcon, + authMode: AuthMode.OAuth, + subBlocks: [ + { + id: 'operation', + title: 'Operation', + type: 'dropdown', + options: [ + { label: 'List Customers', id: 'list_customers' }, + { label: 'List Campaigns', id: 'list_campaigns' }, + { label: 'Campaign Performance', id: 'campaign_performance' }, + { label: 'List Ad Groups', id: 'list_ad_groups' }, + { label: 'Ad Performance', id: 'ad_performance' }, + { label: 'Custom Query (GAQL)', id: 'search' }, + ], + value: () => 'list_campaigns', + }, + + { + id: 'credential', + title: 'Google Ads Account', + type: 'oauth-input', + canonicalParamId: 'oauthCredential', + mode: 'basic', + required: true, + serviceId: 'google-ads', + requiredScopes: getScopesForService('google-ads'), + placeholder: 'Select Google Ads account', + }, + { + id: 'manualCredential', + title: 'Google Ads Account', + type: 'short-input', + canonicalParamId: 'oauthCredential', + mode: 'advanced', + placeholder: 'Enter credential ID', + required: true, + }, + + { + id: 'developerToken', + title: 'Developer Token', + type: 'short-input', + placeholder: 'Enter your Google Ads API developer token', + required: true, + password: true, + }, + + { + id: 'customerId', + title: 'Customer ID', + type: 'short-input', + placeholder: 'Google Ads customer ID (no dashes)', + condition: { + field: 'operation', + value: 'list_customers', + not: true, + }, + required: { + field: 'operation', + value: 'list_customers', + not: true, + }, + }, + + { + id: 'managerCustomerId', + title: 'Manager Customer ID', + type: 'short-input', + placeholder: 'Manager account ID (optional)', + mode: 'advanced', + condition: { + field: 'operation', + value: 'list_customers', + not: true, + }, + }, + + { + id: 'query', + title: 'GAQL Query', + type: 'long-input', + placeholder: + "SELECT campaign.id, campaign.name, metrics.impressions FROM campaign WHERE campaign.status = 'ENABLED'", + condition: { field: 'operation', value: 'search' }, + required: { field: 'operation', value: 'search' }, + wandConfig: { + enabled: true, + prompt: `Generate a Google Ads Query Language (GAQL) query based on the user's description. +The query should: +- Use valid GAQL syntax +- Include relevant metrics when asking about performance +- Include segments.date with a date range when using metrics +- Be efficient and well-formatted + +Common resources: campaign, ad_group, ad_group_ad, keyword_view, search_term_view +Common metrics: metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.ctr, metrics.conversions +Date ranges: LAST_7_DAYS, LAST_30_DAYS, THIS_MONTH, YESTERDAY + +Examples: +- "active campaigns" -> SELECT campaign.id, campaign.name, campaign.status FROM campaign WHERE campaign.status = 'ENABLED' +- "campaign spend last week" -> SELECT campaign.name, metrics.cost_micros, segments.date FROM campaign WHERE segments.date DURING LAST_7_DAYS AND campaign.status != 'REMOVED' + +Return ONLY the GAQL query - no explanations, no quotes, no extra text.`, + placeholder: 'Describe the query you want to run...', + }, + }, + + { + id: 'campaignId', + title: 'Campaign ID', + type: 'short-input', + placeholder: 'Campaign ID to filter by', + condition: { + field: 'operation', + value: ['campaign_performance', 'list_ad_groups', 'ad_performance'], + }, + required: { field: 'operation', value: 'list_ad_groups' }, + }, + + { + id: 'adGroupId', + title: 'Ad Group ID', + type: 'short-input', + placeholder: 'Ad group ID to filter by', + mode: 'advanced', + condition: { field: 'operation', value: 'ad_performance' }, + }, + + { + id: 'status', + title: 'Status Filter', + type: 'dropdown', + options: [ + { label: 'All (except removed)', id: '' }, + { label: 'Enabled', id: 'ENABLED' }, + { label: 'Paused', id: 'PAUSED' }, + ], + mode: 'advanced', + condition: { field: 'operation', value: ['list_campaigns', 'list_ad_groups'] }, + }, + + { + id: 'dateRange', + title: 'Date Range', + type: 'dropdown', + options: [ + { label: 'Last 30 Days', id: 'LAST_30_DAYS' }, + { label: 'Last 7 Days', id: 'LAST_7_DAYS' }, + { label: 'Today', id: 'TODAY' }, + { label: 'Yesterday', id: 'YESTERDAY' }, + { label: 'This Month', id: 'THIS_MONTH' }, + { label: 'Last Month', id: 'LAST_MONTH' }, + { label: 'Custom', id: 'CUSTOM' }, + ], + condition: { field: 'operation', value: ['campaign_performance', 'ad_performance'] }, + value: () => 'LAST_30_DAYS', + }, + + { + id: 'startDate', + title: 'Start Date', + type: 'short-input', + placeholder: 'YYYY-MM-DD', + condition: { field: 'dateRange', value: 'CUSTOM' }, + required: { field: 'dateRange', value: 'CUSTOM' }, + }, + + { + id: 'endDate', + title: 'End Date', + type: 'short-input', + placeholder: 'YYYY-MM-DD', + condition: { field: 'dateRange', value: 'CUSTOM' }, + required: { field: 'dateRange', value: 'CUSTOM' }, + }, + + { + id: 'pageToken', + title: 'Page Token', + type: 'short-input', + placeholder: 'Pagination token', + mode: 'advanced', + condition: { field: 'operation', value: 'search' }, + }, + + { + id: 'limit', + title: 'Limit', + type: 'short-input', + placeholder: 'Maximum results to return', + mode: 'advanced', + condition: { + field: 'operation', + value: ['list_campaigns', 'list_ad_groups', 'ad_performance'], + }, + }, + ], + tools: { + access: [ + 'google_ads_list_customers', + 'google_ads_search', + 'google_ads_list_campaigns', + 'google_ads_campaign_performance', + 'google_ads_list_ad_groups', + 'google_ads_ad_performance', + ], + config: { + tool: (params) => `google_ads_${params.operation}`, + params: (params) => { + const { oauthCredential, dateRange, limit, ...rest } = params + + const result: Record = { + ...rest, + oauthCredential, + } + + if (dateRange && dateRange !== 'CUSTOM') { + result.dateRange = dateRange + } + + if (limit !== undefined && limit !== '') { + result.limit = Number(limit) + } + + return result + }, + }, + }, + inputs: { + operation: { type: 'string', description: 'Operation to perform' }, + oauthCredential: { type: 'string', description: 'Google Ads OAuth credential' }, + developerToken: { type: 'string', description: 'Google Ads API developer token' }, + customerId: { type: 'string', description: 'Google Ads customer ID (numeric, no dashes)' }, + managerCustomerId: { type: 'string', description: 'Manager account customer ID' }, + query: { type: 'string', description: 'GAQL query to execute' }, + campaignId: { type: 'string', description: 'Campaign ID to filter by' }, + adGroupId: { type: 'string', description: 'Ad group ID to filter by' }, + status: { type: 'string', description: 'Status filter (ENABLED, PAUSED)' }, + dateRange: { type: 'string', description: 'Date range for performance queries' }, + startDate: { type: 'string', description: 'Custom start date (YYYY-MM-DD)' }, + endDate: { type: 'string', description: 'Custom end date (YYYY-MM-DD)' }, + pageToken: { type: 'string', description: 'Pagination token' }, + limit: { type: 'number', description: 'Maximum results to return' }, + }, + outputs: { + customerIds: { + type: 'json', + description: 'List of accessible customer IDs (list_customers)', + }, + results: { + type: 'json', + description: 'Query results (search)', + }, + campaigns: { + type: 'json', + description: 'Campaign data (list_campaigns, campaign_performance)', + }, + adGroups: { + type: 'json', + description: 'Ad group data (list_ad_groups)', + }, + ads: { + type: 'json', + description: 'Ad performance data (ad_performance)', + }, + totalCount: { + type: 'number', + description: 'Total number of results', + }, + totalResultsCount: { + type: 'number', + description: 'Total results count (search)', + }, + nextPageToken: { + type: 'string', + description: 'Token for next page of results', + }, + }, +} diff --git a/apps/sim/blocks/registry.ts b/apps/sim/blocks/registry.ts index 100ee73f3c..7efb33d6f5 100644 --- a/apps/sim/blocks/registry.ts +++ b/apps/sim/blocks/registry.ts @@ -52,6 +52,7 @@ import { GitLabBlock } from '@/blocks/blocks/gitlab' import { GmailBlock, GmailV2Block } from '@/blocks/blocks/gmail' import { GongBlock } from '@/blocks/blocks/gong' import { GoogleSearchBlock } from '@/blocks/blocks/google' +import { GoogleAdsBlock } from '@/blocks/blocks/google_ads' import { GoogleBigQueryBlock } from '@/blocks/blocks/google_bigquery' import { GoogleBooksBlock } from '@/blocks/blocks/google_books' import { GoogleCalendarBlock, GoogleCalendarV2Block } from '@/blocks/blocks/google_calendar' @@ -257,6 +258,7 @@ export const registry: Record = { gmail_v2: GmailV2Block, google_calendar: GoogleCalendarBlock, google_calendar_v2: GoogleCalendarV2Block, + google_ads: GoogleAdsBlock, google_books: GoogleBooksBlock, google_contacts: GoogleContactsBlock, google_docs: GoogleDocsBlock, diff --git a/apps/sim/components/icons.tsx b/apps/sim/components/icons.tsx index 2f7be8184b..0db577837d 100644 --- a/apps/sim/components/icons.tsx +++ b/apps/sim/components/icons.tsx @@ -3572,6 +3572,27 @@ export const ResendIcon = (props: SVGProps) => ( ) +export const GoogleAdsIcon = (props: SVGProps) => ( + + + + + + + + + +) + export const GoogleBigQueryIcon = (props: SVGProps) => ( { + try { + const response = await fetch('https://openidconnect.googleapis.com/v1/userinfo', { + headers: { Authorization: `Bearer ${tokens.accessToken}` }, + }) + if (!response.ok) { + logger.error('Failed to fetch Google user info', { status: response.status }) + throw new Error(`Failed to fetch Google user info: ${response.statusText}`) + } + const profile = await response.json() + const now = new Date() + return { + id: `${profile.sub}-${crypto.randomUUID()}`, + name: profile.name || 'Google User', + email: profile.email, + image: profile.picture || undefined, + emailVerified: profile.email_verified || false, + createdAt: now, + updatedAt: now, + } + } catch (error) { + logger.error('Error in Google getUserInfo', { error }) + throw error + } + }, + }, { providerId: 'google-bigquery', clientId: env.GOOGLE_CLIENT_ID as string, diff --git a/apps/sim/lib/oauth/oauth.ts b/apps/sim/lib/oauth/oauth.ts index 25b1aff0f9..4b23ecde3f 100644 --- a/apps/sim/lib/oauth/oauth.ts +++ b/apps/sim/lib/oauth/oauth.ts @@ -7,6 +7,7 @@ import { ConfluenceIcon, DropboxIcon, GmailIcon, + GoogleAdsIcon, GoogleBigQueryIcon, GoogleCalendarIcon, GoogleContactsIcon, @@ -146,6 +147,18 @@ export const OAUTH_PROVIDERS: Record = { 'https://www.googleapis.com/auth/contacts', ], }, + 'google-ads': { + name: 'Google Ads', + description: 'Query campaigns, ad groups, and performance metrics in Google Ads.', + providerId: 'google-ads', + icon: GoogleAdsIcon, + baseProviderIcon: GoogleIcon, + scopes: [ + 'https://www.googleapis.com/auth/userinfo.email', + 'https://www.googleapis.com/auth/userinfo.profile', + 'https://www.googleapis.com/auth/adwords', + ], + }, 'google-bigquery': { name: 'Google BigQuery', description: 'Query, list, and insert data in Google BigQuery.', diff --git a/apps/sim/lib/oauth/types.ts b/apps/sim/lib/oauth/types.ts index d48c3b1a5b..ef32838dde 100644 --- a/apps/sim/lib/oauth/types.ts +++ b/apps/sim/lib/oauth/types.ts @@ -8,6 +8,7 @@ export type OAuthProvider = | 'google-sheets' | 'google-calendar' | 'google-contacts' + | 'google-ads' | 'google-bigquery' | 'google-tasks' | 'google-vault' @@ -55,6 +56,7 @@ export type OAuthService = | 'google-sheets' | 'google-calendar' | 'google-contacts' + | 'google-ads' | 'google-bigquery' | 'google-tasks' | 'google-vault' diff --git a/apps/sim/lib/oauth/utils.ts b/apps/sim/lib/oauth/utils.ts index b23084895e..9f09fd42a5 100644 --- a/apps/sim/lib/oauth/utils.ts +++ b/apps/sim/lib/oauth/utils.ts @@ -24,6 +24,7 @@ export const SCOPE_DESCRIPTIONS: Record = { 'https://www.googleapis.com/auth/userinfo.profile': 'View basic profile info', 'https://www.googleapis.com/auth/forms.body': 'View and manage Google Forms', 'https://www.googleapis.com/auth/forms.responses.readonly': 'View responses to Google Forms', + 'https://www.googleapis.com/auth/adwords': 'Manage Google Ads campaigns and reporting', 'https://www.googleapis.com/auth/bigquery': 'View and manage data in Google BigQuery', 'https://www.googleapis.com/auth/ediscovery': 'Access Google Vault for eDiscovery', 'https://www.googleapis.com/auth/devstorage.read_only': 'Read files from Google Cloud Storage', diff --git a/apps/sim/tools/google_ads/ad_performance.ts b/apps/sim/tools/google_ads/ad_performance.ts new file mode 100644 index 0000000000..337379298a --- /dev/null +++ b/apps/sim/tools/google_ads/ad_performance.ts @@ -0,0 +1,211 @@ +import type { + GoogleAdsAdPerformanceParams, + GoogleAdsAdPerformanceResponse, +} from '@/tools/google_ads/types' +import { validateDate, validateDateRange, validateNumericId } from '@/tools/google_ads/types' +import type { ToolConfig } from '@/tools/types' + +export const googleAdsAdPerformanceTool: ToolConfig< + GoogleAdsAdPerformanceParams, + GoogleAdsAdPerformanceResponse +> = { + id: 'google_ads_ad_performance', + name: 'Google Ads Ad Performance', + description: 'Get performance metrics for individual ads over a date range', + version: '1.0.0', + + oauth: { + required: true, + provider: 'google-ads', + }, + + params: { + accessToken: { + type: 'string', + required: true, + visibility: 'hidden', + description: 'OAuth access token for the Google Ads API', + }, + customerId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Google Ads customer ID (numeric, no dashes)', + }, + developerToken: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Google Ads API developer token', + }, + managerCustomerId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Manager account customer ID (if accessing via manager account)', + }, + campaignId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Filter by campaign ID', + }, + adGroupId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Filter by ad group ID', + }, + dateRange: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: + 'Predefined date range (LAST_7_DAYS, LAST_30_DAYS, THIS_MONTH, LAST_MONTH, TODAY, YESTERDAY)', + }, + startDate: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Custom start date in YYYY-MM-DD format', + }, + endDate: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Custom end date in YYYY-MM-DD format', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of results to return', + }, + }, + + request: { + url: (params) => { + const customerId = validateNumericId(params.customerId, 'customerId') + return `https://googleads.googleapis.com/v19/customers/${customerId}/googleAds:search` + }, + method: 'POST', + headers: (params) => { + const headers: Record = { + Authorization: `Bearer ${params.accessToken}`, + 'Content-Type': 'application/json', + 'developer-token': params.developerToken, + } + if (params.managerCustomerId) { + headers['login-customer-id'] = validateNumericId( + params.managerCustomerId, + 'managerCustomerId' + ) + } + return headers + }, + body: (params) => { + let query = + 'SELECT ad_group_ad.ad.id, ad_group.id, ad_group.name, campaign.id, campaign.name, ad_group_ad.ad.type, metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.ctr, metrics.conversions, segments.date FROM ad_group_ad' + + const conditions: string[] = ["ad_group_ad.status != 'REMOVED'"] + + if (params.campaignId) { + conditions.push(`campaign.id = ${validateNumericId(params.campaignId, 'campaignId')}`) + } + + if (params.adGroupId) { + conditions.push(`ad_group.id = ${validateNumericId(params.adGroupId, 'adGroupId')}`) + } + + if (params.startDate && params.endDate) { + const start = validateDate(params.startDate, 'startDate') + const end = validateDate(params.endDate, 'endDate') + conditions.push(`segments.date BETWEEN '${start}' AND '${end}'`) + } else { + const dateRange = validateDateRange(params.dateRange || 'LAST_30_DAYS') + conditions.push(`segments.date DURING ${dateRange}`) + } + + query += ` WHERE ${conditions.join(' AND ')}` + query += ' ORDER BY metrics.impressions DESC' + + if (params.limit) { + query += ` LIMIT ${params.limit}` + } + + return { query } + }, + }, + + transformResponse: async (response: Response) => { + const data = await response.json() + + if (!response.ok) { + const errorMessage = + data?.error?.message ?? data?.error?.details?.[0]?.errors?.[0]?.message ?? 'Unknown error' + return { + success: false, + output: { ads: [], totalCount: 0 }, + error: errorMessage, + } + } + + const results = data.results ?? [] + const ads = results.map((r: Record) => ({ + adId: r.adGroupAd?.ad?.id ?? '', + adGroupId: r.adGroup?.id ?? '', + adGroupName: r.adGroup?.name ?? null, + campaignId: r.campaign?.id ?? '', + campaignName: r.campaign?.name ?? null, + adType: r.adGroupAd?.ad?.type ?? null, + impressions: r.metrics?.impressions ?? '0', + clicks: r.metrics?.clicks ?? '0', + costMicros: r.metrics?.costMicros ?? '0', + ctr: r.metrics?.ctr ?? null, + conversions: r.metrics?.conversions ?? null, + date: r.segments?.date ?? null, + })) + + return { + success: true, + output: { + ads, + totalCount: ads.length, + }, + } + }, + + outputs: { + ads: { + type: 'array', + description: 'Ad performance data broken down by date', + items: { + type: 'object', + properties: { + adId: { type: 'string', description: 'Ad ID' }, + adGroupId: { type: 'string', description: 'Parent ad group ID' }, + adGroupName: { type: 'string', description: 'Parent ad group name' }, + campaignId: { type: 'string', description: 'Parent campaign ID' }, + campaignName: { type: 'string', description: 'Parent campaign name' }, + adType: { + type: 'string', + description: 'Ad type (RESPONSIVE_SEARCH_AD, EXPANDED_TEXT_AD, etc.)', + }, + impressions: { type: 'string', description: 'Number of impressions' }, + clicks: { type: 'string', description: 'Number of clicks' }, + costMicros: { + type: 'string', + description: 'Cost in micros (divide by 1,000,000 for currency value)', + }, + ctr: { type: 'number', description: 'Click-through rate (0.0 to 1.0)' }, + conversions: { type: 'number', description: 'Number of conversions' }, + date: { type: 'string', description: 'Date for this row (YYYY-MM-DD)' }, + }, + }, + }, + totalCount: { + type: 'number', + description: 'Total number of result rows', + }, + }, +} diff --git a/apps/sim/tools/google_ads/campaign_performance.ts b/apps/sim/tools/google_ads/campaign_performance.ts new file mode 100644 index 0000000000..3e4ec688b7 --- /dev/null +++ b/apps/sim/tools/google_ads/campaign_performance.ts @@ -0,0 +1,182 @@ +import type { + GoogleAdsCampaignPerformanceParams, + GoogleAdsCampaignPerformanceResponse, +} from '@/tools/google_ads/types' +import { validateDate, validateDateRange, validateNumericId } from '@/tools/google_ads/types' +import type { ToolConfig } from '@/tools/types' + +export const googleAdsCampaignPerformanceTool: ToolConfig< + GoogleAdsCampaignPerformanceParams, + GoogleAdsCampaignPerformanceResponse +> = { + id: 'google_ads_campaign_performance', + name: 'Google Ads Campaign Performance', + description: 'Get performance metrics for Google Ads campaigns over a date range', + version: '1.0.0', + + oauth: { + required: true, + provider: 'google-ads', + }, + + params: { + accessToken: { + type: 'string', + required: true, + visibility: 'hidden', + description: 'OAuth access token for the Google Ads API', + }, + customerId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Google Ads customer ID (numeric, no dashes)', + }, + developerToken: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Google Ads API developer token', + }, + managerCustomerId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Manager account customer ID (if accessing via manager account)', + }, + campaignId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Filter by specific campaign ID', + }, + dateRange: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: + 'Predefined date range (LAST_7_DAYS, LAST_30_DAYS, THIS_MONTH, LAST_MONTH, TODAY, YESTERDAY)', + }, + startDate: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Custom start date in YYYY-MM-DD format', + }, + endDate: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Custom end date in YYYY-MM-DD format', + }, + }, + + request: { + url: (params) => { + const customerId = validateNumericId(params.customerId, 'customerId') + return `https://googleads.googleapis.com/v19/customers/${customerId}/googleAds:search` + }, + method: 'POST', + headers: (params) => { + const headers: Record = { + Authorization: `Bearer ${params.accessToken}`, + 'Content-Type': 'application/json', + 'developer-token': params.developerToken, + } + if (params.managerCustomerId) { + headers['login-customer-id'] = validateNumericId( + params.managerCustomerId, + 'managerCustomerId' + ) + } + return headers + }, + body: (params) => { + let query = + 'SELECT campaign.id, campaign.name, campaign.status, metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.ctr, metrics.conversions, segments.date FROM campaign' + + const conditions: string[] = ["campaign.status != 'REMOVED'"] + + if (params.campaignId) { + conditions.push(`campaign.id = ${validateNumericId(params.campaignId, 'campaignId')}`) + } + + if (params.startDate && params.endDate) { + const start = validateDate(params.startDate, 'startDate') + const end = validateDate(params.endDate, 'endDate') + conditions.push(`segments.date BETWEEN '${start}' AND '${end}'`) + } else { + const dateRange = validateDateRange(params.dateRange || 'LAST_30_DAYS') + conditions.push(`segments.date DURING ${dateRange}`) + } + + query += ` WHERE ${conditions.join(' AND ')}` + query += ' ORDER BY metrics.impressions DESC' + + return { query } + }, + }, + + transformResponse: async (response: Response) => { + const data = await response.json() + + if (!response.ok) { + const errorMessage = + data?.error?.message ?? data?.error?.details?.[0]?.errors?.[0]?.message ?? 'Unknown error' + return { + success: false, + output: { campaigns: [], totalCount: 0 }, + error: errorMessage, + } + } + + const results = data.results ?? [] + const campaigns = results.map((r: Record) => ({ + id: r.campaign?.id ?? '', + name: r.campaign?.name ?? '', + status: r.campaign?.status ?? '', + impressions: r.metrics?.impressions ?? '0', + clicks: r.metrics?.clicks ?? '0', + costMicros: r.metrics?.costMicros ?? '0', + ctr: r.metrics?.ctr ?? null, + conversions: r.metrics?.conversions ?? null, + date: r.segments?.date ?? null, + })) + + return { + success: true, + output: { + campaigns, + totalCount: campaigns.length, + }, + } + }, + + outputs: { + campaigns: { + type: 'array', + description: 'Campaign performance data broken down by date', + items: { + type: 'object', + properties: { + id: { type: 'string', description: 'Campaign ID' }, + name: { type: 'string', description: 'Campaign name' }, + status: { type: 'string', description: 'Campaign status' }, + impressions: { type: 'string', description: 'Number of impressions' }, + clicks: { type: 'string', description: 'Number of clicks' }, + costMicros: { + type: 'string', + description: 'Cost in micros (divide by 1,000,000 for currency value)', + }, + ctr: { type: 'number', description: 'Click-through rate (0.0 to 1.0)' }, + conversions: { type: 'number', description: 'Number of conversions' }, + date: { type: 'string', description: 'Date for this row (YYYY-MM-DD)' }, + }, + }, + }, + totalCount: { + type: 'number', + description: 'Total number of result rows', + }, + }, +} diff --git a/apps/sim/tools/google_ads/index.ts b/apps/sim/tools/google_ads/index.ts new file mode 100644 index 0000000000..aff6b5e3f3 --- /dev/null +++ b/apps/sim/tools/google_ads/index.ts @@ -0,0 +1,17 @@ +import { googleAdsAdPerformanceTool } from '@/tools/google_ads/ad_performance' +import { googleAdsCampaignPerformanceTool } from '@/tools/google_ads/campaign_performance' +import { googleAdsListAdGroupsTool } from '@/tools/google_ads/list_ad_groups' +import { googleAdsListCampaignsTool } from '@/tools/google_ads/list_campaigns' +import { googleAdsListCustomersTool } from '@/tools/google_ads/list_customers' +import { googleAdsSearchTool } from '@/tools/google_ads/search' + +export { + googleAdsAdPerformanceTool, + googleAdsCampaignPerformanceTool, + googleAdsListAdGroupsTool, + googleAdsListCampaignsTool, + googleAdsListCustomersTool, + googleAdsSearchTool, +} + +export * from './types' diff --git a/apps/sim/tools/google_ads/list_ad_groups.ts b/apps/sim/tools/google_ads/list_ad_groups.ts new file mode 100644 index 0000000000..8d8d243031 --- /dev/null +++ b/apps/sim/tools/google_ads/list_ad_groups.ts @@ -0,0 +1,167 @@ +import type { + GoogleAdsListAdGroupsParams, + GoogleAdsListAdGroupsResponse, +} from '@/tools/google_ads/types' +import { validateNumericId, validateStatus } from '@/tools/google_ads/types' +import type { ToolConfig } from '@/tools/types' + +export const googleAdsListAdGroupsTool: ToolConfig< + GoogleAdsListAdGroupsParams, + GoogleAdsListAdGroupsResponse +> = { + id: 'google_ads_list_ad_groups', + name: 'List Google Ads Ad Groups', + description: 'List ad groups in a Google Ads campaign', + version: '1.0.0', + + oauth: { + required: true, + provider: 'google-ads', + }, + + params: { + accessToken: { + type: 'string', + required: true, + visibility: 'hidden', + description: 'OAuth access token for the Google Ads API', + }, + customerId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Google Ads customer ID (numeric, no dashes)', + }, + developerToken: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Google Ads API developer token', + }, + managerCustomerId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Manager account customer ID (if accessing via manager account)', + }, + campaignId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Campaign ID to list ad groups for', + }, + status: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Filter by ad group status (ENABLED, PAUSED, REMOVED)', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of ad groups to return', + }, + }, + + request: { + url: (params) => { + const customerId = validateNumericId(params.customerId, 'customerId') + return `https://googleads.googleapis.com/v19/customers/${customerId}/googleAds:search` + }, + method: 'POST', + headers: (params) => { + const headers: Record = { + Authorization: `Bearer ${params.accessToken}`, + 'Content-Type': 'application/json', + 'developer-token': params.developerToken, + } + if (params.managerCustomerId) { + headers['login-customer-id'] = validateNumericId( + params.managerCustomerId, + 'managerCustomerId' + ) + } + return headers + }, + body: (params) => { + let query = + 'SELECT ad_group.id, ad_group.name, ad_group.status, ad_group.type, campaign.id, campaign.name FROM ad_group' + + const campaignId = validateNumericId(params.campaignId, 'campaignId') + const conditions: string[] = [`campaign.id = ${campaignId}`] + + if (params.status) { + conditions.push(`ad_group.status = '${validateStatus(params.status)}'`) + } else { + conditions.push("ad_group.status != 'REMOVED'") + } + + query += ` WHERE ${conditions.join(' AND ')}` + query += ' ORDER BY ad_group.name' + + if (params.limit) { + query += ` LIMIT ${params.limit}` + } + + return { query } + }, + }, + + transformResponse: async (response: Response) => { + const data = await response.json() + + if (!response.ok) { + const errorMessage = + data?.error?.message ?? data?.error?.details?.[0]?.errors?.[0]?.message ?? 'Unknown error' + return { + success: false, + output: { adGroups: [], totalCount: 0 }, + error: errorMessage, + } + } + + const results = data.results ?? [] + const adGroups = results.map((r: Record) => ({ + id: r.adGroup?.id ?? '', + name: r.adGroup?.name ?? '', + status: r.adGroup?.status ?? '', + type: r.adGroup?.type ?? null, + campaignId: r.campaign?.id ?? '', + campaignName: r.campaign?.name ?? null, + })) + + return { + success: true, + output: { + adGroups, + totalCount: adGroups.length, + }, + } + }, + + outputs: { + adGroups: { + type: 'array', + description: 'List of ad groups in the campaign', + items: { + type: 'object', + properties: { + id: { type: 'string', description: 'Ad group ID' }, + name: { type: 'string', description: 'Ad group name' }, + status: { type: 'string', description: 'Ad group status (ENABLED, PAUSED, REMOVED)' }, + type: { + type: 'string', + description: 'Ad group type (SEARCH_STANDARD, DISPLAY_STANDARD, SHOPPING_PRODUCT_ADS)', + }, + campaignId: { type: 'string', description: 'Parent campaign ID' }, + campaignName: { type: 'string', description: 'Parent campaign name' }, + }, + }, + }, + totalCount: { + type: 'number', + description: 'Total number of ad groups returned', + }, + }, +} diff --git a/apps/sim/tools/google_ads/list_campaigns.ts b/apps/sim/tools/google_ads/list_campaigns.ts new file mode 100644 index 0000000000..ed738cc955 --- /dev/null +++ b/apps/sim/tools/google_ads/list_campaigns.ts @@ -0,0 +1,168 @@ +import type { + GoogleAdsListCampaignsParams, + GoogleAdsListCampaignsResponse, +} from '@/tools/google_ads/types' +import { validateNumericId, validateStatus } from '@/tools/google_ads/types' +import type { ToolConfig } from '@/tools/types' + +export const googleAdsListCampaignsTool: ToolConfig< + GoogleAdsListCampaignsParams, + GoogleAdsListCampaignsResponse +> = { + id: 'google_ads_list_campaigns', + name: 'List Google Ads Campaigns', + description: 'List campaigns in a Google Ads account with optional status filtering', + version: '1.0.0', + + oauth: { + required: true, + provider: 'google-ads', + }, + + params: { + accessToken: { + type: 'string', + required: true, + visibility: 'hidden', + description: 'OAuth access token for the Google Ads API', + }, + customerId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Google Ads customer ID (numeric, no dashes)', + }, + developerToken: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Google Ads API developer token', + }, + managerCustomerId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Manager account customer ID (if accessing via manager account)', + }, + status: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Filter by campaign status (ENABLED, PAUSED, REMOVED)', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of campaigns to return', + }, + }, + + request: { + url: (params) => { + const customerId = validateNumericId(params.customerId, 'customerId') + return `https://googleads.googleapis.com/v19/customers/${customerId}/googleAds:search` + }, + method: 'POST', + headers: (params) => { + const headers: Record = { + Authorization: `Bearer ${params.accessToken}`, + 'Content-Type': 'application/json', + 'developer-token': params.developerToken, + } + if (params.managerCustomerId) { + headers['login-customer-id'] = validateNumericId( + params.managerCustomerId, + 'managerCustomerId' + ) + } + return headers + }, + body: (params) => { + let query = + 'SELECT campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type, campaign.start_date, campaign.end_date, campaign_budget.amount_micros FROM campaign' + + const conditions: string[] = [] + if (params.status) { + conditions.push(`campaign.status = '${validateStatus(params.status)}'`) + } else { + conditions.push("campaign.status != 'REMOVED'") + } + + if (conditions.length > 0) { + query += ` WHERE ${conditions.join(' AND ')}` + } + + query += ' ORDER BY campaign.name' + + if (params.limit) { + query += ` LIMIT ${params.limit}` + } + + return { query } + }, + }, + + transformResponse: async (response: Response) => { + const data = await response.json() + + if (!response.ok) { + const errorMessage = + data?.error?.message ?? data?.error?.details?.[0]?.errors?.[0]?.message ?? 'Unknown error' + return { + success: false, + output: { campaigns: [], totalCount: 0 }, + error: errorMessage, + } + } + + const results = data.results ?? [] + const campaigns = results.map((r: Record) => ({ + id: r.campaign?.id ?? '', + name: r.campaign?.name ?? '', + status: r.campaign?.status ?? '', + channelType: r.campaign?.advertisingChannelType ?? null, + startDate: r.campaign?.startDate ?? null, + endDate: r.campaign?.endDate ?? null, + budgetAmountMicros: r.campaignBudget?.amountMicros ?? null, + })) + + return { + success: true, + output: { + campaigns, + totalCount: campaigns.length, + }, + } + }, + + outputs: { + campaigns: { + type: 'array', + description: 'List of campaigns in the account', + items: { + type: 'object', + properties: { + id: { type: 'string', description: 'Campaign ID' }, + name: { type: 'string', description: 'Campaign name' }, + status: { type: 'string', description: 'Campaign status (ENABLED, PAUSED, REMOVED)' }, + channelType: { + type: 'string', + description: + 'Advertising channel type (SEARCH, DISPLAY, SHOPPING, VIDEO, PERFORMANCE_MAX)', + }, + startDate: { type: 'string', description: 'Campaign start date (YYYY-MM-DD)' }, + endDate: { type: 'string', description: 'Campaign end date (YYYY-MM-DD)' }, + budgetAmountMicros: { + type: 'string', + description: 'Daily budget in micros (divide by 1,000,000 for currency value)', + }, + }, + }, + }, + totalCount: { + type: 'number', + description: 'Total number of campaigns returned', + }, + }, +} diff --git a/apps/sim/tools/google_ads/list_customers.ts b/apps/sim/tools/google_ads/list_customers.ts new file mode 100644 index 0000000000..9d764b8691 --- /dev/null +++ b/apps/sim/tools/google_ads/list_customers.ts @@ -0,0 +1,84 @@ +import type { + GoogleAdsListCustomersParams, + GoogleAdsListCustomersResponse, +} from '@/tools/google_ads/types' +import type { ToolConfig } from '@/tools/types' + +export const googleAdsListCustomersTool: ToolConfig< + GoogleAdsListCustomersParams, + GoogleAdsListCustomersResponse +> = { + id: 'google_ads_list_customers', + name: 'List Google Ads Customers', + description: 'List all Google Ads customer accounts accessible by the authenticated user', + version: '1.0.0', + + oauth: { + required: true, + provider: 'google-ads', + }, + + params: { + accessToken: { + type: 'string', + required: true, + visibility: 'hidden', + description: 'OAuth access token for the Google Ads API', + }, + developerToken: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Google Ads API developer token', + }, + }, + + request: { + url: 'https://googleads.googleapis.com/v19/customers:listAccessibleCustomers', + method: 'GET', + headers: (params) => ({ + Authorization: `Bearer ${params.accessToken}`, + 'developer-token': params.developerToken, + }), + }, + + transformResponse: async (response: Response) => { + const data = await response.json() + + if (!response.ok) { + const errorMessage = + data?.error?.message ?? data?.error?.details?.[0]?.errors?.[0]?.message ?? 'Unknown error' + return { + success: false, + output: { customerIds: [], totalCount: 0 }, + error: errorMessage, + } + } + + const resourceNames: string[] = data.resourceNames ?? [] + const customerIds = resourceNames.map((rn: string) => rn.replace('customers/', '')) + + return { + success: true, + output: { + customerIds, + totalCount: customerIds.length, + }, + } + }, + + outputs: { + customerIds: { + type: 'array', + description: 'List of accessible customer IDs', + items: { + type: 'string', + description: 'Google Ads customer ID (numeric, no dashes)', + }, + }, + totalCount: { + type: 'number', + description: 'Total number of accessible customer accounts', + }, + }, +} diff --git a/apps/sim/tools/google_ads/search.ts b/apps/sim/tools/google_ads/search.ts new file mode 100644 index 0000000000..ffd497fc39 --- /dev/null +++ b/apps/sim/tools/google_ads/search.ts @@ -0,0 +1,130 @@ +import type { GoogleAdsSearchParams, GoogleAdsSearchResponse } from '@/tools/google_ads/types' +import { validateNumericId } from '@/tools/google_ads/types' +import type { ToolConfig } from '@/tools/types' + +export const googleAdsSearchTool: ToolConfig = { + id: 'google_ads_search', + name: 'Google Ads Search (GAQL)', + description: 'Run a custom Google Ads Query Language (GAQL) query', + version: '1.0.0', + + oauth: { + required: true, + provider: 'google-ads', + }, + + params: { + accessToken: { + type: 'string', + required: true, + visibility: 'hidden', + description: 'OAuth access token for the Google Ads API', + }, + customerId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Google Ads customer ID (numeric, no dashes)', + }, + developerToken: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Google Ads API developer token', + }, + managerCustomerId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Manager account customer ID (if accessing via manager account)', + }, + query: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'GAQL query to execute', + }, + pageToken: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Page token for pagination', + }, + }, + + request: { + url: (params) => { + const customerId = validateNumericId(params.customerId, 'customerId') + return `https://googleads.googleapis.com/v19/customers/${customerId}/googleAds:search` + }, + method: 'POST', + headers: (params) => { + const headers: Record = { + Authorization: `Bearer ${params.accessToken}`, + 'Content-Type': 'application/json', + 'developer-token': params.developerToken, + } + if (params.managerCustomerId) { + headers['login-customer-id'] = validateNumericId( + params.managerCustomerId, + 'managerCustomerId' + ) + } + return headers + }, + body: (params) => { + const body: Record = { + query: params.query, + searchSettings: { + returnTotalResultsCount: true, + }, + } + if (params.pageToken) { + body.pageToken = params.pageToken + } + return body + }, + }, + + transformResponse: async (response: Response) => { + const data = await response.json() + + if (!response.ok) { + const errorMessage = + data?.error?.message ?? data?.error?.details?.[0]?.errors?.[0]?.message ?? 'Unknown error' + return { + success: false, + output: { + results: [], + totalResultsCount: null, + nextPageToken: null, + }, + error: errorMessage, + } + } + + return { + success: true, + output: { + results: data.results ?? [], + totalResultsCount: data.totalResultsCount ? Number(data.totalResultsCount) : null, + nextPageToken: data.nextPageToken ?? null, + }, + } + }, + + outputs: { + results: { + type: 'json', + description: 'Array of result objects from the GAQL query', + }, + totalResultsCount: { + type: 'number', + description: 'Total number of matching results', + }, + nextPageToken: { + type: 'string', + description: 'Token for the next page of results', + }, + }, +} diff --git a/apps/sim/tools/google_ads/types.ts b/apps/sim/tools/google_ads/types.ts new file mode 100644 index 0000000000..3f1a9df003 --- /dev/null +++ b/apps/sim/tools/google_ads/types.ts @@ -0,0 +1,187 @@ +import type { ToolResponse } from '@/tools/types' + +const NUMERIC_ID_REGEX = /^\d+$/ +const DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/ +const VALID_STATUSES = new Set(['ENABLED', 'PAUSED', 'REMOVED']) +const VALID_DATE_RANGES = new Set([ + 'TODAY', + 'YESTERDAY', + 'LAST_7_DAYS', + 'LAST_14_DAYS', + 'LAST_30_DAYS', + 'LAST_BUSINESS_WEEK', + 'THIS_MONTH', + 'LAST_MONTH', + 'THIS_WEEK_SUN_TODAY', + 'THIS_WEEK_MON_TODAY', + 'LAST_WEEK_SUN_SAT', + 'LAST_WEEK_MON_SUN', +]) + +/** Validates that a value is a numeric ID (digits only). */ +export function validateNumericId(value: string, fieldName: string): string { + const cleaned = value.replace(/-/g, '') + if (!NUMERIC_ID_REGEX.test(cleaned)) { + throw new Error(`${fieldName} must be numeric (digits only), got: ${value}`) + } + return cleaned +} + +/** Validates that a status value is a known Google Ads status. */ +export function validateStatus(value: string): string { + if (!VALID_STATUSES.has(value)) { + throw new Error(`Invalid status: ${value}. Must be one of: ${[...VALID_STATUSES].join(', ')}`) + } + return value +} + +/** Validates a date string is in YYYY-MM-DD format. */ +export function validateDate(value: string, fieldName: string): string { + if (!DATE_REGEX.test(value)) { + throw new Error(`${fieldName} must be in YYYY-MM-DD format, got: ${value}`) + } + return value +} + +/** Validates a date range is a known Google Ads predefined range. */ +export function validateDateRange(value: string): string { + if (!VALID_DATE_RANGES.has(value)) { + throw new Error( + `Invalid date range: ${value}. Must be one of: ${[...VALID_DATE_RANGES].join(', ')}` + ) + } + return value +} + +export interface GoogleAdsBaseParams { + accessToken: string + customerId: string + developerToken: string + managerCustomerId?: string +} + +export interface GoogleAdsListCustomersParams { + accessToken: string + developerToken: string +} + +export interface GoogleAdsSearchParams extends GoogleAdsBaseParams { + query: string + pageToken?: string +} + +export interface GoogleAdsListCampaignsParams extends GoogleAdsBaseParams { + status?: string + limit?: number +} + +export interface GoogleAdsCampaignPerformanceParams extends GoogleAdsBaseParams { + campaignId?: string + dateRange?: string + startDate?: string + endDate?: string +} + +export interface GoogleAdsListAdGroupsParams extends GoogleAdsBaseParams { + campaignId: string + status?: string + limit?: number +} + +export interface GoogleAdsAdPerformanceParams extends GoogleAdsBaseParams { + campaignId?: string + adGroupId?: string + dateRange?: string + startDate?: string + endDate?: string + limit?: number +} + +export interface GoogleAdsListCustomersResponse extends ToolResponse { + output: { + customerIds: string[] + totalCount: number + } +} + +export interface GoogleAdsSearchResponse extends ToolResponse { + output: { + results: Record[] + totalResultsCount: number | null + nextPageToken: string | null + } +} + +export interface GoogleAdsCampaign { + id: string + name: string + status: string + channelType: string | null + startDate: string | null + endDate: string | null + budgetAmountMicros: string | null +} + +export interface GoogleAdsListCampaignsResponse extends ToolResponse { + output: { + campaigns: GoogleAdsCampaign[] + totalCount: number + } +} + +export interface GoogleAdsCampaignPerformance { + id: string + name: string + status: string + impressions: string + clicks: string + costMicros: string + ctr: number | null + conversions: number | null + date: string | null +} + +export interface GoogleAdsCampaignPerformanceResponse extends ToolResponse { + output: { + campaigns: GoogleAdsCampaignPerformance[] + totalCount: number + } +} + +export interface GoogleAdsAdGroup { + id: string + name: string + status: string + type: string | null + campaignId: string + campaignName: string | null +} + +export interface GoogleAdsListAdGroupsResponse extends ToolResponse { + output: { + adGroups: GoogleAdsAdGroup[] + totalCount: number + } +} + +export interface GoogleAdsAdPerformance { + adId: string + adGroupId: string + adGroupName: string | null + campaignId: string + campaignName: string | null + adType: string | null + impressions: string + clicks: string + costMicros: string + ctr: number | null + conversions: number | null + date: string | null +} + +export interface GoogleAdsAdPerformanceResponse extends ToolResponse { + output: { + ads: GoogleAdsAdPerformance[] + totalCount: number + } +} diff --git a/apps/sim/tools/registry.ts b/apps/sim/tools/registry.ts index f9375bc100..4498d5b5a7 100644 --- a/apps/sim/tools/registry.ts +++ b/apps/sim/tools/registry.ts @@ -728,6 +728,14 @@ import { gongLookupPhoneTool, } from '@/tools/gong' import { googleSearchTool } from '@/tools/google' +import { + googleAdsAdPerformanceTool, + googleAdsCampaignPerformanceTool, + googleAdsListAdGroupsTool, + googleAdsListCampaignsTool, + googleAdsListCustomersTool, + googleAdsSearchTool, +} from '@/tools/google_ads' import { googleBigQueryGetTableTool, googleBigQueryInsertRowsTool, @@ -4038,6 +4046,12 @@ export const tools: Record = { wordpress_list_users: wordpressListUsersTool, wordpress_get_user: wordpressGetUserTool, wordpress_search_content: wordpressSearchContentTool, + google_ads_list_customers: googleAdsListCustomersTool, + google_ads_search: googleAdsSearchTool, + google_ads_list_campaigns: googleAdsListCampaignsTool, + google_ads_campaign_performance: googleAdsCampaignPerformanceTool, + google_ads_list_ad_groups: googleAdsListAdGroupsTool, + google_ads_ad_performance: googleAdsAdPerformanceTool, google_bigquery_query: googleBigQueryQueryTool, google_bigquery_list_datasets: googleBigQueryListDatasetsTool, google_bigquery_list_tables: googleBigQueryListTablesTool, From d90f828e88019d69d94840fd092eaf7962230d59 Mon Sep 17 00:00:00 2001 From: Vikhyath Mondreti Date: Thu, 12 Mar 2026 22:48:01 -0700 Subject: [PATCH 5/5] fix(grain): update to stable version of API (#3556) * fix(grain): update to stable version of API * fix prewebhook lookup * update pending webhook verification infra * add generic webhook test event verification subblock --- .../api/webhooks/trigger/[path]/route.test.ts | 96 +++++++- .../app/api/webhooks/trigger/[path]/route.ts | 16 +- apps/sim/blocks/blocks/grain.ts | 44 ++-- apps/sim/lib/webhooks/deploy.ts | 14 ++ .../lib/webhooks/pending-verification.test.ts | 142 ++++++++++++ apps/sim/lib/webhooks/pending-verification.ts | 218 ++++++++++++++++++ apps/sim/lib/webhooks/processor.ts | 36 ++- .../lib/webhooks/provider-subscriptions.ts | 83 ++++--- apps/sim/tools/grain/create_hook.ts | 115 ++------- apps/sim/tools/grain/delete_hook.ts | 3 +- apps/sim/tools/grain/index.ts | 1 + apps/sim/tools/grain/list_hooks.ts | 10 +- apps/sim/tools/grain/list_views.ts | 66 ++++++ apps/sim/tools/grain/types.ts | 51 ++-- apps/sim/tools/registry.ts | 2 + apps/sim/triggers/generic/webhook.ts | 10 + apps/sim/triggers/grain/highlight_created.ts | 13 ++ apps/sim/triggers/grain/highlight_updated.ts | 13 ++ apps/sim/triggers/grain/recording_created.ts | 13 ++ apps/sim/triggers/grain/recording_updated.ts | 13 ++ apps/sim/triggers/grain/story_created.ts | 13 ++ apps/sim/triggers/grain/utils.ts | 4 +- apps/sim/triggers/grain/webhook.ts | 15 +- 23 files changed, 796 insertions(+), 195 deletions(-) create mode 100644 apps/sim/lib/webhooks/pending-verification.test.ts create mode 100644 apps/sim/lib/webhooks/pending-verification.ts create mode 100644 apps/sim/tools/grain/list_views.ts diff --git a/apps/sim/app/api/webhooks/trigger/[path]/route.test.ts b/apps/sim/app/api/webhooks/trigger/[path]/route.test.ts index 3f02f330e8..195572f8cb 100644 --- a/apps/sim/app/api/webhooks/trigger/[path]/route.test.ts +++ b/apps/sim/app/api/webhooks/trigger/[path]/route.test.ts @@ -268,6 +268,32 @@ vi.mock('@/lib/webhooks/processor', () => ({ } }), handleProviderChallenges: vi.fn().mockResolvedValue(null), + handlePreLookupWebhookVerification: vi + .fn() + .mockImplementation( + async ( + method: string, + body: Record | undefined, + _requestId: string, + path: string + ) => { + if (path !== 'pending-verification-path') { + return null + } + + const isVerificationProbe = + method === 'GET' || + method === 'HEAD' || + (method === 'POST' && (!body || Object.keys(body).length === 0 || !body.type)) + + if (!isVerificationProbe) { + return null + } + + const { NextResponse } = require('next/server') + return NextResponse.json({ status: 'ok', message: 'Webhook endpoint verified' }) + } + ), handleProviderReachabilityTest: vi.fn().mockReturnValue(null), verifyProviderAuth: vi .fn() @@ -353,7 +379,7 @@ vi.mock('@/lib/core/utils/request', () => requestUtilsMock) process.env.DATABASE_URL = 'postgresql://test:test@localhost:5432/test' -import { POST } from '@/app/api/webhooks/trigger/[path]/route' +import { GET, POST } from '@/app/api/webhooks/trigger/[path]/route' describe('Webhook Trigger API Route', () => { beforeEach(() => { @@ -389,7 +415,7 @@ describe('Webhook Trigger API Route', () => { }) it('should handle 404 for non-existent webhooks', async () => { - const req = createMockRequest('POST', { event: 'test' }) + const req = createMockRequest('POST', { type: 'event.test' }) const params = Promise.resolve({ path: 'non-existent-path' }) @@ -401,6 +427,72 @@ describe('Webhook Trigger API Route', () => { expect(text).toMatch(/not found/i) }) + it('should return 405 for GET requests on unknown webhook paths', async () => { + const req = createMockRequest( + 'GET', + undefined, + {}, + 'http://localhost:3000/api/webhooks/trigger/non-existent-path' + ) + + const params = Promise.resolve({ path: 'non-existent-path' }) + + const response = await GET(req as any, { params }) + + expect(response.status).toBe(405) + }) + + it('should return 200 for GET verification probes on registered pending paths', async () => { + const req = createMockRequest( + 'GET', + undefined, + {}, + 'http://localhost:3000/api/webhooks/trigger/pending-verification-path' + ) + + const params = Promise.resolve({ path: 'pending-verification-path' }) + + const response = await GET(req as any, { params }) + + expect(response.status).toBe(200) + await expect(response.json()).resolves.toMatchObject({ + status: 'ok', + message: 'Webhook endpoint verified', + }) + }) + + it('should return 200 for empty POST verification probes on registered pending paths', async () => { + const req = createMockRequest( + 'POST', + undefined, + {}, + 'http://localhost:3000/api/webhooks/trigger/pending-verification-path' + ) + + const params = Promise.resolve({ path: 'pending-verification-path' }) + + const response = await POST(req as any, { params }) + + expect(response.status).toBe(200) + await expect(response.json()).resolves.toMatchObject({ + status: 'ok', + message: 'Webhook endpoint verified', + }) + }) + + it('should return 404 for POST requests without type on unknown webhook paths', async () => { + const req = createMockRequest('POST', { event: 'test' }) + + const params = Promise.resolve({ path: 'non-existent-path' }) + + const response = await POST(req as any, { params }) + + expect(response.status).toBe(404) + + const text = await response.text() + expect(text).toMatch(/not found/i) + }) + describe('Generic Webhook Authentication', () => { it('should process generic webhook without authentication', async () => { testData.webhooks.push({ diff --git a/apps/sim/app/api/webhooks/trigger/[path]/route.ts b/apps/sim/app/api/webhooks/trigger/[path]/route.ts index 139bdf7a48..f8d0d8fb1b 100644 --- a/apps/sim/app/api/webhooks/trigger/[path]/route.ts +++ b/apps/sim/app/api/webhooks/trigger/[path]/route.ts @@ -5,6 +5,7 @@ import { checkWebhookPreprocessing, findAllWebhooksForPath, handlePreDeploymentVerification, + handlePreLookupWebhookVerification, handleProviderChallenges, handleProviderReachabilityTest, parseWebhookBody, @@ -30,7 +31,10 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{ return challengeResponse } - return new NextResponse('Method not allowed', { status: 405 }) + return ( + (await handlePreLookupWebhookVerification(request.method, undefined, requestId, path)) || + new NextResponse('Method not allowed', { status: 405 }) + ) } export async function POST( @@ -64,6 +68,16 @@ export async function POST( const webhooksForPath = await findAllWebhooksForPath({ requestId, path }) if (webhooksForPath.length === 0) { + const verificationResponse = await handlePreLookupWebhookVerification( + request.method, + body, + requestId, + path + ) + if (verificationResponse) { + return verificationResponse + } + logger.warn(`[${requestId}] Webhook or workflow not found for path: ${path}`) return new NextResponse('Not Found', { status: 404 }) } diff --git a/apps/sim/blocks/blocks/grain.ts b/apps/sim/blocks/blocks/grain.ts index 86fdbf544e..4840272e08 100644 --- a/apps/sim/blocks/blocks/grain.ts +++ b/apps/sim/blocks/blocks/grain.ts @@ -25,6 +25,7 @@ export const GrainBlock: BlockConfig = { { label: 'List Recordings', id: 'grain_list_recordings' }, { label: 'Get Recording', id: 'grain_get_recording' }, { label: 'Get Transcript', id: 'grain_get_transcript' }, + { label: 'List Views', id: 'grain_list_views' }, { label: 'List Teams', id: 'grain_list_teams' }, { label: 'List Meeting Types', id: 'grain_list_meeting_types' }, { label: 'Create Webhook', id: 'grain_create_hook' }, @@ -72,7 +73,7 @@ export const GrainBlock: BlockConfig = { placeholder: 'ISO8601 timestamp (e.g., 2024-01-01T00:00:00Z)', condition: { field: 'operation', - value: ['grain_list_recordings', 'grain_create_hook'], + value: ['grain_list_recordings'], }, wandConfig: { enabled: true, @@ -96,7 +97,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, placeholder: 'ISO8601 timestamp (e.g., 2024-01-01T00:00:00Z)', condition: { field: 'operation', - value: ['grain_list_recordings', 'grain_create_hook'], + value: ['grain_list_recordings'], }, wandConfig: { enabled: true, @@ -125,7 +126,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, value: () => '', condition: { field: 'operation', - value: ['grain_list_recordings', 'grain_create_hook'], + value: ['grain_list_recordings'], }, }, // Title search @@ -162,7 +163,7 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, placeholder: 'Filter by team UUID (optional)', condition: { field: 'operation', - value: ['grain_list_recordings', 'grain_create_hook'], + value: ['grain_list_recordings'], }, }, // Meeting type ID filter @@ -173,7 +174,7 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, placeholder: 'Filter by meeting type UUID (optional)', condition: { field: 'operation', - value: ['grain_list_recordings', 'grain_create_hook'], + value: ['grain_list_recordings'], }, }, // Include highlights @@ -183,7 +184,7 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, type: 'switch', condition: { field: 'operation', - value: ['grain_list_recordings', 'grain_get_recording', 'grain_create_hook'], + value: ['grain_list_recordings', 'grain_get_recording'], }, }, // Include participants @@ -193,7 +194,7 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, type: 'switch', condition: { field: 'operation', - value: ['grain_list_recordings', 'grain_get_recording', 'grain_create_hook'], + value: ['grain_list_recordings', 'grain_get_recording'], }, }, // Include AI summary @@ -203,7 +204,18 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, type: 'switch', condition: { field: 'operation', - value: ['grain_list_recordings', 'grain_get_recording', 'grain_create_hook'], + value: ['grain_list_recordings', 'grain_get_recording'], + }, + }, + { + id: 'viewId', + title: 'View ID', + type: 'short-input', + placeholder: 'Enter Grain view UUID', + required: true, + condition: { + field: 'operation', + value: ['grain_create_hook'], }, }, // Include calendar event (get_recording only) @@ -271,6 +283,7 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, 'grain_list_recordings', 'grain_get_recording', 'grain_get_transcript', + 'grain_list_views', 'grain_list_teams', 'grain_list_meeting_types', 'grain_create_hook', @@ -327,6 +340,7 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, case 'grain_list_teams': case 'grain_list_meeting_types': + case 'grain_list_views': case 'grain_list_hooks': return baseParams @@ -334,17 +348,13 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, if (!params.hookUrl?.trim()) { throw new Error('Webhook URL is required.') } + if (!params.viewId?.trim()) { + throw new Error('View ID is required.') + } return { ...baseParams, hookUrl: params.hookUrl.trim(), - filterBeforeDatetime: params.beforeDatetime || undefined, - filterAfterDatetime: params.afterDatetime || undefined, - filterParticipantScope: params.participantScope || undefined, - filterTeamId: params.teamId || undefined, - filterMeetingTypeId: params.meetingTypeId || undefined, - includeHighlights: params.includeHighlights || false, - includeParticipants: params.includeParticipants || false, - includeAiSummary: params.includeAiSummary || false, + viewId: params.viewId.trim(), } case 'grain_delete_hook': @@ -367,6 +377,7 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, apiKey: { type: 'string', description: 'Grain API key (Personal Access Token)' }, recordingId: { type: 'string', description: 'Recording UUID' }, cursor: { type: 'string', description: 'Pagination cursor' }, + viewId: { type: 'string', description: 'Grain view UUID for webhook subscriptions' }, beforeDatetime: { type: 'string', description: 'Filter recordings before this ISO8601 timestamp', @@ -416,6 +427,7 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, teamsList: { type: 'json', description: 'Array of team objects' }, // Meeting type outputs meetingTypes: { type: 'json', description: 'Array of meeting type objects' }, + views: { type: 'json', description: 'Array of Grain views' }, // Hook outputs hooks: { type: 'json', description: 'Array of webhook objects' }, hook: { type: 'json', description: 'Created webhook data' }, diff --git a/apps/sim/lib/webhooks/deploy.ts b/apps/sim/lib/webhooks/deploy.ts index a4fce31dfb..f1a4533caf 100644 --- a/apps/sim/lib/webhooks/deploy.ts +++ b/apps/sim/lib/webhooks/deploy.ts @@ -5,6 +5,7 @@ import { and, eq, inArray } from 'drizzle-orm' import { nanoid } from 'nanoid' import type { NextRequest } from 'next/server' import { getProviderIdFromServiceId } from '@/lib/oauth' +import { PendingWebhookVerificationTracker } from '@/lib/webhooks/pending-verification' import { cleanupExternalWebhook, createExternalWebhookSubscription, @@ -580,6 +581,7 @@ export async function saveTriggerWebhooksForDeploy({ updatedProviderConfig: Record externalSubscriptionCreated: boolean }> = [] + const pendingVerificationTracker = new PendingWebhookVerificationTracker() for (const block of blocksNeedingWebhook) { const config = webhookConfigs.get(block.id) @@ -595,6 +597,14 @@ export async function saveTriggerWebhooksForDeploy({ } try { + await pendingVerificationTracker.register({ + path: triggerPath, + provider, + workflowId, + blockId: block.id, + metadata: providerConfig, + }) + const result = await createExternalWebhookSubscription( request, createPayload, @@ -613,6 +623,7 @@ export async function saveTriggerWebhooksForDeploy({ }) } catch (error: any) { logger.error(`[${requestId}] Failed to create external subscription for ${block.id}`, error) + await pendingVerificationTracker.clearAll() for (const sub of createdSubscriptions) { if (sub.externalSubscriptionCreated) { try { @@ -666,6 +677,8 @@ export async function saveTriggerWebhooksForDeploy({ } }) + await pendingVerificationTracker.clearAll() + for (const sub of createdSubscriptions) { const pollingError = await configurePollingIfNeeded( sub.provider, @@ -710,6 +723,7 @@ export async function saveTriggerWebhooksForDeploy({ } } } catch (error: any) { + await pendingVerificationTracker.clearAll() logger.error(`[${requestId}] Failed to insert webhook records`, error) for (const sub of createdSubscriptions) { if (sub.externalSubscriptionCreated) { diff --git a/apps/sim/lib/webhooks/pending-verification.test.ts b/apps/sim/lib/webhooks/pending-verification.test.ts new file mode 100644 index 0000000000..eb3e467303 --- /dev/null +++ b/apps/sim/lib/webhooks/pending-verification.test.ts @@ -0,0 +1,142 @@ +/** + * @vitest-environment node + */ +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/core/config/redis', () => ({ + getRedisClient: vi.fn().mockReturnValue(null), +})) + +vi.mock('@sim/logger', () => ({ + createLogger: vi.fn().mockReturnValue({ + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }), +})) + +import { + clearPendingWebhookVerification, + getPendingWebhookVerification, + matchesPendingWebhookVerificationProbe, + PendingWebhookVerificationTracker, + registerPendingWebhookVerification, +} from '@/lib/webhooks/pending-verification' + +describe('pending webhook verification', () => { + afterEach(async () => { + await clearPendingWebhookVerification('grain-path-1') + await clearPendingWebhookVerification('grain-path-2') + await clearPendingWebhookVerification('grain-path-3') + await clearPendingWebhookVerification('grain-path-4') + }) + + it('stores and retrieves pending Grain verification entries', async () => { + await registerPendingWebhookVerification({ + path: 'grain-path-1', + provider: 'grain', + workflowId: 'workflow-1', + blockId: 'block-1', + }) + + const entry = await getPendingWebhookVerification('grain-path-1') + + expect(entry).toMatchObject({ + path: 'grain-path-1', + provider: 'grain', + workflowId: 'workflow-1', + blockId: 'block-1', + }) + }) + + it('matches Grain verification probe shapes only for registered paths', async () => { + await registerPendingWebhookVerification({ + path: 'grain-path-2', + provider: 'grain', + }) + + const entry = await getPendingWebhookVerification('grain-path-2') + + expect(entry).not.toBeNull() + expect( + matchesPendingWebhookVerificationProbe(entry!, { + method: 'POST', + body: {}, + }) + ).toBe(true) + expect( + matchesPendingWebhookVerificationProbe(entry!, { + method: 'POST', + body: { type: 'recording_added' }, + }) + ).toBe(false) + }) + + it('does not register generic pending verification unless verifyTestEvents is enabled', async () => { + await registerPendingWebhookVerification({ + path: 'grain-path-3', + provider: 'generic', + metadata: { verifyTestEvents: false }, + }) + + expect(await getPendingWebhookVerification('grain-path-3')).toBeNull() + }) + + it('registers generic pending verification when verifyTestEvents is enabled', async () => { + await registerPendingWebhookVerification({ + path: 'grain-path-3', + provider: 'generic', + metadata: { verifyTestEvents: true }, + }) + + const entry = await getPendingWebhookVerification('grain-path-3') + + expect(entry).toMatchObject({ + path: 'grain-path-3', + provider: 'generic', + metadata: { verifyTestEvents: true }, + }) + expect( + matchesPendingWebhookVerificationProbe(entry!, { + method: 'POST', + body: {}, + }) + ).toBe(true) + expect( + matchesPendingWebhookVerificationProbe(entry!, { + method: 'POST', + body: { message: 'real event' }, + }) + ).toBe(false) + }) + + it('clears tracked pending verifications after a successful lifecycle', async () => { + const tracker = new PendingWebhookVerificationTracker() + + await tracker.register({ + path: 'grain-path-3', + provider: 'grain', + }) + + expect(await getPendingWebhookVerification('grain-path-3')).not.toBeNull() + + await tracker.clearAll() + + expect(await getPendingWebhookVerification('grain-path-3')).toBeNull() + }) + + it('clears tracked pending verifications after a failed lifecycle', async () => { + const tracker = new PendingWebhookVerificationTracker() + + await tracker.register({ + path: 'grain-path-4', + provider: 'grain', + }) + + expect(await getPendingWebhookVerification('grain-path-4')).not.toBeNull() + + await tracker.clear('grain-path-4') + + expect(await getPendingWebhookVerification('grain-path-4')).toBeNull() + }) +}) diff --git a/apps/sim/lib/webhooks/pending-verification.ts b/apps/sim/lib/webhooks/pending-verification.ts new file mode 100644 index 0000000000..5f851e4104 --- /dev/null +++ b/apps/sim/lib/webhooks/pending-verification.ts @@ -0,0 +1,218 @@ +import { createLogger } from '@sim/logger' +import { getRedisClient } from '@/lib/core/config/redis' + +const logger = createLogger('WebhookPendingVerification') + +const DEFAULT_TTL_SECONDS = 120 +const REDIS_KEY_PREFIX = 'webhook:pending-verification:' + +const inMemoryPendingVerificationStore = new Map() + +export interface PendingWebhookVerification { + path: string + provider: string + workflowId?: string + blockId?: string + metadata?: Record + expiresAt: number +} + +export interface PendingWebhookVerificationRegistration { + path: string + provider: string + workflowId?: string + blockId?: string + metadata?: Record + ttlSeconds?: number +} + +interface PendingWebhookVerificationProbe { + method: string + body: Record | undefined +} + +type PendingWebhookVerificationRegistrationMatcher = ( + registration: PendingWebhookVerificationRegistration +) => boolean + +type PendingWebhookVerificationProbeMatcher = ( + probe: PendingWebhookVerificationProbe, + entry: PendingWebhookVerification +) => boolean + +const pendingWebhookVerificationRegistrationMatchers: Record< + string, + PendingWebhookVerificationRegistrationMatcher +> = { + grain: () => true, + generic: (registration) => registration.metadata?.verifyTestEvents === true, +} + +const pendingWebhookVerificationProbeMatchers: Record< + string, + PendingWebhookVerificationProbeMatcher +> = { + grain: ({ method, body }) => + method === 'GET' || + method === 'HEAD' || + (method === 'POST' && (!body || Object.keys(body).length === 0 || !body.type)), + generic: ({ method, body }) => + method === 'GET' || + method === 'HEAD' || + (method === 'POST' && (!body || Object.keys(body).length === 0)), +} + +function getRedisKey(path: string): string { + return `${REDIS_KEY_PREFIX}${path}` +} + +function isExpired(entry: PendingWebhookVerification): boolean { + return entry.expiresAt <= Date.now() +} + +function getInMemoryPendingWebhookVerification(path: string): PendingWebhookVerification | null { + const entry = inMemoryPendingVerificationStore.get(path) + if (!entry) { + return null + } + + if (isExpired(entry)) { + inMemoryPendingVerificationStore.delete(path) + return null + } + + return entry +} + +export function requiresPendingWebhookVerification( + provider: string, + metadata?: Record +): boolean { + const registrationMatcher = pendingWebhookVerificationRegistrationMatchers[provider] + if (!registrationMatcher) { + return false + } + + return registrationMatcher({ + path: '', + provider, + metadata, + }) +} + +export async function registerPendingWebhookVerification( + registration: PendingWebhookVerificationRegistration +): Promise { + const registrationMatcher = pendingWebhookVerificationRegistrationMatchers[registration.provider] + if (!registrationMatcher || !registrationMatcher(registration)) { + return + } + + const ttlSeconds = registration.ttlSeconds ?? DEFAULT_TTL_SECONDS + const entry: PendingWebhookVerification = { + path: registration.path, + provider: registration.provider, + workflowId: registration.workflowId, + blockId: registration.blockId, + metadata: registration.metadata, + expiresAt: Date.now() + ttlSeconds * 1000, + } + + const redis = getRedisClient() + if (redis) { + await redis.set(getRedisKey(registration.path), JSON.stringify(entry), 'EX', ttlSeconds) + } else { + inMemoryPendingVerificationStore.set(registration.path, entry) + } + + logger.info('Registered pending webhook verification', { + provider: registration.provider, + path: registration.path, + ttlSeconds, + }) +} + +export async function getPendingWebhookVerification( + path: string +): Promise { + const redis = getRedisClient() + if (redis) { + const value = await redis.get(getRedisKey(path)) + if (!value) { + return null + } + + try { + const entry = JSON.parse(value) as PendingWebhookVerification + if (isExpired(entry)) { + await redis.del(getRedisKey(path)) + return null + } + return entry + } catch (error) { + logger.warn('Failed to parse pending webhook verification entry', { + path, + error: error instanceof Error ? error.message : String(error), + }) + await redis.del(getRedisKey(path)) + return null + } + } + + return getInMemoryPendingWebhookVerification(path) +} + +export async function clearPendingWebhookVerification(path: string): Promise { + const redis = getRedisClient() + if (redis) { + await redis.del(getRedisKey(path)) + } else { + inMemoryPendingVerificationStore.delete(path) + } + + logger.info('Cleared pending webhook verification', { path }) +} + +export function matchesPendingWebhookVerificationProbe( + entry: PendingWebhookVerification, + probe: PendingWebhookVerificationProbe +): boolean { + const matcher = pendingWebhookVerificationProbeMatchers[entry.provider] + if (!matcher) { + return false + } + + return matcher(probe, entry) +} + +export class PendingWebhookVerificationTracker { + private readonly registeredPaths = new Set() + + async register(registration: PendingWebhookVerificationRegistration): Promise { + const registrationMatcher = + pendingWebhookVerificationRegistrationMatchers[registration.provider] + if (!registrationMatcher || !registrationMatcher(registration)) { + return + } + + await registerPendingWebhookVerification(registration) + this.registeredPaths.add(registration.path) + } + + async clear(path: string): Promise { + if (!this.registeredPaths.has(path)) { + return + } + + await clearPendingWebhookVerification(path) + this.registeredPaths.delete(path) + } + + async clearAll(): Promise { + for (const path of this.registeredPaths) { + await clearPendingWebhookVerification(path) + } + + this.registeredPaths.clear() + } +} diff --git a/apps/sim/lib/webhooks/processor.ts b/apps/sim/lib/webhooks/processor.ts index df45c1f981..46d8133721 100644 --- a/apps/sim/lib/webhooks/processor.ts +++ b/apps/sim/lib/webhooks/processor.ts @@ -10,6 +10,11 @@ import { isProd } from '@/lib/core/config/feature-flags' import { safeCompare } from '@/lib/core/security/encryption' import { getEffectiveDecryptedEnv } from '@/lib/environment/utils' import { preprocessExecution } from '@/lib/execution/preprocessing' +import { + getPendingWebhookVerification, + matchesPendingWebhookVerificationProbe, + requiresPendingWebhookVerification, +} from '@/lib/webhooks/pending-verification' import { convertSquareBracketsToTwiML } from '@/lib/webhooks/utils' import { handleSlackChallenge, @@ -190,6 +195,32 @@ export async function handleProviderChallenges( return null } +/** + * Returns a verification response for provider reachability probes that happen + * before a webhook row exists and therefore before provider lookup is possible. + */ +export async function handlePreLookupWebhookVerification( + method: string, + body: Record | undefined, + requestId: string, + path: string +): Promise { + const pendingVerification = await getPendingWebhookVerification(path) + if (!pendingVerification) { + return null + } + + if (!matchesPendingWebhookVerificationProbe(pendingVerification, { method, body })) { + return null + } + + logger.info( + `[${requestId}] Returning 200 for pending ${pendingVerification.provider} webhook verification on path: ${path}` + ) + + return NextResponse.json({ status: 'ok', message: 'Webhook endpoint verified' }) +} + /** * Handle provider-specific reachability tests that occur AFTER webhook lookup. * @@ -283,15 +314,12 @@ export function shouldSkipWebhookEvent(webhook: any, body: any, requestId: strin return false } -/** Providers that validate webhook URLs during creation, before workflow deployment */ -const PROVIDERS_WITH_PRE_DEPLOYMENT_VERIFICATION = new Set(['grain']) - /** Returns 200 OK for providers that validate URLs before the workflow is deployed */ export function handlePreDeploymentVerification( webhook: any, requestId: string ): NextResponse | null { - if (PROVIDERS_WITH_PRE_DEPLOYMENT_VERIFICATION.has(webhook.provider)) { + if (requiresPendingWebhookVerification(webhook.provider)) { logger.info( `[${requestId}] ${webhook.provider} webhook - block not in deployment, returning 200 OK for URL validation` ) diff --git a/apps/sim/lib/webhooks/provider-subscriptions.ts b/apps/sim/lib/webhooks/provider-subscriptions.ts index dbab9c6646..4efbeb35e3 100644 --- a/apps/sim/lib/webhooks/provider-subscriptions.ts +++ b/apps/sim/lib/webhooks/provider-subscriptions.ts @@ -769,14 +769,13 @@ export async function deleteGrainWebhook(webhook: any, requestId: string): Promi return } - const grainApiUrl = `https://api.grain.com/_/public-api/v2/hooks/${externalId}` + const grainApiUrl = `https://api.grain.com/_/public-api/hooks/${externalId}` const grainResponse = await fetch(grainApiUrl, { method: 'DELETE', headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', - 'Public-Api-Version': '2025-10-31', }, }) @@ -1237,8 +1236,7 @@ export async function createGrainWebhookSubscription( ): Promise<{ id: string; eventTypes: string[] } | undefined> { try { const { path, providerConfig } = webhookData - const { apiKey, triggerId, includeHighlights, includeParticipants, includeAiSummary } = - providerConfig || {} + const { apiKey, triggerId, viewId } = providerConfig || {} if (!apiKey) { grainLogger.warn(`[${requestId}] Missing apiKey for Grain webhook creation.`, { @@ -1249,32 +1247,39 @@ export async function createGrainWebhookSubscription( ) } - const hookTypeMap: Record = { - grain_webhook: 'recording_added', - grain_recording_created: 'recording_added', - grain_recording_updated: 'recording_added', - grain_highlight_created: 'recording_added', - grain_highlight_updated: 'recording_added', - grain_story_created: 'recording_added', - grain_upload_status: 'upload_status', + if (!viewId) { + grainLogger.warn(`[${requestId}] Missing viewId for Grain webhook creation.`, { + webhookId: webhookData.id, + triggerId, + }) + throw new Error( + 'Grain view ID is required. Please provide the Grain view ID from GET /_/public-api/views in the trigger configuration.' + ) + } + + const actionMap: Record> = { + grain_recording_created: ['added'], + grain_recording_updated: ['updated'], + grain_highlight_created: ['added'], + grain_highlight_updated: ['updated'], + grain_story_created: ['added'], } const eventTypeMap: Record = { grain_webhook: [], grain_recording_created: ['recording_added'], grain_recording_updated: ['recording_updated'], - grain_highlight_created: ['highlight_created'], + grain_highlight_created: ['highlight_added'], grain_highlight_updated: ['highlight_updated'], - grain_story_created: ['story_created'], - grain_upload_status: ['upload_status'], + grain_story_created: ['story_added'], } - const hookType = hookTypeMap[triggerId] ?? 'recording_added' + const actions = actionMap[triggerId] ?? [] const eventTypes = eventTypeMap[triggerId] ?? [] - if (!hookTypeMap[triggerId]) { + if (!triggerId || (!(triggerId in actionMap) && triggerId !== 'grain_webhook')) { grainLogger.warn( - `[${requestId}] Unknown triggerId for Grain: ${triggerId}, defaulting to recording_added`, + `[${requestId}] Unknown triggerId for Grain: ${triggerId}, defaulting to all actions`, { webhookId: webhookData.id, } @@ -1283,32 +1288,23 @@ export async function createGrainWebhookSubscription( grainLogger.info(`[${requestId}] Creating Grain webhook`, { triggerId, - hookType, + viewId, + actions, eventTypes, webhookId: webhookData.id, }) const notificationUrl = `${getBaseUrl()}/api/webhooks/trigger/${path}` - const grainApiUrl = 'https://api.grain.com/_/public-api/v2/hooks/create' + const grainApiUrl = 'https://api.grain.com/_/public-api/hooks' const requestBody: Record = { + version: 2, hook_url: notificationUrl, - hook_type: hookType, - } - - const include: Record = {} - if (includeHighlights) { - include.highlights = true - } - if (includeParticipants) { - include.participants = true - } - if (includeAiSummary) { - include.ai_summary = true + view_id: viewId, } - if (Object.keys(include).length > 0) { - requestBody.include = include + if (actions.length > 0) { + requestBody.actions = actions } const grainResponse = await fetch(grainApiUrl, { @@ -1316,7 +1312,6 @@ export async function createGrainWebhookSubscription( headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', - 'Public-Api-Version': '2025-10-31', }, body: JSON.stringify(requestBody), }) @@ -1349,15 +1344,29 @@ export async function createGrainWebhookSubscription( throw new Error(userFriendlyMessage) } + const grainWebhookId = responseBody.id + + if (!grainWebhookId) { + grainLogger.error( + `[${requestId}] Grain webhook creation response missing id for webhook ${webhookData.id}.`, + { + response: responseBody, + } + ) + throw new Error( + 'Grain webhook created but no webhook ID was returned in the response. Cannot track subscription.' + ) + } + grainLogger.info( `[${requestId}] Successfully created webhook in Grain for webhook ${webhookData.id}.`, { - grainWebhookId: responseBody.id, + grainWebhookId, eventTypes, } ) - return { id: responseBody.id, eventTypes } + return { id: grainWebhookId, eventTypes } } catch (error: any) { grainLogger.error( `[${requestId}] Exception during Grain webhook creation for webhook ${webhookData.id}.`, diff --git a/apps/sim/tools/grain/create_hook.ts b/apps/sim/tools/grain/create_hook.ts index 897dea18af..272a5d7527 100644 --- a/apps/sim/tools/grain/create_hook.ts +++ b/apps/sim/tools/grain/create_hook.ts @@ -20,109 +20,38 @@ export const grainCreateHookTool: ToolConfig ({ 'Content-Type': 'application/json', Authorization: `Bearer ${params.apiKey}`, - 'Public-Api-Version': '2025-10-31', }), body: (params) => { const body: Record = { + version: 2, hook_url: params.hookUrl, - hook_type: params.hookType, - } - - const filter: Record = {} - if (params.filterBeforeDatetime) { - filter.before_datetime = params.filterBeforeDatetime - } - if (params.filterAfterDatetime) { - filter.after_datetime = params.filterAfterDatetime - } - if (params.filterParticipantScope) { - filter.participant_scope = params.filterParticipantScope + view_id: params.viewId, } - if (params.filterTeamId) { - filter.team = params.filterTeamId - } - if (params.filterMeetingTypeId) { - filter.meeting_type = params.filterMeetingTypeId - } - if (Object.keys(filter).length > 0) { - body.filter = filter - } - - const include: Record = {} - if (params.includeHighlights) { - include.highlights = true - } - if (params.includeParticipants) { - include.participants = true - } - if (params.includeAiSummary) { - include.ai_summary = true - } - if (Object.keys(include).length > 0) { - body.include = include + if (params.actions && params.actions.length > 0) { + body.actions = params.actions } return body @@ -136,6 +65,10 @@ export const grainCreateHookTool: ToolConfig `https://api.grain.com/_/public-api/v2/hooks/${params.hookId}`, + url: (params) => `https://api.grain.com/_/public-api/hooks/${params.hookId}`, method: 'DELETE', headers: (params) => ({ 'Content-Type': 'application/json', Authorization: `Bearer ${params.apiKey}`, - 'Public-Api-Version': '2025-10-31', }), }, diff --git a/apps/sim/tools/grain/index.ts b/apps/sim/tools/grain/index.ts index d27baa4543..98ba6187f8 100644 --- a/apps/sim/tools/grain/index.ts +++ b/apps/sim/tools/grain/index.ts @@ -6,3 +6,4 @@ export { grainListHooksTool } from './list_hooks' export { grainListMeetingTypesTool } from './list_meeting_types' export { grainListRecordingsTool } from './list_recordings' export { grainListTeamsTool } from './list_teams' +export { grainListViewsTool } from './list_views' diff --git a/apps/sim/tools/grain/list_hooks.ts b/apps/sim/tools/grain/list_hooks.ts index ee01b77a44..bfd0d7c2c3 100644 --- a/apps/sim/tools/grain/list_hooks.ts +++ b/apps/sim/tools/grain/list_hooks.ts @@ -17,12 +17,11 @@ export const grainListHooksTool: ToolConfig ({ 'Content-Type': 'application/json', Authorization: `Bearer ${params.apiKey}`, - 'Public-Api-Version': '2025-10-31', }), }, @@ -51,9 +50,8 @@ export const grainListHooksTool: ToolConfig = { + id: 'grain_list_views', + name: 'Grain List Views', + description: 'List available Grain views for webhook subscriptions', + version: '1.0.0', + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Grain API key (Personal Access Token)', + }, + typeFilter: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Optional view type filter: recordings, highlights, or stories', + }, + }, + + request: { + url: (params) => + params.typeFilter + ? `https://api.grain.com/_/public-api/views?type_filter=${encodeURIComponent(params.typeFilter)}` + : 'https://api.grain.com/_/public-api/views', + method: 'GET', + headers: (params) => ({ + 'Content-Type': 'application/json', + Authorization: `Bearer ${params.apiKey}`, + }), + }, + + transformResponse: async (response) => { + const data = await response.json() + + if (!response.ok) { + throw new Error(data.error || data.message || 'Failed to list views') + } + + return { + success: true, + output: { + views: data.views || data || [], + }, + } + }, + + outputs: { + views: { + type: 'array', + description: 'Array of Grain views', + items: { + type: 'object', + properties: { + id: { type: 'string', description: 'View UUID' }, + name: { type: 'string', description: 'View name' }, + type: { type: 'string', description: 'View type: recordings, highlights, or stories' }, + }, + }, + }, + }, +} diff --git a/apps/sim/tools/grain/types.ts b/apps/sim/tools/grain/types.ts index 8b9b11857e..572cabb4a4 100644 --- a/apps/sim/tools/grain/types.ts +++ b/apps/sim/tools/grain/types.ts @@ -94,33 +94,27 @@ export interface GrainRecording { export interface GrainHook { id: string enabled: boolean + version?: number hook_url: string - hook_type: 'recording_added' | 'upload_status' - filter: GrainRecordingFilter - include: GrainRecordingInclude + view_id?: string + actions?: Array<'added' | 'updated' | 'removed'> inserted_at: string } -export interface GrainRecordingFilter { - before_datetime?: string - after_datetime?: string - attendance?: 'hosted' | 'attended' - participant_scope?: 'internal' | 'external' - title_search?: string - team?: string - meeting_type?: string -} - -export interface GrainRecordingInclude { - highlights?: boolean - participants?: boolean - ai_summary?: boolean - private_notes?: boolean - calendar_event?: boolean - hubspot?: boolean - ai_template_sections?: { - format?: 'json' | 'markdown' | 'text' - allowed_sections?: string[] +export interface GrainView { + id: string + name?: string + type?: 'recordings' | 'highlights' | 'stories' +} + +export interface GrainListViewsParams { + apiKey: string + typeFilter?: 'recordings' | 'highlights' | 'stories' +} + +export interface GrainListViewsResponse extends ToolResponse { + output: { + views: GrainView[] } } @@ -193,15 +187,8 @@ export interface GrainListMeetingTypesResponse extends ToolResponse { export interface GrainCreateHookParams { apiKey: string hookUrl: string - hookType: 'recording_added' | 'upload_status' - filterBeforeDatetime?: string - filterAfterDatetime?: string - filterParticipantScope?: 'internal' | 'external' - filterTeamId?: string - filterMeetingTypeId?: string - includeHighlights?: boolean - includeParticipants?: boolean - includeAiSummary?: boolean + viewId: string + actions?: Array<'added' | 'updated' | 'removed'> } export interface GrainCreateHookResponse extends ToolResponse { diff --git a/apps/sim/tools/registry.ts b/apps/sim/tools/registry.ts index 4498d5b5a7..86ce7908ee 100644 --- a/apps/sim/tools/registry.ts +++ b/apps/sim/tools/registry.ts @@ -933,6 +933,7 @@ import { grainListMeetingTypesTool, grainListRecordingsTool, grainListTeamsTool, + grainListViewsTool, } from '@/tools/grain' import { greenhouseGetApplicationTool, @@ -3162,6 +3163,7 @@ export const tools: Record = { grain_get_transcript: grainGetTranscriptTool, grain_list_teams: grainListTeamsTool, grain_list_meeting_types: grainListMeetingTypesTool, + grain_list_views: grainListViewsTool, grain_create_hook: grainCreateHookTool, grain_list_hooks: grainListHooksTool, grain_delete_hook: grainDeleteHookTool, diff --git a/apps/sim/triggers/generic/webhook.ts b/apps/sim/triggers/generic/webhook.ts index 295c58a739..d9e0e2ea5f 100644 --- a/apps/sim/triggers/generic/webhook.ts +++ b/apps/sim/triggers/generic/webhook.ts @@ -70,6 +70,15 @@ export const genericWebhookTrigger: TriggerConfig = { defaultValue: 'default', mode: 'trigger', }, + { + id: 'verifyTestEvents', + title: 'Verify Test Events', + type: 'switch', + description: + 'Return a temporary 200 response for test or verification probes on this webhook URL during setup.', + defaultValue: false, + mode: 'trigger', + }, { id: 'responseStatusCode', title: 'Response Status Code', @@ -120,6 +129,7 @@ export const genericWebhookTrigger: TriggerConfig = { 'All request data (headers, body, query parameters) will be available in your workflow.', 'If authentication is enabled, include the token in requests using either the custom header or "Authorization: Bearer TOKEN".', 'To deduplicate incoming events, set the Deduplication Field to the dot-notation path of a unique identifier in the payload (e.g. "event.id"). Duplicate values within 7 days will be skipped.', + 'Enable "Verify Test Events" only if the sending service needs a temporary 200 response while validating the webhook URL.', ] .map( (instruction, index) => diff --git a/apps/sim/triggers/grain/highlight_created.ts b/apps/sim/triggers/grain/highlight_created.ts index 2c03cfa360..5f5bdb310c 100644 --- a/apps/sim/triggers/grain/highlight_created.ts +++ b/apps/sim/triggers/grain/highlight_created.ts @@ -25,6 +25,19 @@ export const grainHighlightCreatedTrigger: TriggerConfig = { value: 'grain_highlight_created', }, }, + { + id: 'viewId', + title: 'View ID', + type: 'short-input', + placeholder: 'Enter Grain highlight view UUID', + description: 'Required by Grain to create the webhook subscription.', + required: true, + mode: 'trigger', + condition: { + field: 'selectedTriggerId', + value: 'grain_highlight_created', + }, + }, { id: 'triggerSave', title: '', diff --git a/apps/sim/triggers/grain/highlight_updated.ts b/apps/sim/triggers/grain/highlight_updated.ts index d2047023db..13c08b22e1 100644 --- a/apps/sim/triggers/grain/highlight_updated.ts +++ b/apps/sim/triggers/grain/highlight_updated.ts @@ -25,6 +25,19 @@ export const grainHighlightUpdatedTrigger: TriggerConfig = { value: 'grain_highlight_updated', }, }, + { + id: 'viewId', + title: 'View ID', + type: 'short-input', + placeholder: 'Enter Grain highlight view UUID', + description: 'Required by Grain to create the webhook subscription.', + required: true, + mode: 'trigger', + condition: { + field: 'selectedTriggerId', + value: 'grain_highlight_updated', + }, + }, { id: 'triggerSave', title: '', diff --git a/apps/sim/triggers/grain/recording_created.ts b/apps/sim/triggers/grain/recording_created.ts index da1c6096ef..c2af9a7086 100644 --- a/apps/sim/triggers/grain/recording_created.ts +++ b/apps/sim/triggers/grain/recording_created.ts @@ -25,6 +25,19 @@ export const grainRecordingCreatedTrigger: TriggerConfig = { value: 'grain_recording_created', }, }, + { + id: 'viewId', + title: 'View ID', + type: 'short-input', + placeholder: 'Enter Grain recording view UUID', + description: 'Required by Grain to create the webhook subscription.', + required: true, + mode: 'trigger', + condition: { + field: 'selectedTriggerId', + value: 'grain_recording_created', + }, + }, { id: 'triggerSave', title: '', diff --git a/apps/sim/triggers/grain/recording_updated.ts b/apps/sim/triggers/grain/recording_updated.ts index d7afdddfa0..22c74fc586 100644 --- a/apps/sim/triggers/grain/recording_updated.ts +++ b/apps/sim/triggers/grain/recording_updated.ts @@ -25,6 +25,19 @@ export const grainRecordingUpdatedTrigger: TriggerConfig = { value: 'grain_recording_updated', }, }, + { + id: 'viewId', + title: 'View ID', + type: 'short-input', + placeholder: 'Enter Grain recording view UUID', + description: 'Required by Grain to create the webhook subscription.', + required: true, + mode: 'trigger', + condition: { + field: 'selectedTriggerId', + value: 'grain_recording_updated', + }, + }, { id: 'triggerSave', title: '', diff --git a/apps/sim/triggers/grain/story_created.ts b/apps/sim/triggers/grain/story_created.ts index abe86698b1..f4a1dc4c11 100644 --- a/apps/sim/triggers/grain/story_created.ts +++ b/apps/sim/triggers/grain/story_created.ts @@ -25,6 +25,19 @@ export const grainStoryCreatedTrigger: TriggerConfig = { value: 'grain_story_created', }, }, + { + id: 'viewId', + title: 'View ID', + type: 'short-input', + placeholder: 'Enter Grain story view UUID', + description: 'Required by Grain to create the webhook subscription.', + required: true, + mode: 'trigger', + condition: { + field: 'selectedTriggerId', + value: 'grain_story_created', + }, + }, { id: 'triggerSave', title: '', diff --git a/apps/sim/triggers/grain/utils.ts b/apps/sim/triggers/grain/utils.ts index ea04655497..ead2bed6cd 100644 --- a/apps/sim/triggers/grain/utils.ts +++ b/apps/sim/triggers/grain/utils.ts @@ -18,7 +18,9 @@ export const grainTriggerOptions = [ export function grainSetupInstructions(eventType: string): string { const instructions = [ 'Enter your Grain API Key (Personal Access Token) above.', - 'You can find or create your API key in Grain at Settings > Integrations > API. See the Grain API documentation for details.', + `Enter the Grain view ID that matches the ${eventType} trigger. Grain requires view_id for webhook creation.`, + 'Use the Grain "List Views" tool or GET /_/public-api/views to find the correct view ID.', + 'You can find or create your API key in Grain at Workspace Settings > API under Integrations on grain.com.', 'The webhook will be automatically deleted when you remove this trigger.', ] diff --git a/apps/sim/triggers/grain/webhook.ts b/apps/sim/triggers/grain/webhook.ts index 4cbe0c3a89..19e1362371 100644 --- a/apps/sim/triggers/grain/webhook.ts +++ b/apps/sim/triggers/grain/webhook.ts @@ -6,7 +6,7 @@ export const grainWebhookTrigger: TriggerConfig = { id: 'grain_webhook', name: 'Grain Webhook', provider: 'grain', - description: 'Generic webhook trigger for all Grain events', + description: 'Generic webhook trigger for all actions in a selected Grain view', version: '1.0.0', icon: GrainIcon, @@ -25,6 +25,19 @@ export const grainWebhookTrigger: TriggerConfig = { value: 'grain_webhook', }, }, + { + id: 'viewId', + title: 'View ID', + type: 'short-input', + placeholder: 'Enter Grain view UUID', + description: 'Required by Grain to create the webhook subscription.', + required: true, + mode: 'trigger', + condition: { + field: 'selectedTriggerId', + value: 'grain_webhook', + }, + }, { id: 'triggerSave', title: '',