From 0fcb06847acab915601d75cc038ebe57251df631 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 15 Nov 2026 16:41:45 -0800 Subject: [PATCH 1/4] =?UTF-8?q?fix(integrations):=20sweep2=20v4=20?= =?UTF-8?q?=E2=80=94=20read=20the=20mapper=20operation=20from=20the=20tool?= =?UTF-8?q?-call=20context=20and=20validate=20integrations=20against=20ven?= =?UTF-8?q?dor=20specs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/sim/blocks/blocks/brex.test.ts | 107 ++++++++ apps/sim/blocks/blocks/brex.ts | 38 +-- apps/sim/blocks/blocks/calcom.test.ts | 126 ++++++++++ apps/sim/blocks/blocks/calcom.ts | 131 ++++++++-- apps/sim/blocks/blocks/calendly.test.ts | 55 ++++ apps/sim/blocks/blocks/calendly.ts | 47 +++- apps/sim/blocks/blocks/ramp.ts | 3 + apps/sim/blocks/blocks/shopify.test.ts | 63 +++++ apps/sim/blocks/blocks/shopify.ts | 136 +++++----- apps/sim/blocks/blocks/typeform.test.ts | 65 +++++ apps/sim/blocks/blocks/typeform.ts | 110 ++++---- apps/sim/blocks/blocks/webflow.test.ts | 46 ++++ apps/sim/blocks/blocks/webflow.ts | 25 +- apps/sim/blocks/blocks/wordpress.test.ts | 65 +++++ apps/sim/blocks/blocks/wordpress.ts | 238 ++++++++++-------- apps/sim/blocks/blocks/zoom.test.ts | 94 +++++++ apps/sim/blocks/blocks/zoom.ts | 171 +++++++------ apps/sim/lib/internal/typeform/operations.ts | 21 +- apps/sim/lib/internal/wordpress/operations.ts | 9 +- apps/sim/lib/internal/zoom/operations.test.ts | 15 ++ apps/sim/lib/internal/zoom/operations.ts | 3 +- apps/sim/tools/brex/create_spend_limit.ts | 2 +- apps/sim/tools/brex/get_budget.ts | 2 +- apps/sim/tools/brex/get_company.test.ts | 20 ++ apps/sim/tools/brex/get_company.ts | 2 +- apps/sim/tools/brex/get_current_user.ts | 2 +- apps/sim/tools/brex/get_expense.ts | 2 +- apps/sim/tools/brex/get_spend_limit.ts | 2 +- apps/sim/tools/brex/get_user.ts | 2 +- apps/sim/tools/brex/list_cards.ts | 3 +- apps/sim/tools/brex/list_expenses.ts | 2 +- apps/sim/tools/brex/types.ts | 5 +- apps/sim/tools/brex/update_expense.ts | 2 +- apps/sim/tools/calcom/cancel_booking.ts | 3 +- apps/sim/tools/calcom/confirm_booking.ts | 3 +- apps/sim/tools/calcom/create_event_type.ts | 6 + apps/sim/tools/calcom/decline_booking.ts | 3 +- apps/sim/tools/calcom/delete_event_type.ts | 3 +- apps/sim/tools/calcom/delete_schedule.ts | 3 +- apps/sim/tools/calcom/get_booking.ts | 3 +- apps/sim/tools/calcom/get_event_type.ts | 9 +- apps/sim/tools/calcom/get_schedule.ts | 3 +- apps/sim/tools/calcom/list_bookings.ts | 46 +++- apps/sim/tools/calcom/list_event_types.ts | 6 + apps/sim/tools/calcom/requests.test.ts | 53 ++++ apps/sim/tools/calcom/reschedule_booking.ts | 3 +- apps/sim/tools/calcom/types.ts | 4 + apps/sim/tools/calcom/update_event_type.ts | 29 ++- apps/sim/tools/calcom/update_schedule.ts | 3 +- apps/sim/tools/calendly/calendly.test.ts | 63 ++++- apps/sim/tools/calendly/cancel_event.ts | 6 +- .../tools/calendly/create_event_invitee.ts | 20 +- apps/sim/tools/calendly/create_webhook.ts | 4 +- .../tools/calendly/delete_invitee_no_show.ts | 2 +- apps/sim/tools/calendly/delete_webhook.ts | 4 +- apps/sim/tools/calendly/get_event_invitee.ts | 2 +- apps/sim/tools/calendly/get_event_type.ts | 2 +- .../sim/tools/calendly/get_scheduled_event.ts | 2 +- apps/sim/tools/calendly/get_user.ts | 2 +- .../sim/tools/calendly/list_event_invitees.ts | 4 +- apps/sim/tools/calendly/list_event_types.ts | 12 +- .../calendly/list_organization_memberships.ts | 2 +- .../tools/calendly/list_scheduled_events.ts | 2 +- apps/sim/tools/calendly/list_webhooks.ts | 2 + apps/sim/tools/calendly/types.ts | 4 + apps/sim/tools/calendly/utils.ts | 27 +- apps/sim/tools/shopify/get_collection.ts | 3 + apps/sim/tools/shopify/list_locations.ts | 2 +- apps/sim/tools/typeform/create_form.ts | 3 +- apps/sim/tools/typeform/delete_form.ts | 3 +- apps/sim/tools/typeform/files.test.ts | 21 ++ apps/sim/tools/typeform/files.ts | 4 +- apps/sim/tools/typeform/get_form.ts | 3 +- apps/sim/tools/typeform/insights.ts | 5 +- apps/sim/tools/typeform/requests.test.ts | 45 ++++ apps/sim/tools/typeform/responses.ts | 27 +- apps/sim/tools/typeform/types.ts | 2 + apps/sim/tools/typeform/update_form.ts | 5 +- apps/sim/tools/webflow/create_item.ts | 16 +- apps/sim/tools/webflow/delete_item.ts | 11 +- apps/sim/tools/webflow/get_item.ts | 15 +- apps/sim/tools/webflow/list_items.ts | 20 +- apps/sim/tools/webflow/types.ts | 2 +- apps/sim/tools/webflow/update_item.ts | 15 +- apps/sim/tools/webflow/webflow.test.ts | 19 ++ apps/sim/tools/wordpress/create_category.ts | 6 +- apps/sim/tools/wordpress/create_comment.ts | 12 +- apps/sim/tools/wordpress/create_page.ts | 14 +- apps/sim/tools/wordpress/create_post.ts | 23 +- apps/sim/tools/wordpress/create_tag.ts | 4 +- apps/sim/tools/wordpress/delete_category.ts | 3 +- apps/sim/tools/wordpress/delete_comment.ts | 3 +- apps/sim/tools/wordpress/delete_media.ts | 3 +- apps/sim/tools/wordpress/delete_page.ts | 3 +- apps/sim/tools/wordpress/delete_post.ts | 3 +- apps/sim/tools/wordpress/delete_tag.ts | 3 +- apps/sim/tools/wordpress/get_category.ts | 4 +- apps/sim/tools/wordpress/get_current_user.ts | 4 +- apps/sim/tools/wordpress/get_media.ts | 4 +- apps/sim/tools/wordpress/get_page.ts | 4 +- apps/sim/tools/wordpress/get_post.ts | 4 +- apps/sim/tools/wordpress/get_tag.ts | 4 +- apps/sim/tools/wordpress/get_user.ts | 34 ++- apps/sim/tools/wordpress/list_categories.ts | 3 +- apps/sim/tools/wordpress/list_comments.ts | 23 +- apps/sim/tools/wordpress/list_media.ts | 3 +- apps/sim/tools/wordpress/list_pages.ts | 3 +- apps/sim/tools/wordpress/list_posts.ts | 14 +- apps/sim/tools/wordpress/list_tags.ts | 3 +- apps/sim/tools/wordpress/list_users.ts | 41 ++- apps/sim/tools/wordpress/request.test.ts | 63 +++++ apps/sim/tools/wordpress/search_content.ts | 12 +- apps/sim/tools/wordpress/types.ts | 17 +- apps/sim/tools/wordpress/update_category.ts | 6 +- apps/sim/tools/wordpress/update_comment.ts | 4 +- apps/sim/tools/wordpress/update_page.ts | 14 +- apps/sim/tools/wordpress/update_post.ts | 23 +- apps/sim/tools/wordpress/update_tag.ts | 4 +- apps/sim/tools/wordpress/utils.ts | 15 ++ apps/sim/tools/zoom/delete_meeting.ts | 4 +- apps/sim/tools/zoom/delete_recording.ts | 6 +- apps/sim/tools/zoom/list_past_participants.ts | 3 +- apps/sim/tools/zoom/list_recordings.ts | 5 +- apps/sim/tools/zoom/update_meeting.ts | 3 +- apps/sim/tools/zoom/utils.test.ts | 31 +++ apps/sim/tools/zoom/utils.ts | 12 + 126 files changed, 2098 insertions(+), 524 deletions(-) create mode 100644 apps/sim/blocks/blocks/brex.test.ts create mode 100644 apps/sim/blocks/blocks/calcom.test.ts create mode 100644 apps/sim/blocks/blocks/calendly.test.ts create mode 100644 apps/sim/blocks/blocks/typeform.test.ts create mode 100644 apps/sim/blocks/blocks/webflow.test.ts create mode 100644 apps/sim/blocks/blocks/wordpress.test.ts create mode 100644 apps/sim/blocks/blocks/zoom.test.ts create mode 100644 apps/sim/tools/brex/get_company.test.ts create mode 100644 apps/sim/tools/calcom/requests.test.ts create mode 100644 apps/sim/tools/typeform/requests.test.ts create mode 100644 apps/sim/tools/wordpress/request.test.ts create mode 100644 apps/sim/tools/wordpress/utils.ts create mode 100644 apps/sim/tools/zoom/utils.test.ts create mode 100644 apps/sim/tools/zoom/utils.ts diff --git a/apps/sim/blocks/blocks/brex.test.ts b/apps/sim/blocks/blocks/brex.test.ts new file mode 100644 index 00000000000..8cf7fd36f0f --- /dev/null +++ b/apps/sim/blocks/blocks/brex.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, it } from 'vitest' +import { BrexBlock } from '@/blocks/blocks/brex' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** Runs the mapper the way each executor path merges it over the incoming params. */ +function runMapper(params: Record, context?: BlockToolParamsContext) { + const mapper = BrexBlock.tools.config?.params + if (!mapper) throw new Error('Brex block has no params mapper') + return { ...params, ...mapper(params, context) } +} + +describe('Brex tool-call mapping', () => { + it('prefers the block cash account field over the model cash account', () => { + const sent = runMapper( + { + apiKey: 'token', + accountId: 'acct_block', + cashAccountId: 'acct_model', + vendorPaymentInstrumentId: 'pi_1', + amount: 5000, + description: 'Invoice 42', + externalMemo: 'Thanks', + }, + { operation: 'create_transfer' } + ) + expect(sent.cashAccountId).toBe('acct_block') + expect(sent.amount).toBe(5000) + }) + + it('keeps the model cash account on a tool call when the block field is blank', () => { + const sent = runMapper( + { + apiKey: 'token', + cashAccountId: 'acct_model', + vendorPaymentInstrumentId: 'pi_1', + amount: 5000, + description: 'Invoice 42', + externalMemo: 'Thanks', + }, + { operation: 'create_transfer' } + ) + expect(sent.cashAccountId).toBe('acct_model') + }) + + it('prefers the block spend limit name, period and members over the model args', () => { + const sent = runMapper( + { + apiKey: 'token', + resourceName: 'Travel', + name: 'Model name', + spendLimitPeriodRecurrenceType: 'PER_MONTH', + periodRecurrenceType: 'PER_YEAR', + spendLimitMemberUserIds: 'u1,u2', + memberUserIds: 'u9', + baseLimitAmount: 1000, + }, + { operation: 'create_spend_limit' } + ) + expect(sent).toMatchObject({ + name: 'Travel', + periodRecurrenceType: 'PER_MONTH', + memberUserIds: 'u1,u2', + baseLimitAmount: 1000, + }) + }) + + it('prefers the block vendor email and phone fields over the model args', () => { + const sent = runMapper( + { apiKey: 'token', vendorId: 'v1', vendorEmail: 'ap@vendor.com', vendorPhone: '555' }, + { operation: 'update_vendor' } + ) + expect(sent).toMatchObject({ email: 'ap@vendor.com', phone: '555' }) + }) + + it('keeps the model vendor email on a tool call when the block field is blank', () => { + const sent = runMapper( + { apiKey: 'token', companyName: 'Acme', email: 'model@vendor.com' }, + { operation: 'create_vendor' } + ) + expect(sent.email).toBe('model@vendor.com') + }) +}) + +describe('Brex canvas list filters never reach writes', () => { + it('drops a saved List Users email filter from a vendor write', () => { + const sent = runMapper({ + operation: 'update_vendor', + apiKey: 'token', + vendorId: 'v1', + companyName: 'Acme', + email: 'alice@corp.com', + }) + expect(sent.email).toBeUndefined() + }) + + it('drops a saved List Spend Limits member filter from a new spend limit', () => { + const sent = runMapper({ + operation: 'create_spend_limit', + apiKey: 'token', + resourceName: 'Travel', + spendLimitPeriodRecurrenceType: 'PER_MONTH', + baseLimitAmount: '1000', + memberUserIds: 'u1,u2', + }) + expect(sent.memberUserIds).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/brex.ts b/apps/sim/blocks/blocks/brex.ts index 51e119edd6e..81339f966f3 100644 --- a/apps/sim/blocks/blocks/brex.ts +++ b/apps/sim/blocks/blocks/brex.ts @@ -1,7 +1,12 @@ import { BrexIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' /** Coerces a required money-amount field to a finite number, throwing on blank/non-numeric input rather than silently sending 0 or NaN to Brex. */ function toRequiredAmount(value: unknown, fieldLabel: string): number { @@ -640,7 +645,7 @@ export const BrexBlock: BlockConfig = { id: 'limitBufferPercentage', title: 'Limit Buffer Percentage', type: 'short-input', - placeholder: 'Flexible buffer on the limit as a 0-100 percentage', + placeholder: 'Flexible buffer on the limit as a whole-number percentage from 0 to 100', mode: 'advanced', condition: { field: 'operation', value: 'create_spend_limit' }, }, @@ -723,7 +728,7 @@ export const BrexBlock: BlockConfig = { wandConfig: { enabled: true, prompt: - 'Generate a comma-separated list of Brex expense payment statuses to filter by.\n\nValid statuses: NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED\n\nExamples:\n- "only cleared payments" -> CLEARED\n- "refunded or refunding" -> REFUNDED,REFUNDING\n\nReturn ONLY the comma-separated status values - no explanations, no extra text.', + 'Generate a comma-separated list of Brex expense payment statuses to filter by.\n\nValid statuses: NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED, HELD\n\nExamples:\n- "only cleared payments" -> CLEARED\n- "refunded or refunding" -> REFUNDED,REFUNDING\n\nReturn ONLY the comma-separated status values - no explanations, no extra text.', placeholder: 'Describe which payment statuses to include...', }, }, @@ -880,8 +885,9 @@ export const BrexBlock: BlockConfig = { ], config: { tool: (params) => `brex_${params.operation}`, - params: (params) => { - const { operation, apiKey } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { apiKey } = params const result: Record = { apiKey } switch (operation) { @@ -943,7 +949,7 @@ export const BrexBlock: BlockConfig = { result.budgetId = params.budgetId break case 'create_budget': { - result.name = params.resourceName + result.name = params.resourceName || toolCallArg(context, params.name) result.description = params.description result.parentBudgetId = params.parentBudgetId result.periodRecurrenceType = params.periodRecurrenceType @@ -961,8 +967,10 @@ export const BrexBlock: BlockConfig = { result.spendLimitId = params.spendLimitId break case 'create_spend_limit': { - result.name = params.resourceName - result.periodRecurrenceType = params.spendLimitPeriodRecurrenceType + result.name = params.resourceName || toolCallArg(context, params.name) + result.periodRecurrenceType = + params.spendLimitPeriodRecurrenceType || + toolCallArg(context, params.periodRecurrenceType) result.spendType = params.spendType result.expenseVisibility = params.expenseVisibility result.authorizationVisibility = params.authorizationVisibility @@ -991,8 +999,8 @@ export const BrexBlock: BlockConfig = { if (transactionLimitAmount !== undefined) result.transactionLimitAmount = transactionLimitAmount if (params.ownerUserIds) result.ownerUserIds = params.ownerUserIds - if (params.spendLimitMemberUserIds) - result.memberUserIds = params.spendLimitMemberUserIds + result.memberUserIds = + params.spendLimitMemberUserIds || toolCallArg(context, params.memberUserIds) break } case 'get_vendor': @@ -1000,20 +1008,20 @@ export const BrexBlock: BlockConfig = { break case 'create_vendor': result.companyName = params.companyName - if (params.vendorEmail) result.email = params.vendorEmail - if (params.vendorPhone) result.phone = params.vendorPhone + result.email = params.vendorEmail || toolCallArg(context, params.email) + result.phone = params.vendorPhone || toolCallArg(context, params.phone) break case 'update_vendor': result.vendorId = params.vendorId if (params.companyName) result.companyName = params.companyName - if (params.vendorEmail) result.email = params.vendorEmail - if (params.vendorPhone) result.phone = params.vendorPhone + result.email = params.vendorEmail || toolCallArg(context, params.email) + result.phone = params.vendorPhone || toolCallArg(context, params.phone) break case 'get_transfer': result.transferId = params.transferId break case 'create_transfer': { - result.cashAccountId = params.accountId + result.cashAccountId = params.accountId || toolCallArg(context, params.cashAccountId) result.vendorPaymentInstrumentId = params.vendorPaymentInstrumentId result.amount = toRequiredAmount(params.amount, 'Amount') if (params.currency) result.currency = params.currency diff --git a/apps/sim/blocks/blocks/calcom.test.ts b/apps/sim/blocks/blocks/calcom.test.ts new file mode 100644 index 00000000000..eeb03b3306b --- /dev/null +++ b/apps/sim/blocks/blocks/calcom.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it } from 'vitest' +import { CalComBlock } from '@/blocks/blocks/calcom' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = CalComBlock.tools.config?.params + if (!mapper) throw new Error('Cal.com block has no params mapper') + return mapper(params, context) +} + +/** What the tool receives: the mapper output spread over the params it was given. */ +function sentParams(params: Record, context?: BlockToolParamsContext) { + return { ...params, ...mapParams(params, context) } +} + +describe('Cal.com create booking on a tool call', () => { + it('lets pinned attendee fields win over the model attendee and keeps the rest', () => { + const sent = sentParams( + { + attendeeName: 'Pinned Name', + attendeeTimeZone: 'Europe/London', + attendee: { name: 'Model Name', email: 'model@x.com', timeZone: 'UTC' }, + eventTypeId: 123, + start: '2026-01-15T10:00:00Z', + }, + { operation: 'calcom_create_booking' } + ) + + expect(sent.attendee).toEqual({ + name: 'Pinned Name', + email: 'model@x.com', + timeZone: 'Europe/London', + }) + expect(sent.eventTypeId).toBe(123) + }) + + it('splits pinned comma-separated guests into an array', () => { + const sent = sentParams( + { guests: 'a@x.com, b@y.com', attendee: { name: 'A', timeZone: 'UTC' } }, + { operation: 'calcom_create_booking' } + ) + expect(sent.guests).toEqual(['a@x.com', 'b@y.com']) + }) + + it('coerces a pinned event type id string to a number', () => { + const sent = sentParams( + { eventTypeId: '456', attendee: { name: 'A', timeZone: 'UTC' } }, + { operation: 'calcom_create_booking' } + ) + expect(sent.eventTypeId).toBe(456) + }) +}) + +describe('Cal.com create booking on the canvas', () => { + it('accepts guests that already resolved to an array', () => { + const sent = sentParams({ + operation: 'calcom_create_booking', + attendeeName: 'A', + attendeeTimeZone: 'UTC', + guests: ['a@x.com'], + }) + expect(sent.guests).toEqual(['a@x.com']) + }) +}) + +describe('Cal.com list bookings', () => { + it('sends the pinned status instead of the model status on a tool call', () => { + const sent = sentParams( + { bookingStatus: 'past', status: 'upcoming' }, + { operation: 'calcom_list_bookings' } + ) + expect(sent.status).toBe('past') + }) + + it('keeps the model status and attendee filter when nothing is pinned', () => { + const sent = sentParams( + { status: 'upcoming', attendeeEmail: 'a@x.com', take: 5 }, + { operation: 'calcom_list_bookings' } + ) + expect(sent.status).toBe('upcoming') + expect(sent.attendeeEmail).toBe('a@x.com') + expect(sent.take).toBe(5) + }) + + it('does not filter by an attendee email left over from Create Booking on the canvas', () => { + const sent = sentParams({ + operation: 'calcom_list_bookings', + attendeeEmail: 'stale@x.com', + take: '10', + }) + expect(sent.attendeeEmail).toBeUndefined() + expect(sent.take).toBe(10) + }) + + it.each([null, ''])('drops blank advanced limit and offset (%j) on the canvas', (blank) => { + const sent = sentParams({ operation: 'calcom_list_bookings', take: blank, skip: blank }) + expect(sent.take).toBeUndefined() + expect(sent.skip).toBeUndefined() + }) +}) + +describe('Cal.com event type id on a tool call', () => { + it('uses the event type picked in the tool row', () => { + const sent = sentParams( + { eventTypeIdParam: '42', eventTypeId: 7 }, + { operation: 'calcom_get_event_type' } + ) + expect(sent.eventTypeId).toBe(42) + }) + + it('keeps the model event type id and fields on an update with nothing pinned', () => { + const sent = sentParams( + { eventTypeId: 7, lengthInMinutes: 45, scheduleId: 3 }, + { operation: 'calcom_update_event_type' } + ) + expect(sent).toMatchObject({ eventTypeId: 7, lengthInMinutes: 45, scheduleId: 3 }) + }) + + it('maps the pinned duration onto lengthInMinutes', () => { + const sent = sentParams( + { eventTypeId: 7, eventLength: '30' }, + { operation: 'calcom_update_event_type' } + ) + expect(sent.lengthInMinutes).toBe(30) + }) +}) diff --git a/apps/sim/blocks/blocks/calcom.ts b/apps/sim/blocks/blocks/calcom.ts index 3f7d0b4f09d..41233d0a1de 100644 --- a/apps/sim/blocks/blocks/calcom.ts +++ b/apps/sim/blocks/blocks/calcom.ts @@ -1,6 +1,8 @@ +import { isPlainRecord } from '@sim/utils/object' import { CalComIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' const EVENT_TYPE_FIELD = ['eventTypeSelector', 'eventTypeId'] as const @@ -350,6 +352,58 @@ Return ONLY the IANA timezone string - no explanations or quotes.`, ], condition: { field: 'operation', value: 'calcom_list_bookings' }, }, + { + id: 'filterAttendeeEmail', + title: 'Attendee Email', + type: 'short-input', + placeholder: 'Only bookings with this attendee', + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, + { + id: 'afterStart', + title: 'Starts After', + type: 'short-input', + placeholder: 'ISO 8601 (e.g., 2024-01-15T00:00:00Z)', + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, + { + id: 'beforeEnd', + title: 'Ends Before', + type: 'short-input', + placeholder: 'ISO 8601 (e.g., 2024-01-22T00:00:00Z)', + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, + { + id: 'sortStart', + title: 'Sort by Start', + type: 'dropdown', + options: [ + { label: 'None', id: '' }, + { label: 'Ascending', id: 'asc' }, + { label: 'Descending', id: 'desc' }, + ], + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, + { + id: 'take', + title: 'Limit', + type: 'short-input', + placeholder: 'Bookings to return (default 100)', + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, + { + id: 'skip', + title: 'Offset', + type: 'short-input', + placeholder: 'Bookings to skip (default 0)', + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, // Event Type fields { @@ -712,9 +766,9 @@ Return ONLY valid JSON - no explanations.`, ], config: { tool: (params) => params.operation || 'calcom_list_bookings', - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, oauthCredential, attendeeName, attendeeEmail, @@ -745,6 +799,11 @@ Return ONLY valid JSON - no explanations.`, duration, metadata, availability, + attendee, + status, + filterAttendeeEmail, + take, + skip, ...rest } = params @@ -759,12 +818,23 @@ Return ONLY valid JSON - no explanations.`, } switch (operation) { - case 'calcom_create_booking': - result.attendee = { - name: attendeeName, - ...(attendeeEmail && { email: attendeeEmail }), - timeZone: attendeeTimeZone, - ...(attendeePhone && { phoneNumber: attendeePhone }), + case 'calcom_create_booking': { + const modelAttendee = toolCallArg(context, attendee) + if (isPlainRecord(modelAttendee)) { + const pinned = Object.entries({ + name: attendeeName, + email: attendeeEmail, + timeZone: attendeeTimeZone, + phoneNumber: attendeePhone, + }).filter(([, value]) => value !== undefined && value !== null && value !== '') + result.attendee = { ...modelAttendee, ...Object.fromEntries(pinned) } + } else if (modelAttendee === undefined || attendeeName || attendeeTimeZone) { + result.attendee = { + name: attendeeName, + ...(attendeeEmail && { email: attendeeEmail }), + timeZone: attendeeTimeZone, + ...(attendeePhone && { phoneNumber: attendeePhone }), + } } { const eventTypeIdNum = toNumber(eventTypeId) @@ -772,7 +842,13 @@ Return ONLY valid JSON - no explanations.`, } if (start) result.start = start if (end) result.end = end - if (guests) result.guests = guests.split(',').map((g: string) => g.trim()) + if (guests) { + result.guests = Array.isArray(guests) + ? guests + : String(guests) + .split(',') + .map((g: string) => g.trim()) + } { const lengthNum = toNumber(lengthInMinutes) if (lengthNum !== undefined) result.lengthInMinutes = lengthNum @@ -785,6 +861,7 @@ Return ONLY valid JSON - no explanations.`, } } break + } case 'calcom_cancel_booking': if (bookingUid) result.bookingUid = bookingUid @@ -797,20 +874,28 @@ Return ONLY valid JSON - no explanations.`, if (reschedulingReason) result.reschedulingReason = reschedulingReason break - case 'calcom_list_bookings': - if (bookingStatus) result.status = bookingStatus + case 'calcom_list_bookings': { + const statusFilter = bookingStatus || toolCallArg(context, status) + if (statusFilter) result.status = statusFilter + result.attendeeEmail = filterAttendeeEmail || toolCallArg(context, attendeeEmail) + result.take = toNumber(take) + result.skip = toNumber(skip) break + } case 'calcom_create_event_type': case 'calcom_update_event_type': { if (operation === 'calcom_update_event_type') { - const eventTypeIdNum = toNumber(eventTypeIdParam) + const eventTypeIdNum = + toNumber(eventTypeIdParam) ?? toolCallArg(context, toNumber(eventTypeId)) if (eventTypeIdNum !== undefined) result.eventTypeId = eventTypeIdNum } - const lengthNum = toNumber(eventLength) + const lengthNum = + toNumber(eventLength) ?? toolCallArg(context, toNumber(lengthInMinutes)) if (lengthNum !== undefined) result.lengthInMinutes = lengthNum - const scheduleIdNum = toNumber(eventTypeScheduleId) + const scheduleIdNum = + toNumber(eventTypeScheduleId) ?? toolCallArg(context, toNumber(scheduleId)) if (scheduleIdNum !== undefined) result.scheduleId = scheduleIdNum const slotIntervalNum = toNumber(slotInterval) if (slotIntervalNum !== undefined) result.slotInterval = slotIntervalNum @@ -829,7 +914,8 @@ Return ONLY valid JSON - no explanations.`, case 'calcom_get_event_type': case 'calcom_delete_event_type': { - const eventTypeIdNum = toNumber(eventTypeIdParam) + const eventTypeIdNum = + toNumber(eventTypeIdParam) ?? toolCallArg(context, toNumber(eventTypeId)) if (eventTypeIdNum !== undefined) result.eventTypeId = eventTypeIdNum } break @@ -943,9 +1029,24 @@ Return ONLY valid JSON - no explanations.`, eventTypeSlug: { type: 'string', description: 'Event type slug' }, username: { type: 'string', description: 'Cal.com username' }, duration: { type: 'number', description: 'Slot duration in minutes' }, + filterAttendeeEmail: { type: 'string', description: 'List Bookings attendee email filter' }, + afterStart: { type: 'string', description: 'List bookings starting after this time' }, + beforeEnd: { type: 'string', description: 'List bookings ending before this time' }, + sortStart: { type: 'string', description: 'Sort bookings by start time (asc or desc)' }, + take: { type: 'number', description: 'Number of bookings to return' }, + skip: { type: 'number', description: 'Number of bookings to skip' }, }, outputs: { success: { type: 'boolean', description: 'Whether operation succeeded' }, + data: { + type: 'json', + description: + 'Cal.com response data: a booking, event type, or schedule object, an array of them for list operations, or the slots map keyed by date (YYYY-MM-DD) for Get Available Slots', + }, + pagination: { + type: 'json', + description: 'List Bookings pagination (totalItems, remainingItems, hasNextPage, ...)', + }, bookingUid: { type: 'string', description: 'Booking unique identifier' }, bookingId: { type: 'number', description: 'Booking ID' }, status: { type: 'string', description: 'Booking or event status' }, diff --git a/apps/sim/blocks/blocks/calendly.test.ts b/apps/sim/blocks/blocks/calendly.test.ts new file mode 100644 index 00000000000..a1c42436b45 --- /dev/null +++ b/apps/sim/blocks/blocks/calendly.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest' +import { CalendlyBlock } from '@/blocks/blocks/calendly' +import type { BlockToolParamsContext } from '@/blocks/types' +import { listEventTypesTool } from '@/tools/calendly/list_event_types' + +/** + * Assertions run against `{ ...inputs, ...mapper(inputs, context) }`, the shape both the canvas + * handler and the tool-call transform forward: a key the mapper leaves out keeps its raw value. + */ +describe('CalendlyBlock params mapper', () => { + const mapper = CalendlyBlock.tools.config?.params + if (!mapper) throw new Error('CalendlyBlock is missing its params mapper') + + const resolve = (inputs: Record, context?: BlockToolParamsContext) => ({ + ...inputs, + ...mapper(inputs, context), + }) + + const eventTypesUrl = (params: Record) => { + const url = listEventTypesTool.request.url + if (typeof url !== 'function') throw new Error('Expected a url builder') + return url(params as Parameters[0]) + } + + it('lists all event types on the canvas when the Active Only switch was turned off', () => { + const params = resolve({ + operation: 'calendly_list_event_types', + apiKey: 'k', + user: 'user-1', + active: false, + }) + + expect(eventTypesUrl(params)).not.toContain('active=') + }) + + it('lists all event types on a tool call whose stored row has the switch off', () => { + const params = resolve( + { apiKey: 'k', user: 'user-1', active: false }, + { operation: 'calendly_list_event_types' } + ) + + expect(eventTypesUrl(params)).not.toContain('active=') + }) + + it('still filters to active event types when the switch is on', () => { + const params = resolve({ + operation: 'calendly_list_event_types', + apiKey: 'k', + user: 'user-1', + active: true, + }) + + expect(eventTypesUrl(params)).toContain('active=true') + }) +}) diff --git a/apps/sim/blocks/blocks/calendly.ts b/apps/sim/blocks/blocks/calendly.ts index 2f4a57f06c4..8187514d98e 100644 --- a/apps/sim/blocks/blocks/calendly.ts +++ b/apps/sim/blocks/blocks/calendly.ts @@ -34,7 +34,7 @@ export const CalendlyBlock: BlockConfig = { authMode: AuthMode.ApiKey, triggerAllowed: true, longDescription: - 'Manage event types, scheduled events, invitees, and webhooks. Trigger workflows based on Calendly webhook events (invitee scheduled, invitee canceled, routing form submitted). Requires Personal Access Token.', + 'Manage event types, scheduled events, invitees, bookings, availability, and routing forms. Trigger workflows based on Calendly webhook events (invitee scheduled, invitee canceled, routing form submitted). Requires Personal Access Token.', docsLink: 'https://docs.sim.ai/integrations/calendly', category: 'tools', integrationType: IntegrationType.Productivity, @@ -445,9 +445,43 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes prompt: 'Generate a JSON array of guest email address strings, for example ["guest@example.com"]. Return ONLY the JSON array - no explanations, no extra text.', placeholder: 'Describe the guests to copy on the invite...', + generationType: 'json-array', + }, + }, + { + id: 'location', + title: 'Location', + type: 'long-input', + placeholder: '{"kind": "outbound_call", "location": "+14155551234"}', + description: + 'Must match a location on the event type. Leave empty for round robin event types.', + mode: 'advanced', + condition: { field: 'operation', value: 'calendly_create_event_invitee' }, + wandConfig: { + enabled: true, + prompt: + 'Generate a Calendly invitee location JSON object with a "kind" (physical, inbound_call, outbound_call, zoom_conference, google_conference, gotomeeting_conference, microsoft_teams_conference, webex_conference, ask_invitee, or custom) and, for physical, outbound_call, ask_invitee, and custom, a "location" string. Return ONLY the JSON object - no explanations, no extra text.', + placeholder: 'Describe where the meeting takes place...', generationType: 'json-object', }, }, + { + id: 'questionsAndAnswers', + title: 'Questions and Answers', + type: 'long-input', + placeholder: '[{"question": "Company", "answer": "Acme", "position": 0}]', + description: + "Answers to the event type's booking questions. Questions must match exactly; required ones must be answered.", + mode: 'advanced', + condition: { field: 'operation', value: 'calendly_create_event_invitee' }, + wandConfig: { + enabled: true, + prompt: + 'Generate a JSON array of Calendly booking answers, each an object with "question" (the exact question text), "answer", and "position" (the question\'s zero-based order). Return ONLY the JSON array - no explanations, no extra text.', + placeholder: 'Describe the answers to the booking questions...', + generationType: 'json-array', + }, + }, { id: 'inviteeUri', title: 'Invitee URI', @@ -583,8 +617,8 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes return { ...rest, - // The switch cannot express "inactive only", so off means unfiltered, not `active=false`. - ...(active === true && { active: true }), + // Off means unfiltered, not `active=false`; always written so it overrides the raw input. + active: active === true ? true : undefined, ...(events !== undefined && { events: parseJsonArray(events, 'events') }), ...(eventGuests !== undefined && { eventGuests: parseJsonArray(eventGuests, 'eventGuests'), @@ -621,6 +655,11 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes inviteeTimezone: { type: 'string', description: 'Timezone of the invitee' }, textReminderNumber: { type: 'string', description: 'Phone number for SMS reminders' }, eventGuests: { type: 'json', description: 'Array of additional guest email addresses' }, + location: { type: 'json', description: 'Meeting location ({kind, location})' }, + questionsAndAnswers: { + type: 'json', + description: 'Answers to booking questions ([{question, answer, position}])', + }, role: { type: 'string', description: 'Filter memberships by role' }, formUri: { type: 'string', description: 'Routing form UUID or URI' }, count: { type: 'number', description: 'Results per page' }, @@ -803,7 +842,7 @@ export const CalendlyV2Block: BlockConfig = { hideFromToolbar: false, sunset: undefined, longDescription: - 'Manage event types, scheduled events, invitees, and webhooks. Trigger workflows based on Calendly webhook events (invitee scheduled, invitee canceled, routing form submitted).', + 'Manage event types, scheduled events, invitees, bookings, availability, and routing forms. Trigger workflows based on Calendly webhook events (invitee scheduled, invitee canceled, routing form submitted).', ...withSavedCredential(CalendlyBlock, { id: 'credential', type: 'oauth-input', diff --git a/apps/sim/blocks/blocks/ramp.ts b/apps/sim/blocks/blocks/ramp.ts index 3d4f0e7d23b..15849684e14 100644 --- a/apps/sim/blocks/blocks/ramp.ts +++ b/apps/sim/blocks/blocks/ramp.ts @@ -254,11 +254,14 @@ export const RampBlock: BlockConfig = { { label: 'Init', id: 'INIT' }, { label: 'Manually Reimbursed', id: 'MANUALLY_REIMBURSED' }, { label: 'Missing Ach', id: 'MISSING_ACH' }, + { label: 'Payroll Failed', id: 'PAYROLL_FAILED' }, + { label: 'Payroll Submitted', id: 'PAYROLL_SUBMITTED' }, { label: 'Pending', id: 'PENDING' }, { label: 'Processing', id: 'PROCESSING' }, { label: 'Push Payment Failed', id: 'PUSH_PAYMENT_FAILED' }, { label: 'Push Payment Initiated', id: 'PUSH_PAYMENT_INITIATED' }, { label: 'Reimbursed', id: 'REIMBURSED' }, + { label: 'Reimbursed Via Payroll', id: 'REIMBURSED_VIA_PAYROLL' }, { label: 'Reimbursed Via Push', id: 'REIMBURSED_VIA_PUSH' }, { label: 'Rejected', id: 'REJECTED' }, ], diff --git a/apps/sim/blocks/blocks/shopify.test.ts b/apps/sim/blocks/blocks/shopify.test.ts index e3b59fb4cb5..98bc6de02c5 100644 --- a/apps/sim/blocks/blocks/shopify.test.ts +++ b/apps/sim/blocks/blocks/shopify.test.ts @@ -27,3 +27,66 @@ describe('Shopify operation changes', () => { expect(mapParams({ operation, [idField]: id })[field]).toBeUndefined() }) }) + +describe('Shopify tool calls (operation only in context)', () => { + it.each([ + 'shopify_list_products', + 'shopify_list_orders', + 'shopify_list_customers', + 'shopify_list_collections', + 'shopify_list_locations', + ])('keeps the model query and sortKey for %s', (operation) => { + const params = mapParams({ query: 'title:Summer', sortKey: 'ID' }, { operation }) + expect(params.query).toBe('title:Summer') + expect(params.sortKey).toBe('ID') + }) + + it('keeps the model status filter when listing orders', () => { + const params = mapParams({ status: 'open' }, { operation: 'shopify_list_orders' }) + expect(params.status).toBe('open') + }) + + it('cancels an order with the model reason and notify flag', () => { + const params = mapParams( + { orderId: 'gid://shopify/Order/1', reason: 'CUSTOMER', notifyCustomer: true }, + { operation: 'shopify_cancel_order' } + ) + expect(params.reason).toBe('CUSTOMER') + expect(params.notifyCustomer).toBe(true) + }) + + it('keeps model note, email, phone and array tags when updating an order', () => { + const params = mapParams( + { + orderId: 'gid://shopify/Order/1', + note: 'Gift', + email: 'a@example.com', + phone: '+15550100', + tags: ['vip', ' rush '], + }, + { operation: 'shopify_update_order' } + ) + expect(params).toMatchObject({ + note: 'Gift', + email: 'a@example.com', + phone: '+15550100', + tags: ['vip', 'rush'], + }) + }) + + it('keeps model email, note and array tags when creating a customer', () => { + const params = mapParams( + { email: 'a@example.com', note: 'VIP', tags: ['vip'] }, + { operation: 'shopify_create_customer' } + ) + expect(params).toMatchObject({ email: 'a@example.com', note: 'VIP', tags: ['vip'] }) + }) + + it('accepts model array tags when creating a product', () => { + const params = mapParams( + { title: 'Hat', tags: ['summer', 'sale'] }, + { operation: 'shopify_create_product' } + ) + expect(params.tags).toEqual(['summer', 'sale']) + }) +}) diff --git a/apps/sim/blocks/blocks/shopify.ts b/apps/sim/blocks/blocks/shopify.ts index 2f08ab273c8..7752024358e 100644 --- a/apps/sim/blocks/blocks/shopify.ts +++ b/apps/sim/blocks/blocks/shopify.ts @@ -2,7 +2,12 @@ import { ShopifyIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { parseOptionalBooleanInput, parseOptionalNumberInput } from '@/blocks/utils' +import { + mapperOperation, + parseOptionalBooleanInput, + parseOptionalNumberInput, + toolCallArg, +} from '@/blocks/utils' const LIST_OPERATIONS = [ 'shopify_list_products', @@ -17,6 +22,20 @@ const LIST_OPERATIONS = [ 'shopify_get_inventory_level', ] as const +/** + * Parses a tag list from a comma-separated block field or an array a model sent on a tool call. + */ +function parseTagList(value: unknown): string[] | undefined { + if (Array.isArray(value)) { + return value.map((tag) => String(tag).trim()).filter(Boolean) + } + if (typeof value !== 'string') return undefined + return value + .split(',') + .map((tag) => tag.trim()) + .filter(Boolean) +} + export const ShopifyBlock: BlockConfig = { type: 'shopify', name: 'Shopify', @@ -224,6 +243,7 @@ export const ShopifyBlock: BlockConfig = { mode: 'advanced', options: [ { label: 'Shopify default', id: '' }, + { label: 'Created At', id: 'CREATED_AT' }, { label: 'Id', id: 'ID' }, { label: 'Name', id: 'NAME' }, { label: 'Relevance', id: 'RELEVANCE' }, @@ -1513,8 +1533,8 @@ export const ShopifyBlock: BlockConfig = { tool: (params) => { return params.operation || 'shopify_list_products' }, - params: (params) => { - const operation = params.operation || 'shopify_list_products' + params: (params, context) => { + const operation = mapperOperation(params, context) || 'shopify_list_products' const first = LIST_OPERATIONS.some((listOperation) => listOperation === operation) ? parseOptionalNumberInput(params.first, 'first') : undefined @@ -1579,10 +1599,7 @@ export const ShopifyBlock: BlockConfig = { descriptionHtml: params.descriptionHtml?.trim(), productType: params.productType?.trim(), vendor: params.vendor?.trim(), - tags: params.tags - ?.split(',') - .map((t: string) => t.trim()) - .filter(Boolean), + tags: parseTagList(params.tags), status: params.status || undefined, } @@ -1600,9 +1617,9 @@ export const ShopifyBlock: BlockConfig = { case 'shopify_list_products': return { ...baseParams, - sortKey: params.productsSortKey || undefined, + sortKey: params.productsSortKey || toolCallArg(context, params.sortKey), first, - query: params.productQuery?.trim(), + query: params.productQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_update_product': @@ -1616,10 +1633,7 @@ export const ShopifyBlock: BlockConfig = { descriptionHtml: params.descriptionHtml?.trim(), productType: params.productType?.trim(), vendor: params.vendor?.trim(), - tags: params.tags - ?.split(',') - .map((t: string) => t.trim()) - .filter(Boolean), + tags: parseTagList(params.tags), status: params.status || undefined, } @@ -1645,10 +1659,13 @@ export const ShopifyBlock: BlockConfig = { case 'shopify_list_orders': return { ...baseParams, - sortKey: params.ordersSortKey || undefined, + sortKey: params.ordersSortKey || toolCallArg(context, params.sortKey), first, - status: params.orderStatus !== 'any' ? params.orderStatus : undefined, - query: params.orderQuery?.trim(), + status: + params.orderStatus && params.orderStatus !== 'any' + ? params.orderStatus + : toolCallArg(context, params.status), + query: params.orderQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_update_order': @@ -1658,48 +1675,50 @@ export const ShopifyBlock: BlockConfig = { return { ...baseParams, orderId: params.orderId.trim(), - note: params.orderNote?.trim(), - email: params.orderEmail?.trim(), - phone: params.orderPhone?.trim(), - tags: params.orderTags - ?.split(',') - .map((t: string) => t.trim()) - .filter(Boolean), + note: params.orderNote?.trim() ?? toolCallArg(context, params.note), + email: params.orderEmail?.trim() ?? toolCallArg(context, params.email), + phone: params.orderPhone?.trim() ?? toolCallArg(context, params.phone), + tags: + parseTagList(params.orderTags) ?? toolCallArg(context, parseTagList(params.tags)), } case 'shopify_cancel_order': if (!params.orderId?.trim()) { throw new Error('Order ID is required.') } - if (!params.cancelReason) { - throw new Error('Cancel reason is required.') - } - return { - ...baseParams, - orderId: params.orderId.trim(), - reason: params.cancelReason, - restock: parseOptionalBooleanInput(params.restock) ?? false, - notifyCustomer: parseOptionalBooleanInput(params.cancelNotifyCustomer), - refundMethod: - params.refundMethod || - (parseOptionalBooleanInput(params.refundOriginalPayment) === true - ? { originalPaymentMethodsRefund: true } - : undefined), - staffNote: params.staffNote?.trim(), + { + const reason = params.cancelReason || toolCallArg(context, params.reason) + if (!reason) { + throw new Error('Cancel reason is required.') + } + return { + ...baseParams, + orderId: params.orderId.trim(), + reason, + restock: parseOptionalBooleanInput(params.restock) ?? false, + notifyCustomer: + parseOptionalBooleanInput(params.cancelNotifyCustomer) ?? + toolCallArg(context, parseOptionalBooleanInput(params.notifyCustomer)), + refundMethod: + params.refundMethod || + (parseOptionalBooleanInput(params.refundOriginalPayment) === true + ? { originalPaymentMethodsRefund: true } + : undefined), + staffNote: params.staffNote?.trim(), + } } case 'shopify_create_customer': return { ...baseParams, - email: params.customerEmail?.trim(), + email: params.customerEmail?.trim() ?? toolCallArg(context, params.email), firstName: params.firstName?.trim(), lastName: params.lastName?.trim(), phone: params.phone?.trim(), - note: params.customerNote?.trim(), - tags: params.customerTags - ?.split(',') - .map((t: string) => t.trim()) - .filter(Boolean), + note: params.customerNote?.trim() ?? toolCallArg(context, params.note), + tags: + parseTagList(params.customerTags) ?? + toolCallArg(context, parseTagList(params.tags)), } case 'shopify_get_customer': @@ -1714,9 +1733,9 @@ export const ShopifyBlock: BlockConfig = { case 'shopify_list_customers': return { ...baseParams, - sortKey: params.customersSortKey || undefined, + sortKey: params.customersSortKey || toolCallArg(context, params.sortKey), first, - query: params.customerQuery?.trim(), + query: params.customerQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_update_customer': @@ -1726,15 +1745,14 @@ export const ShopifyBlock: BlockConfig = { return { ...baseParams, customerId: params.customerId.trim(), - email: params.customerEmail?.trim(), + email: params.customerEmail?.trim() ?? toolCallArg(context, params.email), firstName: params.firstName?.trim(), lastName: params.lastName?.trim(), phone: params.phone?.trim(), - note: params.customerNote?.trim(), - tags: params.customerTags - ?.split(',') - .map((t: string) => t.trim()) - .filter(Boolean), + note: params.customerNote?.trim() ?? toolCallArg(context, params.note), + tags: + parseTagList(params.customerTags) ?? + toolCallArg(context, parseTagList(params.tags)), } case 'shopify_delete_customer': @@ -1750,7 +1768,7 @@ export const ShopifyBlock: BlockConfig = { return { ...baseParams, first, - query: params.inventoryQuery?.trim(), + query: params.inventoryQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_get_inventory_level': @@ -1787,11 +1805,11 @@ export const ShopifyBlock: BlockConfig = { case 'shopify_list_locations': return { ...baseParams, - sortKey: params.locationsSortKey || undefined, + sortKey: params.locationsSortKey || toolCallArg(context, params.sortKey), first, includeInactive: parseOptionalBooleanInput(params.includeInactive), includeLegacy: parseOptionalBooleanInput(params.includeLegacy), - query: params.locationQuery?.trim(), + query: params.locationQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_create_fulfillment': @@ -1810,9 +1828,9 @@ export const ShopifyBlock: BlockConfig = { case 'shopify_list_collections': return { ...baseParams, - sortKey: params.collectionsSortKey || undefined, + sortKey: params.collectionsSortKey || toolCallArg(context, params.sortKey), first, - query: params.collectionQuery?.trim(), + query: params.collectionQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_get_collection': @@ -1841,7 +1859,9 @@ export const ShopifyBlock: BlockConfig = { return { ...baseParams, fulfillmentId: params.fulfillmentId?.trim(), - notifyCustomer: parseOptionalBooleanInput(params.trackingNotifyCustomer), + notifyCustomer: + parseOptionalBooleanInput(params.trackingNotifyCustomer) ?? + toolCallArg(context, parseOptionalBooleanInput(params.notifyCustomer)), } default: return baseParams diff --git a/apps/sim/blocks/blocks/typeform.test.ts b/apps/sim/blocks/blocks/typeform.test.ts new file mode 100644 index 00000000000..a3606d64d5c --- /dev/null +++ b/apps/sim/blocks/blocks/typeform.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import { TypeformV2Block } from '@/blocks/blocks/typeform' +import type { BlockToolParamsContext } from '@/blocks/types' +import { createFormTool } from '@/tools/typeform/create_form' +import { updateFormTool } from '@/tools/typeform/update_form' + +/** + * Assertions run against `{ ...inputs, ...mapper(inputs, context) }`, the shape both the canvas + * handler and the tool-call transform forward: a key the mapper leaves out keeps its raw value. + */ +describe('TypeformV2Block params mapper', () => { + const mapper = TypeformV2Block.tools.config?.params + if (!mapper) throw new Error('TypeformV2Block is missing its params mapper') + + const resolve = (inputs: Record, context?: BlockToolParamsContext) => ({ + ...inputs, + ...mapper(inputs, context), + }) + + const patchBody = (params: Record) => { + const body = updateFormTool.request.body + if (!body) throw new Error('Expected a body builder') + return body(params as Parameters[0]) + } + + const createBody = (params: Record) => { + const body = createFormTool.request.body + if (!body) throw new Error('Expected a body builder') + return body(params as Parameters[0]) + } + + it('sends patch operations a model passed as an array on a tool call', () => { + const operations = [{ op: 'replace', path: '/title', value: 'Renamed' }] + const params = resolve( + { apiKey: 'k', formId: 'abc123', operations }, + { operation: 'typeform_update_form' } + ) + + expect(patchBody(params)).toEqual(operations) + }) + + it('sends fields and settings a model passed as structured values on a tool call', () => { + const fields = [{ type: 'short_text', title: 'Name?' }] + const settings = { is_public: false } + const params = resolve( + { apiKey: 'k', title: 'Survey', fields, settings }, + { operation: 'typeform_create_form' } + ) + + expect(createBody(params)).toMatchObject({ title: 'Survey', fields, settings }) + }) + + it('still parses JSON text typed on the canvas', () => { + const params = resolve({ + operation: 'typeform_update_form', + apiKey: 'k', + formId: 'abc123', + operations: '[{"op":"replace","path":"/settings/is_public","value":false}]', + }) + + expect(patchBody(params)).toEqual([ + { op: 'replace', path: '/settings/is_public', value: false }, + ]) + }) +}) diff --git a/apps/sim/blocks/blocks/typeform.ts b/apps/sim/blocks/blocks/typeform.ts index e112989f102..7a5c20098a5 100644 --- a/apps/sim/blocks/blocks/typeform.ts +++ b/apps/sim/blocks/blocks/typeform.ts @@ -1,3 +1,4 @@ +import { getErrorMessage } from '@sim/utils/errors' import { TypeformIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' @@ -125,7 +126,7 @@ export const TypeformBlock: BlockConfig = { id: 'since', title: 'Since', type: 'short-input', - placeholder: 'Retrieve responses after this date (ISO format)', + placeholder: 'Retrieve responses on or after this date (ISO format)', condition: { field: 'operation', value: 'typeform_responses' }, wandConfig: { enabled: true, @@ -147,7 +148,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, id: 'until', title: 'Until', type: 'short-input', - placeholder: 'Retrieve responses before this date (ISO format)', + placeholder: 'Retrieve responses on or before this date (ISO format)', condition: { field: 'operation', value: 'typeform_responses' }, wandConfig: { enabled: true, @@ -176,6 +177,14 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, ], condition: { field: 'operation', value: 'typeform_responses' }, }, + { + id: 'responseType', + title: 'Response Types', + type: 'short-input', + placeholder: 'e.g., partial,completed (overrides Completed)', + mode: 'advanced', + condition: { field: 'operation', value: 'typeform_responses' }, + }, // File operation fields { id: 'responseId', @@ -183,6 +192,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, type: 'short-input', placeholder: 'Enter response ID (token)', condition: { field: 'operation', value: 'typeform_files' }, + required: true, }, { id: 'fieldId', @@ -190,6 +200,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, type: 'short-input', placeholder: 'Enter file upload field ID', condition: { field: 'operation', value: 'typeform_files' }, + required: true, }, { id: 'filename', @@ -197,6 +208,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, type: 'short-input', placeholder: 'Enter exact filename of the file', condition: { field: 'operation', value: 'typeform_files' }, + required: true, }, { id: 'inline', @@ -249,6 +261,11 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, options: [ { label: 'Form', id: 'form' }, { label: 'Quiz', id: 'quiz' }, + { label: 'Classification', id: 'classification' }, + { label: 'Score', id: 'score' }, + { label: 'Branching', id: 'branching' }, + { label: 'Classification Branching', id: 'classification_branching' }, + { label: 'Score Branching', id: 'score_branching' }, ], condition: { field: 'operation', value: 'typeform_create_form' }, }, @@ -300,54 +317,39 @@ Current operations: {context} ### JSON PATCH OPERATIONS Each operation is an object with: -- "op": The operation type ("add", "remove", "replace", "move", "copy", "test") -- "path": JSON pointer to the target location (e.g., "/title", "/fields/0", "/settings/language") -- "value": The new value (required for "add", "replace", "copy", "test") -- "from": Source path (required for "move" and "copy") +- "op": The operation type (usually "replace") +- "path": One of the paths Typeform accepts (listed below) +- "value": The new value -### COMMON TYPEFORM PATHS -- /title - Form title -- /settings/language - Form language (e.g., "en", "es", "fr") -- /settings/is_public - Whether form is public (true/false) -- /settings/show_progress_bar - Show progress bar (true/false) -- /fields - Array of form fields -- /fields/- - Add to end of fields array -- /fields/0 - First field -- /welcome_screens - Array of welcome screens -- /thankyou_screens - Array of thank you screens -- /theme/href - Theme URL reference +### PATHS TYPEFORM ACCEPTS (no others are allowed) +- /title - Form title (string) +- /settings/is_public - Whether the form is public (true/false) +- /settings/meta - Sharing metadata object: { "title", "description", "allow_indexing", "image": { "href" } } +- /settings/google_analytics - Google Analytics tracking ID +- /settings/google_tag_manager - Google Tag Manager ID +- /settings/facebook_pixel - Facebook Pixel ID +- /settings/enrichment_in_renderer - Enrichment setting +- /settings/email_consent_notifications_config - Email consent notification settings +- /theme - Theme reference: { "href": "https://api.typeform.com/themes/{theme_id}" } +- /workspace - Workspace reference: { "href": "https://api.typeform.com/workspaces/{workspace_id}" } -### FIELD OBJECT STRUCTURE -{ - "type": "short_text" | "long_text" | "email" | "number" | "multiple_choice" | "yes_no" | "rating" | "date" | "dropdown" | "file_upload", - "title": "Question text", - "ref": "unique_reference_id", - "properties": { ... }, - "validations": { "required": true/false } -} +Fields, welcome screens, thank-you screens, and language cannot be changed with these operations. If the user asks for one of those, return only the operations for the paths above. ### EXAMPLES **Change form title:** [{"op": "replace", "path": "/title", "value": "My Updated Form"}] -**Add a new text field:** -[{"op": "add", "path": "/fields/-", "value": {"type": "short_text", "title": "What is your name?", "ref": "name_field", "validations": {"required": true}}}] - -**Add multiple choice field:** -[{"op": "add", "path": "/fields/-", "value": {"type": "multiple_choice", "title": "Select your favorite color", "ref": "color_field", "properties": {"choices": [{"label": "Red"}, {"label": "Blue"}, {"label": "Green"}]}}}] +**Make the form private:** +[{"op": "replace", "path": "/settings/is_public", "value": false}] -**Remove first field:** -[{"op": "remove", "path": "/fields/0"}] +**Update sharing metadata:** +[{"op": "replace", "path": "/settings/meta", "value": {"title": "Customer Feedback", "description": "Tell us how we did", "allow_indexing": false}}] -**Update form settings:** -[{"op": "replace", "path": "/settings/language", "value": "es"}, {"op": "replace", "path": "/settings/is_public", "value": false}] - -**Multiple operations:** +**Move the form to another workspace and apply a theme:** [ - {"op": "replace", "path": "/title", "value": "Customer Feedback Form"}, - {"op": "add", "path": "/fields/-", "value": {"type": "rating", "title": "Rate your experience", "ref": "rating_field", "properties": {"steps": 5}}}, - {"op": "replace", "path": "/settings/show_progress_bar", "value": true} + {"op": "replace", "path": "/workspace", "value": {"href": "https://api.typeform.com/workspaces/abc123"}}, + {"op": "replace", "path": "/theme", "value": {"href": "https://api.typeform.com/themes/xyz789"}} ] Do not include any explanations, markdown formatting, or other text outside the JSON array.`, @@ -402,18 +404,19 @@ Do not include any explanations, markdown formatting, or other text outside the ...rest } = params - let parsedFields: any | undefined - let parsedSettings: any | undefined - let parsedOperations: any | undefined - - try { - if (fields) parsedFields = JSON.parse(fields) - if (settings) parsedSettings = JSON.parse(settings) - if (operations) parsedOperations = JSON.parse(operations) - } catch (error: any) { - throw new Error(`Invalid JSON input: ${error.message}`) + const parseJsonInput = (value: unknown): unknown => { + if (typeof value !== 'string') return value + try { + return JSON.parse(value) + } catch (error) { + throw new Error(`Invalid JSON input: ${getErrorMessage(error)}`) + } } + const parsedFields = fields ? parseJsonInput(fields) : undefined + const parsedSettings = settings ? parseJsonInput(settings) : undefined + const parsedOperations = operations ? parseJsonInput(operations) : undefined + const pageSize = listPageSize !== undefined ? listPageSize : params.pageSize const workspaceId = workspaceIdCreate || params.workspaceId @@ -422,9 +425,9 @@ Do not include any explanations, markdown formatting, or other text outside the ...rest, ...(pageSize && { pageSize }), ...(workspaceId && { workspaceId }), - ...(parsedFields && { fields: parsedFields }), - ...(parsedSettings && { settings: parsedSettings }), - ...(parsedOperations && { operations: parsedOperations }), + ...(parsedFields ? { fields: parsedFields } : {}), + ...(parsedSettings ? { settings: parsedSettings } : {}), + ...(parsedOperations ? { operations: parsedOperations } : {}), } }, }, @@ -440,6 +443,7 @@ Do not include any explanations, markdown formatting, or other text outside the since: { type: 'string', description: 'Start date filter' }, until: { type: 'string', description: 'End date filter' }, completed: { type: 'string', description: 'Completion status filter' }, + responseType: { type: 'string', description: 'Comma-separated response types to return' }, // File operation params responseId: { type: 'string', description: 'Response identifier' }, fieldId: { type: 'string', description: 'Field identifier' }, @@ -452,7 +456,7 @@ Do not include any explanations, markdown formatting, or other text outside the listPageSize: { type: 'number', description: 'Forms per page' }, // Create form operation params title: { type: 'string', description: 'Form title' }, - type: { type: 'string', description: 'Form type (form or quiz)' }, + type: { type: 'string', description: 'Form type (e.g., quiz, score, branching)' }, workspaceIdCreate: { type: 'string', description: 'Workspace ID for creation' }, fields: { type: 'json', description: 'Form fields array' }, settings: { type: 'json', description: 'Form settings object' }, diff --git a/apps/sim/blocks/blocks/webflow.test.ts b/apps/sim/blocks/blocks/webflow.test.ts new file mode 100644 index 00000000000..6a80557ea11 --- /dev/null +++ b/apps/sim/blocks/blocks/webflow.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import { WebflowBlock } from '@/blocks/blocks/webflow' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** The block's `tools.config.params` mapper; `context` is set on a tool call, absent on the canvas. */ +const buildParams = ( + inputs: Record, + context?: BlockToolParamsContext +): Record => WebflowBlock.tools.config?.params?.(inputs, context) ?? {} + +/** + * On an agent call the stored row and model args merge under the tool's param names, the operation + * reaches the mapper only on `context`, and the result is spread over the merged params. + */ +describe('WebflowBlock agent tool calls', () => { + const agentCall = ( + operation: string, + args: Record + ): Record => ({ + ...args, + ...buildParams(args, { operation }), + }) + + it('trims a model itemId with surrounding whitespace on update', () => { + const mapped = agentCall('update', { + oauthCredential: 'cred-1', + collectionId: '580e63fc8c9a982ac9b8b745', + itemId: ' 580e64008c9a982ac9b8b754 ', + fieldData: { name: 'Renamed' }, + }) + expect(mapped).toMatchObject({ + credential: 'cred-1', + itemId: '580e64008c9a982ac9b8b754', + fieldData: { name: 'Renamed' }, + }) + }) + + it('parses a JSON string fieldData on create', () => { + const mapped = agentCall('create', { + oauthCredential: 'cred-1', + collectionId: '580e63fc8c9a982ac9b8b745', + fieldData: '{"name":"Post","slug":"post"}', + }) + expect(mapped.fieldData).toEqual({ name: 'Post', slug: 'post' }) + }) +}) diff --git a/apps/sim/blocks/blocks/webflow.ts b/apps/sim/blocks/blocks/webflow.ts index 0c41458ee63..b74f04e014b 100644 --- a/apps/sim/blocks/blocks/webflow.ts +++ b/apps/sim/blocks/blocks/webflow.ts @@ -1,7 +1,9 @@ +import { getErrorMessage } from '@sim/utils/errors' import { WebflowIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** CMS collection, whichever mode the card is in. */ @@ -214,7 +216,8 @@ export const WebflowBlock: BlockConfig = { throw new Error(`Invalid Webflow operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { oauthCredential, fieldData, @@ -223,14 +226,16 @@ export const WebflowBlock: BlockConfig = { itemId, // Canonical param from itemSelector (basic) or manualItemId (advanced) ...rest } = params - let parsedFieldData: any | undefined + let parsedFieldData: unknown try { - if (fieldData && (params.operation === 'create' || params.operation === 'update')) { - parsedFieldData = JSON.parse(fieldData) + if (fieldData && (operation === 'create' || operation === 'update')) { + parsedFieldData = typeof fieldData === 'string' ? JSON.parse(fieldData) : fieldData } - } catch (error: any) { - throw new Error(`Invalid JSON input for ${params.operation} operation: ${error.message}`) + } catch (error) { + throw new Error( + `Invalid JSON input for ${operation} operation: ${getErrorMessage(error)}` + ) } const effectiveSiteId = siteId ? String(siteId).trim() : '' @@ -244,7 +249,7 @@ export const WebflowBlock: BlockConfig = { ...rest, } - switch (params.operation) { + switch (operation) { case 'create': case 'update': return { @@ -317,7 +322,7 @@ export const WebflowBlockMeta = { icon: WebflowIcon, title: 'Webflow CMS publisher', prompt: - 'Create a workflow that reads a draft articles table, generates an SEO-optimized post, publishes it as a Webflow CMS item, and writes the live URL back to the row.', + 'Create a workflow that reads a draft articles table, generates an SEO-optimized post, creates it as a Webflow CMS item, and writes the new item ID and slug back to the row.', modules: ['tables', 'agent', 'workflows'], category: 'marketing', tags: ['marketing', 'content'], @@ -378,14 +383,14 @@ export const WebflowBlockMeta = { description: 'Create a new item in a Webflow CMS collection from supplied or generated field data.', content: - '# Publish a Webflow CMS Item\n\nTurn structured content into a live Webflow CMS collection item.\n\n## Steps\n1. Identify the target site and collection. If unknown, list collections to confirm the collection ID and its field schema.\n2. Map the incoming content to the collection fields, including required fields like name and slug. Generate a URL-safe slug if one is not provided.\n3. Call the create-item operation with the assembled fieldData JSON.\n4. Confirm the new item ID and slug returned by the API.\n\n## Output\nReport the created item ID, slug, and the live or staged URL. If a required field was missing, name it explicitly rather than guessing a value.', + '# Publish a Webflow CMS Item\n\nTurn structured content into a new Webflow CMS collection item. Webflow creates it as a Draft.\n\n## Steps\n1. Identify the target site and collection ID. If unknown, ask for them, and list a few existing items in the collection to learn its field names.\n2. Map the incoming content to the collection fields, including required fields like name and slug. Generate a URL-safe slug if one is not provided.\n3. Call the create-item operation with the assembled fieldData JSON.\n4. Confirm the new item ID and slug returned by the API.\n\n## Output\nReport the created item ID and slug, and note that the item has Draft status: it will not go live on the next site publish until someone marks it as not a draft in Webflow. If a required field was missing, name it explicitly rather than guessing a value.', }, { name: 'update-cms-item', description: 'Find a Webflow CMS item and update specific fields without disturbing the rest.', content: - '# Update a Webflow CMS Item\n\nApply targeted edits to an existing collection item.\n\n## Steps\n1. Resolve the item by ID, or list items in the collection and match on slug or name.\n2. Get the current item so existing field values are known.\n3. Build fieldData containing only the fields that change, merged onto the current values so untouched fields are preserved.\n4. Call the update-item operation and confirm the change took effect.\n\n## Output\nList exactly which fields changed and their new values. Note the item ID and whether the change is live or staged.', + '# Update a Webflow CMS Item\n\nApply targeted edits to an existing collection item.\n\n## Steps\n1. Resolve the item by ID, or list items in the collection and match on slug or name.\n2. Get the current item so existing field values are known.\n3. Build fieldData containing only the fields that change, merged onto the current values so untouched fields are preserved.\n4. Call the update-item operation and confirm the change took effect.\n\n## Output\nList exactly which fields changed and their new values. Note the item ID. The change is not live until the site is published, and a draft item stays unpublished even then.', }, { name: 'audit-collection-content', diff --git a/apps/sim/blocks/blocks/wordpress.test.ts b/apps/sim/blocks/blocks/wordpress.test.ts new file mode 100644 index 00000000000..114dc04833b --- /dev/null +++ b/apps/sim/blocks/blocks/wordpress.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import { WordPressBlock } from '@/blocks/blocks/wordpress' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = WordPressBlock.tools.config?.params + if (!mapper) throw new Error('WordPress block has no params mapper') + return mapper(params, context) +} + +/** The tool-call path: merged args, then the mapper result spread over them. */ +function toolCallParams(modelArgs: Record, operation: string) { + return { ...modelArgs, ...mapParams(modelArgs, { operation }) } +} + +describe('WordPress tool calls', () => { + it.each([ + [ + 'wordpress_create_comment', + { siteId: 's', postId: '42', content: 'Thanks!', parent: 17, authorName: 'Ann' }, + { postId: 42, content: 'Thanks!', parent: 17, authorName: 'Ann' }, + ], + [ + 'wordpress_create_category', + { siteId: 's', name: 'News', description: 'd', slug: 'news', parent: '3' }, + { name: 'News', description: 'd', slug: 'news', parent: 3 }, + ], + [ + 'wordpress_update_tag', + { siteId: 's', tagId: 9, name: 'Renamed', slug: 'renamed' }, + { tagId: 9, name: 'Renamed', slug: 'renamed' }, + ], + [ + 'wordpress_update_comment', + { siteId: 's', commentId: 5, content: 'edited', status: 'hold' }, + { commentId: 5, content: 'edited', status: 'hold' }, + ], + [ + 'wordpress_list_posts', + { siteId: 's', status: 'draft', author: '7' }, + { status: 'draft', author: 7 }, + ], + ['wordpress_search_content', { siteId: 's', query: 'q', subtype: 'page' }, { subtype: 'page' }], + ])( + '%s keeps the model args the block renames from its own fields', + (operation, args, expected) => { + expect(toolCallParams(args, operation)).toMatchObject(expected) + } + ) + + it('unwraps a stored single-file array for upload_media', () => { + const file = { name: 'a.png', key: 'k', url: 'u', size: 1, type: 'image/png' } + expect(toolCallParams({ siteId: 's', file: [file] }, 'wordpress_upload_media').file).toEqual( + file + ) + }) +}) + +describe('WordPress list comments order', () => { + it('drops an Order By the comments endpoint rejects and keeps a valid one', () => { + const base = { operation: 'wordpress_list_comments', siteId: 's' } + expect(mapParams({ ...base, orderBy: 'title' }).orderBy).toBeUndefined() + expect(mapParams({ ...base, orderBy: 'id' }).orderBy).toBe('id') + }) +}) diff --git a/apps/sim/blocks/blocks/wordpress.ts b/apps/sim/blocks/blocks/wordpress.ts index 294e323270a..a35ad9a0428 100644 --- a/apps/sim/blocks/blocks/wordpress.ts +++ b/apps/sim/blocks/blocks/wordpress.ts @@ -2,11 +2,37 @@ import { WordpressIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' /** The media file to upload, whichever mode the user is in. */ const MEDIA_FILE_FIELD = ['fileUpload', 'file'] as const +const CREATE_STATUS_OPERATIONS = new Set([ + 'wordpress_create_post', + 'wordpress_create_page', +]) +const UPDATE_STATUS_OPERATIONS = new Set([ + 'wordpress_update_post', + 'wordpress_update_page', +]) + +/** `orderby` values the comments endpoint accepts; the shared Order By field also offers post-only ones. */ +const COMMENT_ORDER_BY_FIELDS = new Set([ + 'date', + 'date_gmt', + 'id', + 'include', + 'post', + 'parent', + 'type', +]) + +/** A numeric field from a block input or model arg, `undefined` when blank. */ +function optionalNumber(value: unknown): number | undefined { + if (value === undefined || value === null || value === '') return undefined + return typeof value === 'number' ? value : Number(value) +} + export const WordPressBlock: BlockConfig = { type: 'wordpress', name: 'WordPress', @@ -264,13 +290,30 @@ export const WordPressBlock: BlockConfig = { id: 'status', title: 'Status', type: 'dropdown', - options: [ + dependsOn: ['operation'], + /** + * Canvas and builder create contexts default to Publish. Every other context leads with + * "No change" so the existing or model-supplied status is kept, including Agent tool rows, + * whose options see the host Agent block's values (no `operation`), so create rows there + * keep the model's status or WordPress's own `draft` default. + * Without block values (Copilot validation, catalogs) every option is listed, "No change" last. + */ + options: (params) => [ + ...(params && !CREATE_STATUS_OPERATIONS.has(params.values.operation) + ? [{ label: 'No change', id: '' }] + : []), { label: 'Publish', id: 'publish' }, { label: 'Draft', id: 'draft' }, { label: 'Pending', id: 'pending' }, { label: 'Private', id: 'private' }, + ...(params ? [] : [{ label: 'No change', id: '' }]), ], - value: () => 'publish', + value: (params) => + CREATE_STATUS_OPERATIONS.has(params?.operation) + ? 'publish' + : UPDATE_STATUS_OPERATIONS.has(params?.operation) + ? '' + : undefined, condition: { field: 'operation', value: [ @@ -316,6 +359,29 @@ export const WordPressBlock: BlockConfig = { }, }, + { + id: 'date', + title: 'Publish Date', + type: 'short-input', + placeholder: 'e.g., 2026-12-01T09:00:00 (site timezone)', + mode: 'advanced', + condition: { + field: 'operation', + value: [ + 'wordpress_create_post', + 'wordpress_update_post', + 'wordpress_create_page', + 'wordpress_update_page', + ], + }, + wandConfig: { + enabled: true, + prompt: + 'Generate an ISO 8601 date-time without a timezone offset (e.g., 2026-12-01T09:00:00), interpreted in the site timezone. Return ONLY the timestamp string.', + generationType: 'timestamp', + }, + }, + { id: 'categories', title: 'Categories', @@ -569,12 +635,13 @@ export const WordPressBlock: BlockConfig = { title: 'Comment Status', type: 'dropdown', options: [ + { label: 'No change', id: '' }, { label: 'Approved', id: 'approved' }, { label: 'Hold', id: 'hold' }, { label: 'Spam', id: 'spam' }, { label: 'Trash', id: 'trash' }, ], - value: () => 'approved', + value: () => '', mode: 'advanced', condition: { field: 'operation', value: 'wordpress_update_comment' }, }, @@ -898,13 +965,13 @@ export const WordPressBlock: BlockConfig = { ], config: { tool: (params) => params.operation || 'wordpress_create_post', - params: (params) => { - const baseParams: Record = { + params: (params, context) => { + const baseParams: Record = { credential: params.oauthCredential, siteId: params.siteId, } - switch (params.operation) { + switch (mapperOperation(params, context) || 'wordpress_create_post') { case 'wordpress_create_post': return { ...baseParams, @@ -915,15 +982,12 @@ export const WordPressBlock: BlockConfig = { slug: params.slug, categories: params.categories, tags: params.tags, - featuredMedia: - params.featuredMedia !== undefined && params.featuredMedia !== '' - ? Number(params.featuredMedia) - : undefined, + featuredMedia: optionalNumber(params.featuredMedia), } case 'wordpress_update_post': return { ...baseParams, - postId: Number(params.postId), + postId: optionalNumber(params.postId), title: params.title, content: params.content, status: params.status, @@ -931,37 +995,33 @@ export const WordPressBlock: BlockConfig = { slug: params.slug, categories: params.categories, tags: params.tags, - featuredMedia: - params.featuredMedia !== undefined && params.featuredMedia !== '' - ? Number(params.featuredMedia) - : undefined, + featuredMedia: optionalNumber(params.featuredMedia), } case 'wordpress_delete_post': return { ...baseParams, - postId: Number(params.postId), + postId: optionalNumber(params.postId), force: params.force, } case 'wordpress_get_post': return { ...baseParams, - postId: Number(params.postId), + postId: optionalNumber(params.postId), } case 'wordpress_list_posts': return { ...baseParams, perPage: params.perPage ? Number(params.perPage) : undefined, page: params.page ? Number(params.page) : undefined, - status: params.listStatus || undefined, + status: params.listStatus || toolCallArg(context, params.status), search: params.search, orderBy: params.orderBy, order: params.order, categories: params.categories, tags: params.tags, author: - params.listAuthor !== undefined && params.listAuthor !== '' - ? Number(params.listAuthor) - : undefined, + optionalNumber(params.listAuthor) ?? + toolCallArg(context, optionalNumber(params.author)), } case 'wordpress_create_page': return { @@ -971,81 +1031,59 @@ export const WordPressBlock: BlockConfig = { status: params.status, excerpt: params.excerpt, slug: params.slug, - parent: - params.parent !== undefined && params.parent !== '' - ? Number(params.parent) - : undefined, - menuOrder: - params.menuOrder !== undefined && params.menuOrder !== '' - ? Number(params.menuOrder) - : undefined, - featuredMedia: - params.featuredMedia !== undefined && params.featuredMedia !== '' - ? Number(params.featuredMedia) - : undefined, + parent: optionalNumber(params.parent), + menuOrder: optionalNumber(params.menuOrder), + featuredMedia: optionalNumber(params.featuredMedia), } case 'wordpress_update_page': return { ...baseParams, - pageId: Number(params.pageId), + pageId: optionalNumber(params.pageId), title: params.title, content: params.content, status: params.status, excerpt: params.excerpt, slug: params.slug, - parent: - params.parent !== undefined && params.parent !== '' - ? Number(params.parent) - : undefined, - menuOrder: - params.menuOrder !== undefined && params.menuOrder !== '' - ? Number(params.menuOrder) - : undefined, - featuredMedia: - params.featuredMedia !== undefined && params.featuredMedia !== '' - ? Number(params.featuredMedia) - : undefined, + parent: optionalNumber(params.parent), + menuOrder: optionalNumber(params.menuOrder), + featuredMedia: optionalNumber(params.featuredMedia), } case 'wordpress_delete_page': return { ...baseParams, - pageId: Number(params.pageId), + pageId: optionalNumber(params.pageId), force: params.force, } case 'wordpress_get_page': return { ...baseParams, - pageId: Number(params.pageId), + pageId: optionalNumber(params.pageId), } case 'wordpress_list_pages': return { ...baseParams, perPage: params.perPage ? Number(params.perPage) : undefined, page: params.page ? Number(params.page) : undefined, - status: params.listStatus || undefined, + status: params.listStatus || toolCallArg(context, params.status), search: params.search, orderBy: params.orderBy, order: params.order, - parent: - params.parent !== undefined && params.parent !== '' - ? Number(params.parent) - : undefined, + parent: optionalNumber(params.parent), } case 'wordpress_upload_media': - // file is the canonical param for both basic (fileUpload) and advanced modes return { ...baseParams, file: normalizeFileInput(params.file, { single: true }), filename: params.filename, - title: params.mediaTitle, + title: params.mediaTitle ?? toolCallArg(context, params.title), caption: params.caption, altText: params.altText, - description: params.mediaDescription || undefined, + description: params.mediaDescription || toolCallArg(context, params.description), } case 'wordpress_get_media': return { ...baseParams, - mediaId: Number(params.mediaId), + mediaId: optionalNumber(params.mediaId), } case 'wordpress_list_media': return { @@ -1060,54 +1098,56 @@ export const WordPressBlock: BlockConfig = { case 'wordpress_delete_media': return { ...baseParams, - mediaId: Number(params.mediaId), + mediaId: optionalNumber(params.mediaId), } case 'wordpress_create_comment': return { ...baseParams, - postId: Number(params.commentPostId), - content: params.commentContent, + postId: + optionalNumber(params.commentPostId) ?? + toolCallArg(context, optionalNumber(params.postId)), + content: params.commentContent ?? toolCallArg(context, params.content), parent: - params.commentParent !== undefined && params.commentParent !== '' - ? Number(params.commentParent) - : undefined, - authorName: params.commentAuthorName || undefined, - authorEmail: params.commentAuthorEmail || undefined, - authorUrl: params.commentAuthorUrl || undefined, + optionalNumber(params.commentParent) ?? + toolCallArg(context, optionalNumber(params.parent)), + authorName: params.commentAuthorName || toolCallArg(context, params.authorName), + authorEmail: params.commentAuthorEmail || toolCallArg(context, params.authorEmail), + authorUrl: params.commentAuthorUrl || toolCallArg(context, params.authorUrl), } case 'wordpress_list_comments': return { ...baseParams, perPage: params.perPage ? Number(params.perPage) : undefined, page: params.page ? Number(params.page) : undefined, - postId: params.commentPostId ? Number(params.commentPostId) : undefined, + postId: + optionalNumber(params.commentPostId) ?? + toolCallArg(context, optionalNumber(params.postId)), search: params.search, - orderBy: params.orderBy, + orderBy: COMMENT_ORDER_BY_FIELDS.has(params.orderBy) ? params.orderBy : undefined, order: params.order, } case 'wordpress_update_comment': return { ...baseParams, - commentId: Number(params.commentId), - content: params.commentContent, - status: params.commentStatus, + commentId: optionalNumber(params.commentId), + content: params.commentContent ?? toolCallArg(context, params.content), + status: params.commentStatus || toolCallArg(context, params.status), } case 'wordpress_delete_comment': return { ...baseParams, - commentId: Number(params.commentId), + commentId: optionalNumber(params.commentId), force: params.force, } case 'wordpress_create_category': return { ...baseParams, - name: params.categoryName, - description: params.categoryDescription, + name: params.categoryName ?? toolCallArg(context, params.name), + description: params.categoryDescription ?? toolCallArg(context, params.description), parent: - params.categoryParent !== undefined && params.categoryParent !== '' - ? Number(params.categoryParent) - : undefined, - slug: params.categorySlug, + optionalNumber(params.categoryParent) ?? + toolCallArg(context, optionalNumber(params.parent)), + slug: params.categorySlug ?? toolCallArg(context, params.slug), } case 'wordpress_list_categories': return { @@ -1120,31 +1160,30 @@ export const WordPressBlock: BlockConfig = { case 'wordpress_get_category': return { ...baseParams, - categoryId: Number(params.categoryId), + categoryId: optionalNumber(params.categoryId), } case 'wordpress_update_category': return { ...baseParams, - categoryId: Number(params.categoryId), - name: params.categoryName, - description: params.categoryDescription, + categoryId: optionalNumber(params.categoryId), + name: params.categoryName ?? toolCallArg(context, params.name), + description: params.categoryDescription ?? toolCallArg(context, params.description), parent: - params.categoryParent !== undefined && params.categoryParent !== '' - ? Number(params.categoryParent) - : undefined, - slug: params.categorySlug, + optionalNumber(params.categoryParent) ?? + toolCallArg(context, optionalNumber(params.parent)), + slug: params.categorySlug ?? toolCallArg(context, params.slug), } case 'wordpress_delete_category': return { ...baseParams, - categoryId: Number(params.categoryId), + categoryId: optionalNumber(params.categoryId), } case 'wordpress_create_tag': return { ...baseParams, - name: params.tagName, - description: params.tagDescription, - slug: params.tagSlug, + name: params.tagName ?? toolCallArg(context, params.name), + description: params.tagDescription ?? toolCallArg(context, params.description), + slug: params.tagSlug ?? toolCallArg(context, params.slug), } case 'wordpress_list_tags': return { @@ -1157,20 +1196,20 @@ export const WordPressBlock: BlockConfig = { case 'wordpress_get_tag': return { ...baseParams, - tagId: Number(params.tagId), + tagId: optionalNumber(params.tagId), } case 'wordpress_update_tag': return { ...baseParams, - tagId: Number(params.tagId), - name: params.tagName, - description: params.tagDescription, - slug: params.tagSlug, + tagId: optionalNumber(params.tagId), + name: params.tagName ?? toolCallArg(context, params.name), + description: params.tagDescription ?? toolCallArg(context, params.description), + slug: params.tagSlug ?? toolCallArg(context, params.slug), } case 'wordpress_delete_tag': return { ...baseParams, - tagId: Number(params.tagId), + tagId: optionalNumber(params.tagId), } case 'wordpress_get_current_user': return baseParams @@ -1186,7 +1225,7 @@ export const WordPressBlock: BlockConfig = { case 'wordpress_get_user': return { ...baseParams, - userId: Number(params.userId), + userId: optionalNumber(params.userId), } case 'wordpress_search_content': return { @@ -1194,7 +1233,7 @@ export const WordPressBlock: BlockConfig = { query: params.query, perPage: params.perPage ? Number(params.perPage) : undefined, page: params.page ? Number(params.page) : undefined, - subtype: params.searchType || undefined, + subtype: params.searchType || toolCallArg(context, params.subtype), } default: return baseParams @@ -1211,6 +1250,7 @@ export const WordPressBlock: BlockConfig = { content: { type: 'string', description: 'Post or page content' }, status: { type: 'string', description: 'Post or page status' }, excerpt: { type: 'string', description: 'Post or page excerpt' }, + date: { type: 'string', description: 'Publish date in the site timezone (ISO 8601)' }, slug: { type: 'string', description: 'URL slug' }, categories: { type: 'string', description: 'Category IDs (comma-separated)' }, tags: { type: 'string', description: 'Tag IDs (comma-separated)' }, diff --git a/apps/sim/blocks/blocks/zoom.test.ts b/apps/sim/blocks/blocks/zoom.test.ts new file mode 100644 index 00000000000..704f9646c85 --- /dev/null +++ b/apps/sim/blocks/blocks/zoom.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from 'vitest' +import { ZoomBlock } from '@/blocks/blocks/zoom' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = ZoomBlock.tools.config?.params + if (!mapper) throw new Error('Zoom block has no params mapper') + return mapper(params, context) +} + +/** What a tool call sends: the merged row params and model args with the mapper result over them. */ +function toolCall(args: Record, operation: string) { + return { ...args, ...mapParams(args, { operation }) } +} + +describe('Zoom tool calls', () => { + it('sends a stored From/To Date range on List Recordings', () => { + const sent = toolCall( + { userId: 'me', fromDate: '2026-10-01', toDate: '2026-10-31' }, + 'zoom_list_recordings' + ) + expect(sent.from).toBe('2026-10-01') + expect(sent.to).toBe('2026-10-31') + }) + + it("keeps the model's from/to when the row has no dates", () => { + const sent = toolCall( + { userId: 'me', from: '2026-10-01', to: '2026-10-15' }, + 'zoom_list_recordings' + ) + expect(sent.from).toBe('2026-10-01') + expect(sent.to).toBe('2026-10-15') + }) + + it('sends a stored Permanently Delete action on Delete Recording', () => { + const sent = toolCall({ meetingId: '123', deleteAction: 'delete' }, 'zoom_delete_recording') + expect(sent.action).toBe('delete') + }) + + it("keeps the model's topic and list type", () => { + expect(toolCall({ meetingId: '123', topic: 'Renamed' }, 'zoom_update_meeting').topic).toBe( + 'Renamed' + ) + expect(toolCall({ userId: 'me', type: 'upcoming' }, 'zoom_list_meetings').type).toBe('upcoming') + }) + + it('accepts a numeric meeting ID from the model', () => { + expect(toolCall({ meetingId: 85746065432 }, 'zoom_get_meeting').meetingId).toBe('85746065432') + }) + + it('coerces a stored meeting type and drops a stored "none" auto recording', () => { + const sent = toolCall( + { userId: 'me', topic: 'Standup', type: '8', autoRecording: 'none' }, + 'zoom_create_meeting' + ) + expect(sent.type).toBe(8) + expect(sent.autoRecording).toBeUndefined() + }) + + it('does not turn auto recording off from a legacy row that stored "none" on Update Meeting', () => { + const sent = toolCall({ meetingId: '123', autoRecording: 'none' }, 'zoom_update_meeting') + expect(sent.autoRecording).toBeUndefined() + }) + + it("lets the model set auto recording from a new agent tool row's seed", () => { + const field = ZoomBlock.subBlocks.find((subBlock) => subBlock.id === 'autoRecording') + const seeded = field?.value?.({}) + const stored = seeded === undefined ? {} : { autoRecording: seeded } + const sent = toolCall( + { meetingId: '123', autoRecording: 'cloud', ...stored }, + 'zoom_update_meeting' + ) + expect(sent.autoRecording).toBe('cloud') + }) +}) + +describe('Zoom canvas update', () => { + it('does not send a stale create topic', () => { + const inputs = { + operation: 'zoom_update_meeting', + meetingId: '123', + topic: 'Old create topic', + topicUpdate: '', + } + expect({ ...inputs, ...mapParams(inputs) }.topic).not.toBe('Old create topic') + }) + + it('leaves the meeting type unchanged for a new Update Meeting block', () => { + const typeField = ZoomBlock.subBlocks.find((subBlock) => subBlock.id === 'type') + const seeded = typeField?.value?.({ operation: 'zoom_update_meeting' }) + const inputs = { operation: 'zoom_update_meeting', meetingId: '123', type: seeded } + expect({ ...inputs, ...mapParams(inputs) }.type).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/zoom.ts b/apps/sim/blocks/blocks/zoom.ts index a89297ac4be..179112d103f 100644 --- a/apps/sim/blocks/blocks/zoom.ts +++ b/apps/sim/blocks/blocks/zoom.ts @@ -2,6 +2,7 @@ import { ZoomIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' /* @@ -11,6 +12,29 @@ import { getTrigger } from '@/triggers' */ const MEETING_FIELD = ['meetingSelector', 'meetingId'] as const +const MEETING_TYPE_OPTIONS = [ + { label: 'Scheduled', id: '2' }, + { label: 'Instant', id: '1' }, + { label: 'Recurring (no fixed time)', id: '3' }, + { label: 'Recurring (fixed time)', id: '8' }, +] + +const AUTO_RECORDING_OPTIONS = [ + { label: 'None', id: 'none' }, + { label: 'Local', id: 'local' }, + { label: 'Cloud', id: 'cloud' }, +] + +/** + * A text input as a trimmed string. A model may send a Zoom meeting ID as a number, which the + * spec types as an integer. + */ +function trimmedText(value: unknown): string { + if (typeof value === 'string') return value.trim() + if (typeof value === 'number' || typeof value === 'bigint') return String(value) + return '' +} + export const ZoomBlock: BlockConfig = { type: 'zoom', name: 'Zoom', @@ -203,13 +227,27 @@ export const ZoomBlock: BlockConfig = { id: 'type', title: 'Meeting Type', type: 'dropdown', - options: [ - { label: 'Scheduled', id: '2' }, - { label: 'Instant', id: '1' }, - { label: 'Recurring (no fixed time)', id: '3' }, - { label: 'Recurring (fixed time)', id: '8' }, + dependsOn: ['operation'], + /** + * Every context except a known Create Meeting leads with "No change", so an update does not + * turn a recurring meeting into a scheduled one; that includes agent tool rows, whose values + * carry no operation. Without block values (Copilot validation, catalogs) every option is + * listed, with "No change" last so the default stays Scheduled. Create sends Scheduled when + * left empty. + */ + options: (params) => [ + ...(params && params.values.operation !== 'zoom_create_meeting' + ? [{ label: 'No change', id: '' }] + : []), + ...MEETING_TYPE_OPTIONS, + ...(params ? [] : [{ label: 'No change', id: '' }]), ], - value: () => '2', + value: (params) => + params?.operation === 'zoom_create_meeting' + ? '2' + : params?.operation === 'zoom_update_meeting' + ? '' + : undefined, condition: { field: 'operation', value: ['zoom_create_meeting', 'zoom_update_meeting'], @@ -346,12 +384,24 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, id: 'autoRecording', title: 'Auto Recording', type: 'dropdown', - options: [ - { label: 'None', id: 'none' }, - { label: 'Local', id: 'local' }, - { label: 'Cloud', id: 'cloud' }, + dependsOn: ['operation'], + /** + * Same "No change" layout as Meeting Type, so a new Update Meeting block or agent tool row + * does not seed a value that would overwrite the meeting's recording setting. + */ + options: (params) => [ + ...(params && params.values.operation !== 'zoom_create_meeting' + ? [{ label: 'No change', id: '' }] + : []), + ...AUTO_RECORDING_OPTIONS, + ...(params ? [] : [{ label: 'No change', id: '' }]), ], - value: () => 'none', + value: (params) => + params?.operation === 'zoom_create_meeting' + ? 'none' + : params?.operation === 'zoom_update_meeting' + ? '' + : undefined, mode: 'advanced', condition: { field: 'operation', @@ -405,7 +455,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, id: 'fromDate', title: 'From Date', type: 'short-input', - placeholder: 'yyyy-mm-dd (within last 6 months)', + placeholder: 'yyyy-mm-dd (max 1-month range; defaults to today)', mode: 'advanced', condition: { field: 'operation', @@ -415,7 +465,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, enabled: true, prompt: `Generate a date string based on the user's description. The date should be in the format: yyyy-mm-dd (e.g., 2024-01-15). -This is for filtering Zoom recordings from this date (must be within last 6 months). +This is for filtering Zoom recordings from this date. Zoom allows at most a one-month range and defaults to today when no date is given. Examples: - "last month" -> Calculate 30 days ago in yyyy-mm-dd format - "beginning of this month" -> First day of current month in yyyy-mm-dd format @@ -497,6 +547,7 @@ Return ONLY the date string - no explanations, no quotes, no extra text.`, id: 'cancelMeetingReminder', title: 'Send Cancellation Email', type: 'switch', + description: 'Email the meeting registrants about the cancellation', mode: 'advanced', condition: { field: 'operation', @@ -527,23 +578,32 @@ Return ONLY the date string - no explanations, no quotes, no extra text.`, tool: (params) => { return params.operation || 'zoom_create_meeting' }, - params: (params) => { - const baseParams: Record = { + params: (params, context) => { + const baseParams: Record = { credential: params.oauthCredential, } + const userId = trimmedText(params.userId) + const meetingId = trimmedText(params.meetingId) + const requireUserId = () => { + if (!userId) throw new Error('User ID is required.') + return userId + } + const requireMeetingId = () => { + if (!meetingId) throw new Error('Meeting ID is required.') + return meetingId + } - switch (params.operation) { - case 'zoom_create_meeting': - if (!params.userId?.trim()) { - throw new Error('User ID is required.') - } - if (!params.topic?.trim()) { + switch (mapperOperation(params, context)) { + case 'zoom_create_meeting': { + const topic = trimmedText(params.topic) + requireUserId() + if (!topic) { throw new Error('Topic is required.') } return { ...baseParams, - userId: params.userId.trim(), - topic: params.topic.trim(), + userId, + topic, type: params.type ? Number(params.type) : 2, startTime: params.startTime, duration: params.duration ? Number(params.duration) : undefined, @@ -557,37 +617,29 @@ Return ONLY the date string - no explanations, no quotes, no extra text.`, waitingRoom: params.waitingRoom, autoRecording: params.autoRecording !== 'none' ? params.autoRecording : undefined, } + } case 'zoom_list_meetings': - if (!params.userId?.trim()) { - throw new Error('User ID is required.') - } return { ...baseParams, - userId: params.userId.trim(), - type: params.listType, + userId: requireUserId(), + type: params.listType || toolCallArg(context, params.type), pageSize: params.pageSize ? Number(params.pageSize) : undefined, nextPageToken: params.nextPageToken, } case 'zoom_get_meeting': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } return { ...baseParams, - meetingId: params.meetingId.trim(), + meetingId: requireMeetingId(), occurrenceId: params.occurrenceId, } case 'zoom_update_meeting': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } return { ...baseParams, - meetingId: params.meetingId.trim(), - topic: params.topicUpdate, + meetingId: requireMeetingId(), + topic: params.topicUpdate || toolCallArg(context, params.topic), type: params.type ? Number(params.type) : undefined, startTime: params.startTime, duration: params.duration ? Number(params.duration) : undefined, @@ -603,65 +655,42 @@ Return ONLY the date string - no explanations, no quotes, no extra text.`, } case 'zoom_delete_meeting': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } return { ...baseParams, - meetingId: params.meetingId.trim(), + meetingId: requireMeetingId(), occurrenceId: params.occurrenceId, cancelMeetingReminder: params.cancelMeetingReminder, } case 'zoom_get_meeting_invitation': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } + case 'zoom_get_meeting_recordings': return { ...baseParams, - meetingId: params.meetingId.trim(), + meetingId: requireMeetingId(), } case 'zoom_list_recordings': - if (!params.userId?.trim()) { - throw new Error('User ID is required.') - } return { ...baseParams, - userId: params.userId.trim(), - from: params.fromDate, - to: params.toDate, + userId: requireUserId(), + from: params.fromDate || toolCallArg(context, params.from), + to: params.toDate || toolCallArg(context, params.to), pageSize: params.pageSize ? Number(params.pageSize) : undefined, nextPageToken: params.nextPageToken, } - case 'zoom_get_meeting_recordings': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } - return { - ...baseParams, - meetingId: params.meetingId.trim(), - } - case 'zoom_delete_recording': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } return { ...baseParams, - meetingId: params.meetingId.trim(), + meetingId: requireMeetingId(), recordingId: params.recordingId, - action: params.deleteAction, + action: params.deleteAction || toolCallArg(context, params.action), } case 'zoom_list_past_participants': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } return { ...baseParams, - meetingId: params.meetingId.trim(), + meetingId: requireMeetingId(), pageSize: params.pageSize ? Number(params.pageSize) : undefined, nextPageToken: params.nextPageToken, } @@ -749,9 +778,9 @@ export const ZoomBlockMeta = { }, { icon: ZoomIcon, - title: 'Zoom webinar follow-up', + title: 'Zoom meeting follow-up', prompt: - 'Build a workflow that runs after a Zoom webinar, pulls the registrant and attendee lists, sends a follow-up email with the recording link, and writes attendance into HubSpot for marketing scoring.', + 'Build a workflow that runs after a Zoom meeting ends, lists the past participants, sends each a follow-up email with the recording link, and writes attendance into HubSpot for marketing scoring.', modules: ['agent', 'workflows'], category: 'marketing', tags: ['marketing', 'crm'], diff --git a/apps/sim/lib/internal/typeform/operations.ts b/apps/sim/lib/internal/typeform/operations.ts index 0d5ada8984d..5f0e54a4a59 100644 --- a/apps/sim/lib/internal/typeform/operations.ts +++ b/apps/sim/lib/internal/typeform/operations.ts @@ -1,3 +1,4 @@ +import { getErrorMessage } from '@sim/utils/errors' import { secureFetchWithPinnedIP, validateUrlWithDNS, @@ -11,6 +12,7 @@ import { TypeformOperationError } from '@/lib/internal/typeform/errors' import { uploadCopilotFile } from '@/lib/uploads/contexts/copilot' import { uploadExecutionFile } from '@/lib/uploads/contexts/execution' import type { TypeformFilesParams, TypeformFilesResponse } from '@/tools/typeform/types' +import { safeUrlPathSegment } from '@/tools/url-path' const MAX_TYPEFORM_FILE_BYTES = 10 * 1024 * 1024 @@ -22,9 +24,26 @@ export interface TypeformOperationContext { signal?: AbortSignal } +/** Rejects dot segments (which `new URL` would resolve away) before they reach the authenticated request. */ +function typeformPathSegment( + value: string, + paramName: string, + options?: { allowSeparators?: boolean } +): string { + try { + return safeUrlPathSegment(value, paramName, options) + } catch (error) { + throw new TypeformOperationError(getErrorMessage(error, `Invalid ${paramName}`), 400) + } +} + function buildTypeformFileUrl(input: TypeformFilesParams): string { + const formId = typeformPathSegment(input.formId, 'formId') + const responseId = typeformPathSegment(input.responseId, 'responseId') + const fieldId = typeformPathSegment(input.fieldId, 'fieldId') + const filename = typeformPathSegment(input.filename, 'filename', { allowSeparators: true }) const url = new URL( - `https://api.typeform.com/forms/${encodeURIComponent(input.formId)}/responses/${encodeURIComponent(input.responseId)}/fields/${encodeURIComponent(input.fieldId)}/files/${encodeURIComponent(input.filename)}` + `https://api.typeform.com/forms/${formId}/responses/${responseId}/fields/${fieldId}/files/${filename}` ) if (input.inline !== undefined) url.searchParams.set('inline', String(input.inline)) return url.toString() diff --git a/apps/sim/lib/internal/wordpress/operations.ts b/apps/sim/lib/internal/wordpress/operations.ts index 8f2840bed43..a77c033d586 100644 --- a/apps/sim/lib/internal/wordpress/operations.ts +++ b/apps/sim/lib/internal/wordpress/operations.ts @@ -15,6 +15,7 @@ import { import { downloadServableFileFromStorage } from '@/lib/uploads/utils/file.server' import type { RawFileInput } from '@/lib/uploads/utils/file-schemas' import { assertToolFileAccess } from '@/app/api/files/authorization' +import { safeUrlPathSegment } from '@/tools/url-path' import type { WordPressUploadMediaResponse } from '@/tools/wordpress/types' const logger = createLogger('WordPressOperations') @@ -61,6 +62,12 @@ export async function uploadWordPressMedia( if (!input.file) { throw new WordPressOperationError('No file provided. Please upload a file.', 400) } + let siteSegment: string + try { + siteSegment = safeUrlPathSegment(input.siteId, 'siteId') + } catch (error) { + throw new WordPressOperationError(getErrorMessage(error, 'Invalid siteId'), 400) + } let userFile try { userFile = processSingleFileToUserFile(input.file, context.requestId, logger) @@ -97,7 +104,7 @@ export async function uploadWordPressMedia( if (input.altText) formData.append('alt_text', input.altText) if (input.description) formData.append('description', input.description) - const response = await outboundFetch(`${WORDPRESS_COM_API_BASE}/${input.siteId}/media`, { + const response = await outboundFetch(`${WORDPRESS_COM_API_BASE}/${siteSegment}/media`, { method: 'POST', headers: { Authorization: `Bearer ${input.accessToken}` }, body: formData, diff --git a/apps/sim/lib/internal/zoom/operations.test.ts b/apps/sim/lib/internal/zoom/operations.test.ts index c9f840984e7..e49275b537d 100644 --- a/apps/sim/lib/internal/zoom/operations.test.ts +++ b/apps/sim/lib/internal/zoom/operations.test.ts @@ -48,4 +48,19 @@ describe('getZoomMeetingRecordings', () => { expect.objectContaining({ maxResponseBytes: 2 }) ) }) + + it('double encodes a meeting UUID that starts with a slash', async () => { + mockSecureFetchWithPinnedIP.mockResolvedValueOnce(Response.json({ recording_files: [] })) + + await getZoomMeetingRecordings( + { accessToken: 'token', meetingId: '/ajXp112==' }, + { requestId: 'request-1' } + ) + + expect(mockSecureFetchWithPinnedIP).toHaveBeenLastCalledWith( + 'https://api.zoom.us/v2/meetings/%252FajXp112%253D%253D/recordings', + '203.0.113.1', + expect.anything() + ) + }) }) diff --git a/apps/sim/lib/internal/zoom/operations.ts b/apps/sim/lib/internal/zoom/operations.ts index 98ef6429161..deb94fec59a 100644 --- a/apps/sim/lib/internal/zoom/operations.ts +++ b/apps/sim/lib/internal/zoom/operations.ts @@ -12,6 +12,7 @@ import { ZoomOperationError } from '@/lib/internal/zoom/errors' import { MAX_BUFFERED_TRANSFER_BYTES } from '@/lib/uploads/shared/types' import { getExtensionFromMimeType } from '@/lib/uploads/utils/file' import type { ZoomGetMeetingRecordingsParams } from '@/tools/zoom/types' +import { encodeZoomMeetingPathId } from '@/tools/zoom/utils' const logger = createLogger('ZoomOperations') @@ -63,7 +64,7 @@ export async function getZoomMeetingRecordings( query.set('include_folder_items', String(input.includeFolderItems)) } if (input.ttl) query.set('ttl', String(input.ttl)) - const baseUrl = `https://api.zoom.us/v2/meetings/${encodeURIComponent(input.meetingId)}/recordings` + const baseUrl = `https://api.zoom.us/v2/meetings/${encodeZoomMeetingPathId(input.meetingId)}/recordings` const apiUrl = query.size > 0 ? `${baseUrl}?${query}` : baseUrl const validation = await validateUrlWithDNS(apiUrl, 'apiUrl', 'configuredEndpoint') context.signal?.throwIfAborted() diff --git a/apps/sim/tools/brex/create_spend_limit.ts b/apps/sim/tools/brex/create_spend_limit.ts index 37ecbc18957..9a265fcbd4b 100644 --- a/apps/sim/tools/brex/create_spend_limit.ts +++ b/apps/sim/tools/brex/create_spend_limit.ts @@ -120,7 +120,7 @@ export const brexCreateSpendLimitTool: ToolConfig< type: 'number', required: false, visibility: 'user-or-llm', - description: 'Flexible buffer on the limit as a 0-100 percentage', + description: 'Flexible buffer on the limit as a whole-number percentage from 0 to 100', }, description: { type: 'string', diff --git a/apps/sim/tools/brex/get_budget.ts b/apps/sim/tools/brex/get_budget.ts index 8eda3bdfe6d..d74a5807280 100644 --- a/apps/sim/tools/brex/get_budget.ts +++ b/apps/sim/tools/brex/get_budget.ts @@ -74,7 +74,7 @@ export const brexGetBudgetTool: ToolConfig { + it('reads the camelCase accountType Brex returns on CompanyResponse', async () => { + const transform = brexGetCompanyTool.transformResponse + if (!transform) throw new Error('get_company has no transformResponse') + const response = new Response( + JSON.stringify({ + id: 'co_1', + legal_name: 'Acme Inc', + mailing_address: null, + accountType: 'BREX_EMPOWER', + }), + { status: 200, headers: { 'Content-Type': 'application/json' } } + ) + const result = await transform(response) + expect(result.output.accountType).toBe('BREX_EMPOWER') + }) +}) diff --git a/apps/sim/tools/brex/get_company.ts b/apps/sim/tools/brex/get_company.ts index 68a2bbc0e41..6e0dd17411b 100644 --- a/apps/sim/tools/brex/get_company.ts +++ b/apps/sim/tools/brex/get_company.ts @@ -33,7 +33,7 @@ export const brexGetCompanyTool: ToolConfig status: { type: 'string', description: - 'User status (INVITED, ACTIVE, CLOSED, DISABLED, DELETED, PENDING_ACTIVATION, INACTIVE, ARCHIVED)', + 'User status (INVITED, ACTIVE, DISABLED, PENDING_ACTIVATION, INACTIVE, ARCHIVED)', optional: true, }, managerId: { type: 'string', description: 'ID of the manager', optional: true }, diff --git a/apps/sim/tools/brex/list_cards.ts b/apps/sim/tools/brex/list_cards.ts index 3826c48babf..5d96260b2ba 100644 --- a/apps/sim/tools/brex/list_cards.ts +++ b/apps/sim/tools/brex/list_cards.ts @@ -76,7 +76,8 @@ export const brexListCardsTool: ToolConfig = { payment_status: { type: 'string', description: - 'Payment status (NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED)', + 'Payment status (NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED, HELD)', optional: true, }, expense_type: { @@ -911,8 +911,7 @@ export const BREX_USER_PROPERTIES: Record = { email: { type: 'string', description: 'Email address' }, status: { type: 'string', - description: - 'User status (INVITED, ACTIVE, CLOSED, DISABLED, DELETED, PENDING_ACTIVATION, INACTIVE, ARCHIVED)', + description: 'User status (INVITED, ACTIVE, DISABLED, PENDING_ACTIVATION, INACTIVE, ARCHIVED)', optional: true, }, manager_id: { type: 'string', description: 'ID of the manager', optional: true }, diff --git a/apps/sim/tools/brex/update_expense.ts b/apps/sim/tools/brex/update_expense.ts index 511dca67302..90379dfd773 100644 --- a/apps/sim/tools/brex/update_expense.ts +++ b/apps/sim/tools/brex/update_expense.ts @@ -73,7 +73,7 @@ export const brexUpdateExpenseTool: ToolConfig = { @@ -42,7 +43,7 @@ export const cancelBookingTool: ToolConfig { - return `https://api.cal.com/v2/bookings/${encodeURIComponent(params.bookingUid)}/cancel` + return `https://api.cal.com/v2/bookings/${safeUrlPathSegment(params.bookingUid, 'bookingUid')}/cancel` }, method: 'POST', headers: (params) => ({ diff --git a/apps/sim/tools/calcom/confirm_booking.ts b/apps/sim/tools/calcom/confirm_booking.ts index cab2feb3f9c..b9ca4566be6 100644 --- a/apps/sim/tools/calcom/confirm_booking.ts +++ b/apps/sim/tools/calcom/confirm_booking.ts @@ -6,6 +6,7 @@ import { HOSTS_OUTPUT, } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const confirmBookingTool: ToolConfig< CalcomConfirmBookingParams, @@ -38,7 +39,7 @@ export const confirmBookingTool: ToolConfig< request: { url: (params: CalcomConfirmBookingParams) => { - return `https://api.cal.com/v2/bookings/${encodeURIComponent(params.bookingUid)}/confirm` + return `https://api.cal.com/v2/bookings/${safeUrlPathSegment(params.bookingUid, 'bookingUid')}/confirm` }, method: 'POST', headers: (params) => ({ diff --git a/apps/sim/tools/calcom/create_event_type.ts b/apps/sim/tools/calcom/create_event_type.ts index 5a84bfe5627..2e0ed43a03e 100644 --- a/apps/sim/tools/calcom/create_event_type.ts +++ b/apps/sim/tools/calcom/create_event_type.ts @@ -215,6 +215,12 @@ export const createEventTypeTool: ToolConfig< disableGuests: { type: 'boolean', description: 'Whether guests are disabled' }, createdAt: { type: 'string', description: 'ISO timestamp of creation' }, updatedAt: { type: 'string', description: 'ISO timestamp of last update' }, + bookingUrl: { type: 'string', description: 'Public booking page URL for the event type' }, + hidden: { + type: 'boolean', + description: 'Whether the event type is hidden from the profile', + }, + ownerId: { type: 'number', description: 'ID of the user who owns the event type' }, }, }, }, diff --git a/apps/sim/tools/calcom/decline_booking.ts b/apps/sim/tools/calcom/decline_booking.ts index ed7e25cdf2e..e7c159ed570 100644 --- a/apps/sim/tools/calcom/decline_booking.ts +++ b/apps/sim/tools/calcom/decline_booking.ts @@ -6,6 +6,7 @@ import { HOSTS_OUTPUT, } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const declineBookingTool: ToolConfig< CalcomDeclineBookingParams, @@ -44,7 +45,7 @@ export const declineBookingTool: ToolConfig< request: { url: (params: CalcomDeclineBookingParams) => { - return `https://api.cal.com/v2/bookings/${encodeURIComponent(params.bookingUid)}/decline` + return `https://api.cal.com/v2/bookings/${safeUrlPathSegment(params.bookingUid, 'bookingUid')}/decline` }, method: 'POST', headers: (params) => ({ diff --git a/apps/sim/tools/calcom/delete_event_type.ts b/apps/sim/tools/calcom/delete_event_type.ts index 4e703b8559a..c2546ea136e 100644 --- a/apps/sim/tools/calcom/delete_event_type.ts +++ b/apps/sim/tools/calcom/delete_event_type.ts @@ -3,6 +3,7 @@ import type { CalcomDeleteEventTypeResponse, } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const deleteEventTypeTool: ToolConfig< CalcomDeleteEventTypeParams, @@ -35,7 +36,7 @@ export const deleteEventTypeTool: ToolConfig< request: { url: (params: CalcomDeleteEventTypeParams) => - `https://api.cal.com/v2/event-types/${params.eventTypeId}`, + `https://api.cal.com/v2/event-types/${safeUrlPathSegment(params.eventTypeId, 'eventTypeId')}`, method: 'DELETE', headers: (params) => ({ Authorization: `Bearer ${params.accessToken}`, diff --git a/apps/sim/tools/calcom/delete_schedule.ts b/apps/sim/tools/calcom/delete_schedule.ts index 15e9162e889..dab0d5b33d4 100644 --- a/apps/sim/tools/calcom/delete_schedule.ts +++ b/apps/sim/tools/calcom/delete_schedule.ts @@ -1,5 +1,6 @@ import type { CalcomDeleteScheduleParams, CalcomDeleteScheduleResponse } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const deleteScheduleTool: ToolConfig< CalcomDeleteScheduleParams, @@ -32,7 +33,7 @@ export const deleteScheduleTool: ToolConfig< request: { url: (params: CalcomDeleteScheduleParams) => - `https://api.cal.com/v2/schedules/${encodeURIComponent(params.scheduleId)}`, + `https://api.cal.com/v2/schedules/${safeUrlPathSegment(params.scheduleId, 'scheduleId')}`, method: 'DELETE', headers: (params) => ({ Authorization: `Bearer ${params.accessToken}`, diff --git a/apps/sim/tools/calcom/get_booking.ts b/apps/sim/tools/calcom/get_booking.ts index 83dd1cc952e..42925400c0a 100644 --- a/apps/sim/tools/calcom/get_booking.ts +++ b/apps/sim/tools/calcom/get_booking.ts @@ -6,6 +6,7 @@ import { HOSTS_OUTPUT, } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const getBookingTool: ToolConfig = { id: 'calcom_get_booking', @@ -35,7 +36,7 @@ export const getBookingTool: ToolConfig { - return `https://api.cal.com/v2/bookings/${encodeURIComponent(params.bookingUid)}` + return `https://api.cal.com/v2/bookings/${safeUrlPathSegment(params.bookingUid, 'bookingUid')}` }, method: 'GET', headers: (params) => ({ diff --git a/apps/sim/tools/calcom/get_event_type.ts b/apps/sim/tools/calcom/get_event_type.ts index 461db469d53..793dee34f09 100644 --- a/apps/sim/tools/calcom/get_event_type.ts +++ b/apps/sim/tools/calcom/get_event_type.ts @@ -1,5 +1,6 @@ import type { CalcomGetEventTypeParams, CalcomGetEventTypeResponse } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const getEventTypeTool: ToolConfig = { id: 'calcom_get_event_type', @@ -29,7 +30,7 @@ export const getEventTypeTool: ToolConfig - `https://api.cal.com/v2/event-types/${params.eventTypeId}`, + `https://api.cal.com/v2/event-types/${safeUrlPathSegment(params.eventTypeId, 'eventTypeId')}`, method: 'GET', headers: (params) => ({ Authorization: `Bearer ${params.accessToken}`, @@ -69,6 +70,12 @@ export const getEventTypeTool: ToolConfig